text:
<?xml version="1.0"?>
<!--

    Copyright (C) 2014 Thiago Moreira (tmoreira2020@gmail.com)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>br.com.thiagomoreira.liferay.plugins.lorem-ipsum-button-app</groupId>
		<artifactId>hooks</artifactId>
		<version>1.0.1-SNAPSHOT</version>
	</parent>

	<artifactId>lorem-ipsum-button-hook</artifactId>
	<packaging>war</packaging>

	<name>Lorem Ipsum Button Hook</name>
</project>


text:
/**
 * @class glu.extjs.adapters.combo
 * @author Mike Gai
 * @extends glu.extjs.adapters.field
 *
 * The combo box is usually bound by value (by default the backing Model) and to a store.
 *
 * Note : This adapter eliminates race conditions caused by the value being set
 * before the backing store is loaded. When the store changes (a la the backing
 * data arrives), it will check to see if the value is now present and then set the combo
 * box accordingly.
 */

/*
 */
glu.regAdapter('combo', {
    extend : 'field',

    applyConventions: function(config, viewmodel) {
        Ext.applyIf (config, {
            store : glu.conventions.expression(config.name + 'Store', {optional:true})
        });
        glu.provider.adapters.Field.prototype.applyConventions.apply(this, arguments);
    },

    /**
     * @cfg {Ext.data.Store} store
     * The store for this grid.
     *
     * *One-time binding*
     *
     * **Convention**: @{*itemList*}
     */
    beforeCreate : function(config, viewmodel) {
        if (!config.store)
            return;
        if (config.store.gluTweaked == true)
            return;
        config.store.gluTweaked = true;
        var evtName = Ext.getVersion().major > 3 ? 'datachanged' : 'load';
        config.store.on(evtName, function() {
            var control = Ext.getCmp(config.id);
            if (!control)
                return;
            control.setValue(control.targetValue);
        });
    },
    afterCreate : function(control, viewmodel) {
        glu.provider.adapters.Field.prototype.afterCreate.apply(this, arguments);

        if (!control.delayedEvent) {
            control.delayedEvent = new Ext.util.DelayedTask(function() {
                control.fireEvent('valuechanged', control);
            });
        }

        if (control.enableKeyEvents) {
            control.addListener('keyup', function(t, e, o) {
                control.delayedEvent.delay(control.keyDelay || 100);
                //give some time for multiple keypresses...
            }, control);
        }

        if( control.multiSelect ){
            control.addListener('beforedeselect', function(t, e, o) {
                control.delayedEvent.delay(control.keyDelay || 100);
                //give some time for multiple keypresses...
            }, control);
        }

        control.addListener('change', function(t, e, o) {
            control.delayedEvent.delay(control.keyDelay || 100);
            //give some time for multiple keypresses...
        }, control);

        control.addListener('select', function(t, e, o) {
            control.delayedEvent.delay(control.keyDelay || 100);
            //give some time for multiple keypresses...
        }, control);

        //Solves a race condition in which the initial value is set before the backing store has been loaded
        //does not attempt to solve later race conditions with stores reloading
        if (!control.valueField)
            return;
        // var r = control.findRecord(control.valueField, control.value);
        // if(r) {
        // //reset the value one last time just in case the callback has already happened
        // control.setValue(control.value);
        // return;
        // }
        control.setValueActual = control.setValue;
        control.setValue = function(value) {
            this.targetValue = value;
            this.setValueActual(value);
        };
        control.setValue(control.value);
        //there is no record, so wait until load
        // control.store.on('load',function(){
        // control.setValue(control.value);
        // //control.store.un('load'); //stop listening for load event
        // });
    },
    beforeCollect : function(config) {
        glu.provider.adapters.Field.prototype.beforeCollect.apply(this, arguments);
        if (config.editable)
            config.enableKeyEvents = true;
    },
    initAdapter : function() {
        //this.valueBindings = glu.deepApplyIf({eventName : 'select'},this.valueBindings);
        this.valueBindings = glu.deepApplyIf({
            eventName : 'valuechanged'
        }, this.valueBindings);
    }
});

glu.regAdapter('combobox', {
    extend : 'combo'
});

redpajama_set_name: RedPajamaGithub


text:
VariableType::VariableType(DataExtractor *next, ConcreteTableColumn *prototype, VariableDeclaration *condition, TypesTable *types):DataExtractor(next,prototype,condition) {

	this->types = types;

}

TableColumn* VariableType::handleExtraction(AbstractTree &tree) {

	TableColumn *column = prototype->clone();
	std::vector<std::string> usedTypes;
	FindSignature type;
	FindClassContext the_context;
	SetOperations set_operation;
	std::string name,mycontext;
	std::string typeName = "TypeName";
	std::string contextCol = "Context";
	Table::RowSet *set1,*set2,*set3;
	int id;
	char buff[12];

	//Check for return type
	name = type.findVariable(tree.tree,&usedTypes);

	//Check for ID
	if(name != "") {
		mycontext = the_context.find(the_context.find(tree.tree),&usedTypes,types);
		set1 = types->find_set(typeName,name);
		if(set1->size() == 1) {
			id = types->find_id(*set1->begin());
			sprintf(buff,"%d",id);
			name = buff;
			delete set1;
		} else {
			set2 = types->find_set(contextCol,mycontext);
			set3 = set_operation.intersection_op(set1,set2);
			delete set1;
			delete set2;
			if(set3->size() == 1) {
				id = types->find_id(*set3->begin());
				sprintf(buff,"%d",id);
				name = buff;
			} else {
				name = "<ERROR>";
			}
			delete set3;
		}
	} else {
		name = "<NO_ONE>";
	}
	column->init(name,false);
	return column;
}


text:
using System.Collections.Generic;

namespace ExtraLinq
{
    public static partial class EnumerableExtensions
    {
        /// <summary>
        /// Turns a finite sequence into a circular one, or equivalently,
        /// repeats the original sequence indefinitely.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
        /// <param name="source">An <see cref="IEnumerable{T}"/> to cycle through.</param>
        /// <returns>An infinite sequence cycling through the given sequence.</returns>
        public static IEnumerable<TSource> Cycle<TSource>(this IEnumerable<TSource> source)
        {
            ThrowIf.Argument.IsNull(source, "source");

            return CycleIterator(source);
        }

        private static IEnumerable<TSource> CycleIterator<TSource>(IEnumerable<TSource> source)
        {
            var collection = source as ICollection<TSource>;

            var elementBuffer = collection == null
                ? new List<TSource>()
                : new List<TSource>(collection.Count);

            foreach (TSource element in source)
            {
                yield return element;

                // We add this element to a local element buffer so that
                // we don't have to enumerate the sequence multiple times
                elementBuffer.Add(element);
            }

            if (elementBuffer.IsEmpty())
            {
                // If the element buffer is empty, so was the source sequence.
                // In this case, we can stop here and simply return an empty sequence.
                yield break;
            }

            int index = 0;
            while (true)
            {
                yield return elementBuffer[index];
                index = (index + 1) % elementBuffer.Count;
            }
        }
    }
}


text:
function UnityProgress(gameInstance, progress) {
  if (!gameInstance.Module)
    return;
  if (!gameInstance.logo) {
    gameInstance.logo = document.createElement("div");
    gameInstance.logo.className = "logo " + gameInstance.Module.splashScreenStyle;
    gameInstance.container.appendChild(gameInstance.logo);
  }
  if (!gameInstance.progress) {
    gameInstance.progress = document.createElement("div");
    gameInstance.progress.className = "progress " + gameInstance.Module.splashScreenStyle;
    gameInstance.progress.empty = document.createElement("div");
    gameInstance.progress.empty.className = "empty";
    gameInstance.progress.appendChild(gameInstance.progress.empty);
    gameInstance.progress.full = document.createElement("div");
    gameInstance.progress.full.className = "full";
    gameInstance.progress.appendChild(gameInstance.progress.full);
    gameInstance.container.appendChild(gameInstance.progress);
  }
  gameInstance.progress.full.style.width = (100 * progress) + "%";
  gameInstance.progress.empty.style.width = (100 * (1 - progress)) + "%";
  if (progress == 1)
    gameInstance.logo.style.display = gameInstance.progress.style.display = "none";
}


text:
/**
 */
package de.uni_hildesheim.sse.vil.expressions.expressionDsl.impl;

import de.uni_hildesheim.sse.vil.expressions.expressionDsl.ExpressionDslPackage;
import de.uni_hildesheim.sse.vil.expressions.expressionDsl.PostfixExpression;
import de.uni_hildesheim.sse.vil.expressions.expressionDsl.UnaryExpression;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

/**
 *
 * An implementation of the model object 'Unary Expression'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link de.uni_hildesheim.sse.vil.expressions.expressionDsl.impl.UnaryExpressionImpl#getOp Op}

 *
{@link de.uni_hildesheim.sse.vil.expressions.expressionDsl.impl.UnaryExpressionImpl#getExpr Expr}

 *

 *
 * @generated
 */
public class UnaryExpressionImpl extends MinimalEObjectImpl.Container implements UnaryExpression
{
  /**
   * The default value of the '{@link #getOp() Op}' attribute.
   *
   *
   * @see #getOp()
   * @generated
   * @ordered
   */
  protected static final String OP_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getOp() Op}' attribute.
   *
   *
   * @see #getOp()
   * @generated
   * @ordered
   */
  protected String op = OP_EDEFAULT;

  /**
   * The cached value of the '{@link #getExpr() Expr}' containment reference.
   *
   *
   * @see #getExpr()
   * @generated
   * @ordered
   */
  protected PostfixExpression expr;

  /**
   *
   *
   * @generated
   */
  protected UnaryExpressionImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return ExpressionDslPackage.Literals.UNARY_EXPRESSION;
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String getOp()
  {
    return op;
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void setOp(String newOp)
  {
    String oldOp = op;
    op = newOp;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, ExpressionDslPackage.UNARY_EXPRESSION__OP, oldOp, op));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public PostfixExpression getExpr()
  {
    return expr;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetExpr(PostfixExpression newExpr, NotificationChain msgs)
  {
    PostfixExpression oldExpr = expr;
    expr = newExpr;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ExpressionDslPackage.UNARY_EXPRESSION__EXPR, oldExpr, newExpr);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void setExpr(PostfixExpression newExpr)
  {
    if (newExpr != expr)
    {
      NotificationChain msgs = null;
      if (expr != null)
        msgs = ((InternalEObject)expr).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ExpressionDslPackage.UNARY_EXPRESSION__EXPR, null, msgs);
      if (newExpr != null)
        msgs = ((InternalEObject)newExpr).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ExpressionDslPackage.UNARY_EXPRESSION__EXPR, null, msgs);
      msgs = basicSetExpr(newExpr, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, ExpressionDslPackage.UNARY_EXPRESSION__EXPR, newExpr, newExpr));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case ExpressionDslPackage.UNARY_EXPRESSION__EXPR:
        return basicSetExpr(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case ExpressionDslPackage.UNARY_EXPRESSION__OP:
        return getOp();
      case ExpressionDslPackage.UNARY_EXPRESSION__EXPR:
        return getExpr();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case ExpressionDslPackage.UNARY_EXPRESSION__OP:
        setOp((String)newValue);
        return;
      case ExpressionDslPackage.UNARY_EXPRESSION__EXPR:
        setExpr((PostfixExpression)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case ExpressionDslPackage.UNARY_EXPRESSION__OP:
        setOp(OP_EDEFAULT);
        return;
      case ExpressionDslPackage.UNARY_EXPRESSION__EXPR:
        setExpr((PostfixExpression)null);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case ExpressionDslPackage.UNARY_EXPRESSION__OP:
        return OP_EDEFAULT == null ? op != null : !OP_EDEFAULT.equals(op);
      case ExpressionDslPackage.UNARY_EXPRESSION__EXPR:
        return expr != null;
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuilder result = new StringBuilder(super.toString());
    result.append(" (op: ");
    result.append(op);
    result.append(')');
    return result.toString();
  }

} //UnaryExpressionImpl


text:
Creates one or more Elastic load balancers and configures them with a proxy protocol policy.  This role also installs the AWSCLI to properly configure the buckets

## Installation

``` bash
$ ansible-galaxy install https://github.com/crushlovely/ansible-elb.git
```
## Variables

You will want to fill all these in before running the role.

``` yaml
app_name: test
server_env: qa
aws_access_key: ""
aws_secret_key: ""
aws_elb:
  - port: 80
aws_vpc_subnets:
  - "\"subnet-xxxxxxx\""
  - "\"subnet-xxxxxxx\""
  - "\"subnet-xxxxxxx\""
  - "\"subnet-xxxxxxx\""
```
You can also add a vars folder to your project folder and have your variables served by adding them to a file and calling it in your playbook.

```yaml
- hosts: localhost
...
  vars_files:
    - vars/aws_vars.yml
    - vars/default_vars.yml
...
```
## Usage

Once this role is installed on your system, include it in the roles list of your playbook.

``` yaml
- hosts: localhost
  connection: local
  gather_facts: True
  roles:
    - ansible-elb
```

## Dependencies

None

## License

MIT


text:
Usually, if something in Metasploit triggers an error, there is a backtrace or at least a brief message that explains what the problem is about. Most of the time, there is nothing wrong with that. But sometimes if you wish to report that problem, you might lose that information, which makes your bug report less informative, and the problem may take much longer to solve. This is why logging to file in many cases is extremely useful. In this documentation, we'll explain about how to take advantage of this properly.

## Basic Usage

As an user, you should know that all the logged errors are saved in a file named **framework.log**. The save path is defined in Msf::Config.log_directory, which means in msfconsole, you can switch to irb and figure out where it is:

```
msf > irb
[*] Starting IRB shell...

>> Msf::Config.log_directory
=> "/Users/test/.msf4/logs"
```

By default, all the log errors are on level 0 - the least informative level. But of course, you can change this by setting the datastore option, like this:

```
msf > setg LogLevel 3
LogLevel => 3
msf >
```

## Log Levels

There are 4 different logging levels defined in [log/rex/constants.rb](https://github.com/rapid7/metasploit-framework/blob/master/lib/rex/constants.rb):

Log Level | Description
--------- | -----------
LEV_0 (Default) | The default log level if none is specified. It should be used when a log message should always be displayed when logging is enabled. Very few log messages should occur at this level aside from necessary information logging and error/warning logging.  Debug logging at level zero is not advised.
LEV_1 (Extra) | This log level should be used when extra information may be needed to understand the cause of an error or warning message or to get debugging information that might give clues as to why something is happening. This log level should be used only when information may be useful to understanding the behavior of something at a basic level.  This log level should not be used in an exhaustively verbose fashion.
LEV_2 (Verbose) | This log level should be used when verbose information may be needed to analyze the behavior of the framework.  This should be the default log level for all detailed information not falling into LEV_0 or LEV_1. It is recommended that this log level be used by default if you are unsure.
LEV_3 (Insanity) | This log level should contain very verbose information about the behavior of the framework, such as detailed information about variable states at certain phases including, but not limited to, loop iterations, function calls, and so on.  This log level will rarely be displayed, but when it is the information provided should make it easy to analyze any problem.

For debugging purposes, it's always better to turn on the highest level of logging.

## Logging API

There are mainly five logging methods you will most likely be using a lot, and they all have the exact same arguments. Let's use one of the logging methods to explain what these arguments are about:

```
def elog(msg, src = 'core', level = 0, from = caller)
```

* msg - The message you want to log
* src - The source of the error (default is core, as in Metasploit core)
* level - The log level
* from - The current execution stack. caller is a method from [Kernel](http://www.ruby-doc.org/core-2.1.3/Kernel.html#method-i-caller).

Notice that only the ```msg``` argument is required, the rest are optional.

Now, let's go over these five methods and explain how they're meant to be used:

Method | Purpose
------ | -------
dlog() | LOG_DEBUG
elog() | LOG_ERROR
wlog() | LOG_WARN
ilog() | LOG_INFO
rlow() | LOG_RAW

## Code Example

```ruby
elog("The sky has fallen")
```


text:
import * as classNames from "classnames";
import * as PureRender from "pure-render-decorator";
import * as React from "react";

import { Classes, IIntentProps, IProps } from "../../common";
import { IconName } from "../icon/icon";

/** This component also supports the full range of HTML `<div>` props. */
export interface ICalloutProps extends IIntentProps, IProps {
    /** Name of icon to render on left-hand side. */
    iconName?: IconName;

    /**
     * String content of optional title element.
     *
     * Due to a conflict with the HTML prop types, to provide JSX content simply pass
     * `<h5>JSX title content<h5>` as first `children` element instead of using this prop.
     */
    title?: string;
}

@PureRender
export class Callout extends React.Component<ICalloutProps & React.HTMLAttributes<HTMLDivElement>, {}> {
    public render() {
        const { className, children, iconName, intent, title, ...htmlProps } = this.props;
        const classes = classNames(
            Classes.CALLOUT,
            Classes.intentClass(intent),
            Classes.iconClass(iconName),
            className,
        );
        return (

                {title &&
{title}
}
                {children}

        );
    }
}


text:
var worldcupApp  = angular.module('worldcup2015', [])
    .factory('_', function() {
        return window._; // assumes underscore has already been loaded on the page
    })
    .factory('moment', function() {
        return window.moment;
    });

worldcupApp.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

worldcupApp
    .controller('ScheduleCtrl', [ '$scope', 'MatchesSvc', '_', '$log', 'moment', function ($scope, MatchesSvc, _, $log, moment) {
        'use strict';

        $scope.timeFlag = false;
        $scope.toggleTimeFlag = function() {
            $scope.timeFlag = !$scope.timeFlag;
        }

        $scope.teamsInPool = function(pool){
            var result = [];
            for(var i= 0, team; team = $scope.teams[i]; i++) {
                if(team.pool === pool) {
                    result.push(team);
                }
            }

            var sortedResult = _(result).chain().sortBy('nrr').sortBy('pts').reverse().value();
            return sortedResult;
        };

        MatchesSvc.getAllMatches()
            .success(function(response){

                MatchesSvc.setMatches(response.matches);

                $scope.teams = response.teams;
                $scope.poolATeams = $scope.teamsInPool('A');
                $scope.poolBTeams = $scope.teamsInPool('B');

                $scope.dates = MatchesSvc.getAllMatchDates();

                $scope.venues = MatchesSvc.getAllVenues();

                $scope.showTodaysMatches = function() {
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth()+1;
                    var yyyy = today.getFullYear();
                    if(dd<10) {
                        dd='0'+dd
                    }

                    if(mm<10) {
                        mm='0'+mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    $scope.onDateSelect(today);
                    highlightDatesForSelectedMatches();
                };

                $scope.showTodaysMatches();
        });

        $scope.month = function(date) {
            return date.substr(6,1) === '2' ? 'Feb' : 'Mar';
        };
        $scope.dateOfMonth = function(date) {
            return date.substr(8,2);
        };

        $scope.getTime = function(match) {
            if ($scope.timeFlag) {
                return $scope.month(match.match_date).toUpperCase()
                    + " " + $scope.dateOfMonth(match.match_date).toUpperCase()
                    + " " + match.start_time.toUpperCase();
            } else {
                return moment(match.match_datetime).format("MMM DD hh:mm A").toUpperCase();
            }
        };

        $scope.selectedMatches = {};

        $scope.onDateSelect = function(date, staySelected) {
            staySelected = staySelected || false;
            if(!$scope.staySelected && staySelected) {
                $scope.staySelected = true;
            }

            $scope.deselectAll();

            $scope.selectedMatches = MatchesSvc.getMatchesForDate(date);
            highlightTeamsForSelectedMatches();
            highlightVenuesForSelectedMatches();
        };

        var highlightDatesForSelectedMatches = function() {
            $scope.dates = _.map($scope.dates, function(date) {
                _.each($scope.selectedMatches, function(match) {
                    if(match.match_date === date.date) {
                        date.selected = true;
                    }
                });
                return date;
            });
        };

        var highlightTeamsForSelectedMatches = function() {
            $scope.teams = _.map($scope.teams, function(team) {
                _.each($scope.selectedMatches, function(match) {
                    if(match.team_one_long === team.name || match.team_two_long === team.name) {
                        team.selected = true;
                    }
                });
                return team;
            });
        };

        var highlightVenuesForSelectedMatches = function() {
            $scope.venues = _.map($scope.venues, function(venue) {
                _.each($scope.selectedMatches, function(match) {
                    if(match.city === venue.city) {
                        venue.selected = true;
                    }
                });
                return venue;
            });
        };

        $scope.onTeamSelect = function(team, staySelected) {
            staySelected = staySelected || false;
            if(!$scope.staySelected && staySelected) {
                $scope.staySelected = true;
            }
            $scope.deselectAll();
            $scope.selectedMatches = MatchesSvc.getMatchesForTeam(team);
            highlightDatesForSelectedMatches();
            highlightVenuesForSelectedMatches();
        };

        $scope.onVenueSelect = function(venue, staySelected) {
            staySelected = staySelected || false;
            if(!$scope.staySelected && staySelected) {
                $scope.staySelected = true;
            }
            $scope.deselectAll();
            $scope.selectedMatches = MatchesSvc.getMatchesForVenue(venue);
            highlightDatesForSelectedMatches();
            highlightTeamsForSelectedMatches();
        };

        $scope.deselectAll = function() {
            if(!$scope.staySelected) {
                $scope.selectedMatches = {};
            }

            for(var i= 0, date; date = $scope.dates[i];i++) {
                date.selected = false;
            }
            for(var i= 0, team; team = $scope.teams[i];i++) {
                team.selected = false;
            }
            for(var i= 0, venue; venue = $scope.venues[i];i++) {
                venue.selected = false;
            }
        };

    }]
);


text:
<?php
// Home

Route::get('/',
	array(
		'as' => 'home',
		'uses' => 'HomeController@showWelcome'
	)
);

// get Add Article

Route::get('article/read/{id?}',
	array(
		'uses' => 'ArticleController@readAddArticle'
		)
	);

// Unauthenticated group

Route::group(array('before' => 'guest'), function() {

	// CSRF protection group

	Route::group(array('before' => 'csrf'), function() {

		// Sign In post

		Route::post('account/sign-in',
			array(
				'as' => 'sign-in-post',
				'uses' => 'AccountController@postSignIn'
			)
		);

		// Sign Up post

		Route::post('account/sign-up',
			array(
				'as' => 'sign-up-post',
				'uses' => 'AccountController@postSignUp'
			)
		);

		// Forgot password post

		Route::post('account/forgot-password',
			array(
				'as' => 'forgot-password-post',
				'uses' => 'AccountController@postForgotPassword'
			)
		);

	});

	// Sign In

	Route::get('account/sign-in',
		array(
			'as' => 'sign-in',
			'uses' => 'AccountController@getSignIn'
		)
	);

	// Sign Up

	Route::get('account/sign-up',
		array(
			'as' => 'sign-up',
			'uses' => 'AccountController@getSignUp'
		)
	);

	// Forgot password

	Route::get('account/forgot-password',
		array(
			'as' => 'forgot-password',
			'uses' => 'AccountController@getForgotPassword'
		)
	);

	Route::get('login/fb', function() {
	    $facebook = new Facebook(Config::get('facebook'));
	    $params = array(
	        'redirect_uri' => url('/login/fb/callback'),
	        'scope' => 'email',
	    );
	    return Redirect::to($facebook->getLoginUrl($params));
	});

	Route::get('login/fb/callback', function() {
	    $code = Input::get('code');
	    if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');

	    $facebook = new Facebook(Config::get('facebook'));
	    $uid = $facebook->getUser();

	    if ($uid == 0) return Redirect::to('/')->with('error', 'There was an error');

	    $me = $facebook->api('/me');

	    $user = User::where('facebook_id', '=', $me['id']);
		$user = $user->first();
	    if (!$user) {
			$user = array(
				'name' => $me['name'],
				'email' => $me['email'],
				'facebook_id' => $me['id']
			);
			User::create($user);
	    }

	    $user = User::where('facebook_id', '=', $me['id']);
		$user = $user->first();
	    // print_r($user);
	    Auth::login($user);

	    return Redirect::route('home');
	});
});

// Authenticated group

Route::group(array('before' => 'auth'), function() {

	// CSRF protection group

	Route::group(array('before' => 'csrf'), function() {

		// Change password post

		Route::post('account/change-password',
			array(
				'as' => 'change-password-post',
				'uses' => 'AccountController@postChangePassword'
			)
		);

	});

	// Sign Out

	Route::get('account/sign-out',
		array (
			'as' => 'sign-out',
			'uses' => 'AccountController@getSignOut'
		)
	);

	// Change password

	Route::get('account/change-password',
		array(
			'as' => 'change-password',
			'uses' => 'AccountController@getChangePassword'
		)
	);

	// get Add Article

	Route::get('article/add',
		array(
			'as' => 'add',
			'uses' => 'ArticleController@getAddArticle'
		)
	);

	// Post Add Article

	Route::post('article/add',
		array(
			'as' => 'add-post',
			'uses' => 'ArticleController@postAddArticle'
		)
	);

	// get Add Article

	Route::get('article/edit/{id?}',
		array(
			'uses' => 'ArticleController@getEditArticle'
		)
	);

	// Post Add Article

	Route::post('article/edit/{id?}',
		array(
			'uses' => 'ArticleController@postEditArticle'
		)
	);

	// Post Add Article

	Route::get('article/delete/{id?}',
		array(
			'uses' => 'ArticleController@destroyArticle'
		)
	);
});

App::error(function($exception, $code)
{
    switch ($code)
    {
        case 403:
            return Response::view('errors.403', array(), 403);

        case 404:
            return Response::view('errors.404', array(), 404);

        case 500:
            return Response::view('errors.500', array(), 500);

        default:
            return Response::view('errors.default', array(), $code);
    }
});


text:
package org.apache.camel.component.telegram;

import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.telegram.model.OutgoingTextMessage;
import org.apache.camel.component.telegram.util.TelegramMockRoutes;
import org.apache.camel.component.telegram.util.TelegramMockRoutes.MockProcessor;
import org.apache.camel.component.telegram.util.TelegramTestSupport;
import org.apache.camel.component.telegram.util.TelegramTestUtil;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

/**
 * Tests a producer route with a fixed destination.
 */
public class TelegramProducerChatIdResolutionTest extends TelegramTestSupport {

    @EndpointInject("direct:telegram")
    private Endpoint endpoint;

    @Test
    public void testRouteWithFixedChatId() throws Exception {
        final MockProcessor<OutgoingTextMessage> mockProcessor = getMockRoutes().getMock("sendMessage");
        mockProcessor.clearRecordedMessages();

        template.sendBody(endpoint, "Hello");

        final OutgoingTextMessage message = mockProcessor.awaitRecordedMessages(1, 5000).get(0);
        assertEquals("my-id", message.getChatId());
        assertEquals("Hello", message.getText());
        assertNull(message.getParseMode());
    }

    @Test
    public void testRouteWithOverridenChatId() throws Exception {
        final MockProcessor<OutgoingTextMessage> mockProcessor = getMockRoutes().getMock("sendMessage");
        mockProcessor.clearRecordedMessages();

        Exchange exchange = endpoint.createExchange();
        exchange.getIn().setBody("Hello 2");
        exchange.getIn().setHeader(TelegramConstants.TELEGRAM_CHAT_ID, "my-second-id");

        template.send(endpoint, exchange);

        final OutgoingTextMessage message = mockProcessor.awaitRecordedMessages(1, 5000).get(0);
        assertEquals("my-second-id", message.getChatId());
        assertEquals("Hello 2", message.getText());
        assertNull(message.getParseMode());

    }

    @Override
    protected RoutesBuilder[] createRouteBuilders() throws Exception {
        return new RoutesBuilder[] {
                getMockRoutes(),
                new RouteBuilder() {
                    @Override
                    public void configure() throws Exception {
                        from("direct:telegram")
                                .to("telegram:bots?authorizationToken=mock-token&chatId=my-id");
                    }
                } };
    }

    @Override
    protected TelegramMockRoutes createMockRoutes() {
        return new TelegramMockRoutes(port)
                .addEndpoint(
                        "sendMessage",
                        "POST",
                        OutgoingTextMessage.class,
                        TelegramTestUtil.stringResource("messages/send-message.json"));
    }
}


text:
namespace spdlog {
namespace sinks {

template<typename ConsoleMutex>
SPDLOG_INLINE wincolor_sink<ConsoleMutex>::wincolor_sink(HANDLE out_handle, color_mode mode)
    : out_handle_(out_handle)
    , mutex_(ConsoleMutex::mutex())
    , formatter_(details::make_unique<spdlog::pattern_formatter>())
{
    // check if out_handle is points to the actual console.
    // ::GetConsoleMode() should return 0 if it is redirected or not valid console handle.
    DWORD console_mode;
    in_console_ = ::GetConsoleMode(out_handle, &console_mode) != 0;

    set_color_mode(mode);
    colors_[level::trace] = WHITE;
    colors_[level::debug] = CYAN;
    colors_[level::info] = GREEN;
    colors_[level::warn] = YELLOW | BOLD;
    colors_[level::err] = RED | BOLD;                         // red bold
    colors_[level::critical] = BACKGROUND_RED | WHITE | BOLD; // white bold on red background
    colors_[level::off] = 0;
}

template<typename ConsoleMutex>
SPDLOG_INLINE wincolor_sink<ConsoleMutex>::~wincolor_sink()
{
    this->flush();
}

// change the color for the given level
template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color(level::level_enum level, WORD color)
{
    std::lock_guard<mutex_t> lock(mutex_);
    colors_[level] = color;
}

template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::log(const details::log_msg &msg)
{
    std::lock_guard<mutex_t> lock(mutex_);
    memory_buf_t formatted;
    formatter_->format(msg, formatted);
    if (!in_console_)
    {
        write_to_file_(formatted);
        return;
    }

    if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
    {
        // before color range
        print_range_(formatted, 0, msg.color_range_start);

        // in color range
        auto orig_attribs = set_foreground_color_(colors_[msg.level]);
        print_range_(formatted, msg.color_range_start, msg.color_range_end);
        // reset to orig colors
        ::SetConsoleTextAttribute(out_handle_, orig_attribs);
        print_range_(formatted, msg.color_range_end, formatted.size());
    }
    else // print without colors if color range is invalid (or color is disabled)
    {
        print_range_(formatted, 0, formatted.size());
    }
}

template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::flush()
{
    // windows console always flushed?
}

template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_pattern(const std::string &pattern)
{
    std::lock_guard<mutex_t> lock(mutex_);
    formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
}

template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
{
    std::lock_guard<mutex_t> lock(mutex_);
    formatter_ = std::move(sink_formatter);
}

template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color_mode(color_mode mode)
{
    switch (mode)
    {
    case color_mode::always:
    case color_mode::automatic:
        should_do_colors_ = true;
        break;
    case color_mode::never:
        should_do_colors_ = false;
        break;
    default:
        should_do_colors_ = true;
    }
}

// set foreground color and return the orig console attributes (for resetting later)
template<typename ConsoleMutex>
WORD SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_foreground_color_(WORD attribs)
{
    CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info;
    ::GetConsoleScreenBufferInfo(out_handle_, &orig_buffer_info);
    WORD back_color = orig_buffer_info.wAttributes;
    // retrieve the current background color
    back_color &= static_cast<WORD>(~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY));
    // keep the background color unchanged
    ::SetConsoleTextAttribute(out_handle_, attribs | back_color);
    return orig_buffer_info.wAttributes; // return orig attribs
}

// print a range of formatted message to console
template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end)
{
    auto size = static_cast<DWORD>(end - start);
    ::WriteConsoleA(out_handle_, formatted.data() + start, size, nullptr, nullptr);
}

template<typename ConsoleMutex>
void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::write_to_file_(const memory_buf_t &formatted)
{
    if (out_handle_ == nullptr) // no console and no file redirect
    {
        return;
    }
    auto size = static_cast<DWORD>(formatted.size());
    if (size == 0)
    {
        return;
    }

    DWORD total_written = 0;
    do
    {
        DWORD bytes_written = 0;
        bool ok = ::WriteFile(out_handle_, formatted.data() + total_written, size - total_written, &bytes_written, nullptr) != 0;
        if (!ok || bytes_written == 0)
        {
            SPDLOG_THROW(spdlog_ex("wincolor_sink: write_to_file_ failed. GetLastError(): " + std::to_string(::GetLastError())));
        }
        total_written += bytes_written;
    } while (total_written < size);
}

// wincolor_stdout_sink
template<typename ConsoleMutex>
SPDLOG_INLINE wincolor_stdout_sink<ConsoleMutex>::wincolor_stdout_sink(color_mode mode)
    : wincolor_sink<ConsoleMutex>(::GetStdHandle(STD_OUTPUT_HANDLE), mode)
{}

// wincolor_stderr_sink
template<typename ConsoleMutex>
SPDLOG_INLINE wincolor_stderr_sink<ConsoleMutex>::wincolor_stderr_sink(color_mode mode)
    : wincolor_sink<ConsoleMutex>(::GetStdHandle(STD_ERROR_HANDLE), mode)
{}

} // namespace sinks
} // namespace spdlog


text:
package de.learnlib.alex.integrationtests.websocket.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

public abstract class WSMessages {

    protected final ObjectMapper objectMapper = new ObjectMapper();

    protected String createContent(List<Long> projectIds) {
        final var projects = objectMapper.createArrayNode();
        projectIds.forEach(projects::add);
        final var content = objectMapper.createObjectNode();
        content.set("projectIds", projects);
        return content.toString();
    }
}


text:
package com.yunjuanyunshu.util;

import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.yunjuanyunshu.Entity.ClassEntry;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hansong.xhs
 * @version $Id: CodeMakerUtil.java, v 0.1 2017-01-20 10:15 hansong.xhs Exp $$
 */
public class CodeMakerUtil {

    public static Logger getLogger(Class clazz) {
        return Logger.getInstance(clazz);
    }

    public static PsiClass chooseClass(Project project, PsiClass defaultClass) {
        TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project)
            .createProjectScopeChooser("Select a class", defaultClass);

        chooser.showDialog();

        return chooser.getSelected();
    }

    public static String getSourcePath(PsiClass clazz) {
        String classPath = clazz.getContainingFile().getVirtualFile().getPath();
        return classPath.substring(0, classPath.lastIndexOf('/'));
    }

    public static String getSourceBasePath(Project project) {

        return  project.getBasePath();
        //String classPath = project.getProjectFilePath();
        //return classPath.substring(0, classPath.lastIndexOf('/'));
    }

    public static String generateClassPath(String sourcePath, String className) {
        return sourcePath + "/" + className + ".java";
    }

    public static String generateClassPath(Project project,String packagePath, String className) {
        return project.getBasePath() + "/src/" + packagePath.replace(".","/") +"/" + className;
    }

    public static String generateClassRootPath(Project project) {
        return project.getBasePath() + "/src";
    }

    /**
     * Gets the javafile that's currently selected in the editor. Returns null if it's not a java file.
     *
     * @param dataContext data context.
     * @return The current javafile. Null if not a javafile.
     */
    public static PsiJavaFile getSelectedJavaFile(DataContext dataContext) {
        final PsiFile psiFile = (PsiFile) dataContext.getData("psi.File");

        if (!(psiFile instanceof PsiJavaFile)) {
            return null;
        } else {
            return (PsiJavaFile) psiFile;
        }
    }

    public static List<String> getImportList(PsiJavaFile javaFile) {
        PsiImportList importList = javaFile.getImportList();
        if (importList == null) {
            return new ArrayList<>();
        }
        return Arrays.stream(importList.getImportStatements())
            .map(PsiImportStatement::getQualifiedName).collect(Collectors.toList());
    }

    public static List<ClassEntry.Field> getFields(PsiClass psiClass) {
        return Arrays
            .stream(psiClass.getFields())
            .map(
                psiField -> new ClassEntry.Field(psiField.getType().getPresentableText(), psiField
                    .getName(), psiField.getModifierList() == null ? "" : psiField
                    .getModifierList().getText())).collect(Collectors.toList());
    }

    public static List<ClassEntry.Method> getMethods(PsiClass psiClass) {
        return Arrays
            .stream(psiClass.getMethods())
            .map(
                psiMethod -> {
                    String returnType = psiMethod.getReturnType() == null ? "" : psiMethod
                        .getReturnType().getPresentableText();
                    return new ClassEntry.Method(psiMethod.getName(), psiMethod.getModifierList()
                        .getText(), returnType, psiMethod.getParameterList().getText());
                }).collect(Collectors.toList());
    }

    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }

        int length = str.length();

        for (int i = 0; i < length; i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }
}


text:
using NUnit.Framework;
using Should;
using SpecEasy.Specs.SutLifetime.SupportingExamples;

namespace SpecEasy.Specs.SutLifetime
{
    internal sealed class SutSetterAndConstructSutSpec : Spec<SutWithValueTypeDependency>
    {
        protected override SutWithValueTypeDependency ConstructSUT()
        {
            return new SutWithValueTypeDependency(456);
        }

        public void Run()
        {
            var value = 0;

            When("getting value from SUT", () => value = SUT.Value);

            Given($"{nameof(ConstructSUT)} has been overriden to directly construct an instance").Verify(() =>
                Then($"it should get the value used in {nameof(ConstructSUT)}", () => value.ShouldEqual(456)).
                Then("the resolved instance is the same instance as the SUT property", () => Assert.IsTrue(ReferenceEquals(SUT, Get<SutWithValueTypeDependency>()))));

            Given("SUT has been explicitly set", () => SUT = new SutWithValueTypeDependency(123)).Verify(() =>
                Then("it should get the value provided when the SUT was explicitly set", () => value.ShouldEqual(123)).
                Then("the resolved instance is the same instance as the SUT property", () => Assert.IsTrue(ReferenceEquals(SUT, Get<SutWithValueTypeDependency>()))));
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Class: Logger</title>

    <meta property="og:title" content="MongoDB Driver API for Node.js"/>
    <meta property="og:type" content="website"/>
    <meta property="og:image" content=""/>

    <meta property="og:url" content=""/>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="styles/jaguar.css">

Node.js MongoDB Driver API

        <input id="search" type="text" class="form-control input-sm" placeholder="Search Documentations">

                Admin

            Typedefs

resultCallback

            Methods

addUser

buildInfo

command

listDatabases

ping

removeUser

replSetGetStatus

serverInfo

serverStatus

validateCollection

                AggregationCursor

            Typedefs

endCallback

iteratorCallback

resultCallback

toArrayResultCallback

            Methods

batchSize

clone

close

each

explain

forEach

geoNear

group

hasNext

isClosed

limit

lookup

match

maxTimeMS

next

out

pause

pipe

project

read

redact

resume

rewind

setEncoding

skip

sort

toArray

unpipe

unshift

unwind

wrap

            Events

close

data

end

readable

                AutoEncrypter

            Members

logLevel

            Typedefs

AutoEncryptionExtraOptions

AutoEncryptionOptions

logger

                Binary

            Members

SUBTYPE_BYTE_ARRAY

SUBTYPE_DEFAULT

SUBTYPE_FUNCTION

SUBTYPE_MD5

SUBTYPE_USER_DEFINED

SUBTYPE_UUID

SUBTYPE_UUID_OLD

            Methods

length

put

read

value

write

                BSONRegExp

                BulkOperationBase

            Typedefs

resultCallback

            Methods

execute

find

insert

raw

                BulkWriteError

            Members

errmsg

            Methods

hasErrorLabel

                BulkWriteResult

            Members

nInserted

nMatched

nModified

nRemoved

nUpserted

ok

            Methods

getInsertedIds

getLastOp

getRawResponse

getUpsertedIdAt

getUpsertedIds

getWriteConcernError

getWriteErrorAt

getWriteErrorCount

getWriteErrors

hasWriteErrors

isOk

toJSON

toString

                ChangeStream

            Members

resumeToken

            Typedefs

resultCallback

            Methods

close

hasNext

isClosed

next

pause

pipe

resume

stream

unpipe

            Events

change

close

end

error

resumeTokenChanged

                ClientEncryption

            Typedefs

createDataKeyCallback

dataKeyId

decryptCallback

encryptCallback

            Methods

createDataKey

decrypt

encrypt

                ClientSession

            Members

id

            Methods

abortTransaction

advanceOperationTime

commitTransaction

endSession

equals

incrementTransactionNumber

inTransaction

startTransaction

withTransaction

                Code

                Collection

            Members

collectionName

dbName

hint

namespace

readConcern

readPreference

writeConcern

            Typedefs

aggregationCallback

bulkWriteOpCallback

BulkWriteOpResult

collectionResultCallback

countCallback

deleteWriteOpCallback

deleteWriteOpResult

findAndModifyCallback

findAndModifyWriteOpResult

IndexDefinition

insertOneWriteOpCallback

insertOneWriteOpResult

insertWriteOpCallback

insertWriteOpResult

parallelCollectionScanCallback

resultCallback

updateWriteOpCallback

updateWriteOpResult

writeOpCallback

WriteOpResult

            Methods

aggregate

bulkWrite

count

countDocuments

createIndex

createIndexes

deleteMany

deleteOne

distinct

drop

dropAllIndexes

dropIndex

dropIndexes

ensureIndex

estimatedDocumentCount

find

findAndModify

findAndRemove

findOne

findOneAndDelete

findOneAndReplace

findOneAndUpdate

geoHaystackSearch

group

indexes

indexExists

indexInformation

initializeOrderedBulkOp

initializeUnorderedBulkOp

insert

insertMany

insertOne

isCapped

listIndexes

mapReduce

options

parallelCollectionScan

reIndex

remove

rename

replaceOne

save

stats

update

updateMany

updateOne

watch

                CommandCursor

            Typedefs

endCallback

iteratorCallback

resultCallback

toArrayResultCallback

            Methods

batchSize

clone

close

each

hasNext

isClosed

maxTimeMS

next

pause

pipe

read

resume

rewind

setEncoding

setReadPreference

toArray

unpipe

unshift

wrap

            Events

close

data

end

readable

                Cursor

            Typedefs

countResultCallback

endCallback

iteratorCallback

resultCallback

toArrayResultCallback

            Methods

addCursorFlag

addQueryModifier

batchSize

clone

close

collation

comment

count

each

explain

filter

forEach

hasNext

hint

isClosed

limit

map

max

maxAwaitTimeMS

maxScan

maxTimeMS

min

next

pause

pipe

project

read

resume

returnKey

rewind

setCursorOption

setEncoding

setReadPreference

showRecordId

skip

snapshot

sort

stream

toArray

transformStream

unpipe

unshift

wrap

            Events

close

data

end

readable

                Db

            Members

profilingInfo

            Typedefs

collectionResultCallback

            Methods

addUser

admin

aggregate

collection

collections

command

createCollection

createIndex

dropCollection

dropDatabase

ensureIndex

eval

executeDbAdminCommand

indexInformation

listCollections

profilingLevel

removeUser

renameCollection

setProfilingLevel

stats

unref

watch

            Events

close

error

fullsetup

parseError

reconnect

timeout

                DBRef

                Decimal128

            Methods

toString

fromString

                Double

            Methods

valueOf

                FindOperators

            Methods

delete

deleteOne

remove

removeOne

replaceOne

update

updateOne

upsert

                GridFSBucket

            Typedefs

errorCallback

            Methods

delete

drop

find

openDownloadStream

openDownloadStreamByName

openUploadStream

openUploadStreamWithId

rename

            Events

index

                GridFSBucketReadStream

            Methods

abort

end

pause

pipe

read

resume

setEncoding

start

unpipe

unshift

wrap

            Events

close

data

end

error

file

                GridFSBucketWriteStream

            Methods

abort

end

write

            Events

error

finish

                GridStore

            Members

DEFAULT_CONTENT_TYPE

DEFAULT_ROOT_COLLECTION

IO_SEEK_CUR

IO_SEEK_END

IO_SEEK_SET

            Typedefs

collectionCallback

gridStoreCallback

openCallback

readCallback

readlinesCallback

resultCallback

tellCallback

            Methods

exist

list

read

readlines

unlink

chunkCollection

close

collection

destroy

eof

getc

open

puts

read

readlines

rewind

seek

stream

tell

unlink

write

writeFile

                GridStoreStream

            Methods

end

pause

pipe

read

resume

setEncoding

unpipe

unshift

wrap

write

            Events

close

data

drain

end

error

finish

pipe

readable

unpipe

                Int32

            Methods

valueOf

                Logger

            Typedefs

loggerCallback

            Methods

currentLogger

filter

reset

setCurrentLogger

setLevel

debug

error

info

isDebug

isError

isInfo

isWarn

                Long

            Members

MAX_VALUE

MIN_VALUE

NEG_ONE

ONE

ZERO

            Methods

fromBits

fromInt

fromNumber

fromString

add

and

compare

div

equals

getHighBits

getLowBits

getLowBitsUnsigned

getNumBitsAbs

greaterThan

greaterThanOrEqual

isNegative

isOdd

isZero

lessThan

lessThanOrEqual

modulo

multiply

negate

not

notEquals

or

shiftLeft

shiftRight

shiftRightUnsigned

subtract

toInt

toJSON

toNumber

toString

xor

                MaxKey

                MinKey

                MongoClient

            Typedefs

connectCallback

            Methods

connect

close

connect

db

isConnected

startSession

watch

withSession

                MongoCryptError

                MongoError

            Members

errmsg

            Methods

create

hasErrorLabel

                MongoNetworkError

            Members

errmsg

            Methods

hasErrorLabel

                MongoParseError

            Members

errmsg

            Methods

hasErrorLabel

                Mongos

            Events

close

commandFailed

commandStarted

commandSucceeded

connect

error

fullsetup

ha

joined

left

open

parseError

timeout

                MongoServerSelectionError

            Members

errmsg

            Methods

hasErrorLabel

                MongoTimeoutError

            Members

errmsg

            Methods

hasErrorLabel

                MongoWriteConcernError

            Members

errmsg

            Methods

hasErrorLabel

                ObjectID

            Methods

createFromHexString

createFromTime

isValid

equals

generate

getTimestamp

toHexString

                OrderedBulkOperation

            Methods

execute

find

insert

raw

                ReplSet

            Events

close

commandFailed

commandStarted

commandSucceeded

connect

error

fullsetup

ha

joined

left

open

parseError

timeout

                Server

            Events

close

commandFailed

commandStarted

commandSucceeded

connect

error

parseError

reconnect

timeout

                Symbol

            Methods

valueOf

                Timestamp

            Members

MAX_VALUE

MIN_VALUE

NEG_ONE

ONE

ZERO

            Methods

fromBits

fromInt

fromNumber

fromString

add

and

compare

div

equals

getHighBits

getLowBits

getLowBitsUnsigned

getNumBitsAbs

greaterThan

greaterThanOrEqual

isNegative

isOdd

isZero

lessThan

lessThanOrEqual

modulo

multiply

negate

not

notEquals

or

shiftLeft

shiftRight

shiftRightUnsigned

subtract

toInt

toJSON

toNumber

toString

xor

                UnorderedBulkOperation

            Methods

execute

find

insert

raw

                WriteConcernError

            Members

code

errmsg

            Methods

toJSON

toString

                WriteError

            Members

code

errmsg

index

            Methods

getOperation

toJSON

toString

Class: Logger

    Logger

            new Logger(className, options)

            lib/core/connection/logger.js, line 29

Creates a new Logger instance

		Name

		Type

		Default

		Description

                className

string

The Class name associated with the logging instance

                options

object

                    null

                        optional

Optional settings.

		Name

		Type

		Default

		Description

                logger

Logger~loggerCallback

                    null

                        optional

Custom logger function;

                loggerLevel

string

                    error

                        optional

Override default global log level.

Methods

            staticLogger.currentLogger(){Logger~loggerCallback}

            lib/core/connection/logger.js, line 205

Get the current logger function

            staticLogger.filter(type, values){null}

            lib/core/connection/logger.js, line 227

Set what classes to log.

		Name

		Type

		Description

                type

string

The type of filter (currently only class)

                values

Array.<string>

The filters to apply

            staticLogger.reset(){null}

            lib/core/connection/logger.js, line 195

Resets the logger to default settings, error and no filtered classes

            staticLogger.setCurrentLogger(logger){null}

            lib/core/connection/logger.js, line 215

Set the current logger function

		Name

		Type

		Description

                logger

Logger~loggerCallback

Logger function.

            staticLogger.setLevel(level){null}

            lib/core/connection/logger.js, line 243

Set the current log level

		Name

		Type

		Description

                level

string

Set current log level (debug, info, error)

            debug(message, object){null}

            lib/core/connection/logger.js, line 59

Log a message at the debug level

		Name

		Type

		Description

                message

string

The message to log

                object

object

additional meta data to log

            error(message, object){null}

            lib/core/connection/logger.js, line 138

Log a message at the error level

		Name

		Type

		Description

                message

string

The message to log

                object

object

additional meta data to log

            info(message, object){null}

            lib/core/connection/logger.js, line 112

Log a message at the info level

		Name

		Type

		Description

                message

string

The message to log

                object

object

additional meta data to log

            isDebug(){boolean}

            lib/core/connection/logger.js, line 186

Is the logger set at debug level

            isError(){boolean}

            lib/core/connection/logger.js, line 170

Is the logger set at error level

            isInfo(){boolean}

            lib/core/connection/logger.js, line 162

Is the logger set at info level

            isWarn(){boolean}

            lib/core/connection/logger.js, line 178

Is the logger set at error level

Type Definitions

            loggerCallback(msg, state)

            lib/core/connection/logger.js, line 15

		Name

		Type

		Description

                msg

string

message being logged

                state

object

an object containing more metadata about the logging message

                        Documentation generated by JSDoc 3.6.6 on Wed Jan 20 2021 10:00:34 GMT-0500 (Eastern Standard Time)


text:
/*
 * This file is generated by Sencha Cmd and should NOT be edited. It redirects
 * to the most recently built CSS file for the application to allow index.html
 * in the development directory to load properly (i.e., "dev mode").
 */
@import 'build/production/W2B/resources/W2B-all.css';


text:
package com.restfiddle.dto;

public class PasswordDTO extends UserDTO {

    private String password;

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

}


text:
/*
 * Providers provided by Angular
 */
import {provide, enableProdMode} from 'angular2/core';
import {bootstrap, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';

/*
 * App Component
 * our top level component that holds all of our components
 */
import {App} from './app/app';

import { servicesInjectables } from './app/services/services';
/*
 * Bootstrap our Angular app with a top level component `App` and inject
 * our Services and Providers into Angular's dependency injection
 */
document.addEventListener('DOMContentLoaded', function main() {
  //ToDo need?
  enableProdMode()
  bootstrap(App, [
    ...('production' === process.env.ENV ? [] : ELEMENT_PROBE_PROVIDERS),
    ...HTTP_PROVIDERS,
    ...ROUTER_PROVIDERS,
    servicesInjectables,
    provide(LocationStrategy, { useClass: HashLocationStrategy })
  ])
  .catch(err => console.error(err));
});


text:
#pragma once

#include "hnetd.h"
#include "tlv.h"

/* in6_addr */
#include <netinet/in.h>

/* IFNAMSIZ */
#include <net/if.h>

/* DNS_MAX_ESCAPED_LEN */
#include "dns_util.h"

#include <libubox/list.h>

/* ep_id_t */
#include "dncp_proto.h"

/********************************************* Opaque object-like structures */

/* Defined later; this is the 'public' part of I/O + system API, which
 * essentially just contains a set of callbacks. */
typedef struct dncp_ext_struct dncp_ext_s, *dncp_ext;

/* (Not so opaque) per-endpoint _configuration_ blob, that is actually
 * part of implementation-side-only dncp_ep_i. */
typedef struct dncp_ep_struct dncp_ep_s, *dncp_ep;

/* A single dncp instance. */
typedef struct dncp_struct dncp_s, *dncp;

/* A single node in the dncp network. It is effectively TLV list and
 * other associated metadata that should not be visible to users of
 * this public API. If referring to local node, the TLVs visible here
 * are the ones that have been actually published to other nodes
 * (after a delay). */
typedef struct dncp_node_struct dncp_node_s, *dncp_node;

/* generic subscriber event enum */
enum dncp_subscriber_event {
  DNCP_EVENT_REMOVE,
  DNCP_EVENT_ADD,
  DNCP_EVENT_UPDATE
};

/* A single, local published TLV.*/
typedef struct dncp_tlv_struct dncp_tlv_s, *dncp_tlv;

/*
 * Flow of DNCP state change notifications (outbound case):
 *
 * - (if local TLV change), local_tlv_change_cb is called
 * .. at some point, when TLV changes are to be published to the network ..
 * - republish_cb is called
 * - tlv_change_cb is called
 */

enum {
  DNCP_CALLBACK_LOCAL_TLV,
  DNCP_CALLBACK_REPUBLISH,
  DNCP_CALLBACK_TLV,
  DNCP_CALLBACK_NODE,
  DNCP_CALLBACK_EP,
  DNCP_CALLBACK_SOCKET_MSG,
  NUM_DNCP_CALLBACKS
};

typedef struct dncp_subscriber_struct dncp_subscriber_s, *dncp_subscriber;

struct dncp_subscriber_struct {
  /**
   * Place within list of subscribers (owned by dncp while subscription
   * is valid). Using the same subscriber object twice will result in
   * undefined (and most likely bad) behavior.
   */
  struct list_head lhs[NUM_DNCP_CALLBACKS];

  /**
   * Local TLV change notification.
   *
   * This is called whenever one local set of TLVs (to be published at
   * some point) changes.
   *
   * @param tlv The TLV that is being added or removed (there is no 'update').
   * @param add Flag which indicates whether the operation was add or remove.
   */
  void (*local_tlv_change_cb)(dncp_subscriber s,
                              struct tlv_attr *tlv, bool add);

  /**
   * About to republish local TLVs notification.
   *
   * This is when TLVs with relative timestamps should be refreshed.
   * It is called _before_ TLV change notifications for _local_ TLVs
   * are provided.
   */
  void (*republish_cb)(dncp_subscriber r);

  /**
   * TLV change notification.
   *
   * This is called whenever one TLV within one node in DNCP
   * changes. This INCLUDE also the local node itself.
   *
   * @param n The node for which change notification occurs.
   * @param tlv The TLV that is being added or removed (there is no 'update').
   * @param add Flag which indicates whether the operation was add or remove.
   */
  void (*tlv_change_cb)(dncp_subscriber s,
                        dncp_node n, struct tlv_attr *tlv, bool add);

  /**
   * Node change notification.
   *
   * This is called whenever a node is being added or removed within
   * DNCP.
   *
   * @param n The node which is being added or removed.
   * @param add Flag which indicates whether the operation was add or remove.
   */
  void (*node_change_cb)(dncp_subscriber s, dncp_node n, bool add);

  /**
   * Some endpoint-specific information changed.
   *
   * This is called whenever an endpoint's parameters, or set of
   * endpoints itself changes. Note that DNCP itself does not have any
   * per-endpoint parameters that would cause update event; profiles
   * may.
   *
   * @param ep The endpoint which is being added, removed or modified.
   * @param event indicates whether the endpoint was added, removed or updated.
   */
  void (*ep_change_cb)(dncp_subscriber s, dncp_ep ep,
                       enum dncp_subscriber_event event);

  /**
   * TLV(s) received on a socket-notification.
   *
   * This is called whenever a message is received, either unicast or
   * multicast, on one of the socket(s) controlled by DNCP.
   *
   * NOTE: This is very low-level message handling callback; NO CHECKS
   * HAVE BEEN PERFORMED ON THE PAYLOAD (or that src/dst are really
   * allowed to send us something). Only in the (global) DTLS mode
   * handling this without address checks is probably ok, as the
   * authentication and authorization has happened before this
   * callback is called.
   */
  void (*msg_received_cb)(dncp_subscriber s,
                          dncp_ep ep,
                          struct sockaddr_in6 *src,
                          struct sockaddr_in6 *dst,
                          int recv_flags,
                          struct tlv_attr *msg);
};

/***************************************** API for handling single endpoints */

/* (dncp_ep_i itself is implementation detail) */

struct dncp_ep_struct {
  char ifname[IFNAMSIZ]; /* Name of the endpoint. */
  /* NOTE: This MUST NOT be changed. It is kept around just for
   * usability reasons. */

  char dnsname[DNS_MAX_ESCAPED_LEN]; /* DNS FQDN or label */

  /* Trickle conf */
  hnetd_time_t trickle_imin, trickle_imax;
  int trickle_k;

  /* How frequently (overriding Trickle) we MUST send something on the
   * endpoint. */
  hnetd_time_t keepalive_interval;

  /* How large can the multicasts be? */
  ssize_t maximum_multicast_size;

  /* Or unicasts? (0 = no limit) */
  ssize_t maximum_unicast_size;

  /* Do we accept node data updates via multicast? */
  bool accept_node_data_updates_via_multicast;

  /* Accept non-linklocal traffic (insecure). */
  bool accept_insecure_nonlocal_traffic;

  /* Accept non-linklocal traffic (secure). */
  bool accept_secure_nonlocal_traffic;

  /* Indicate that the interface is in unicast mode.
   *
   * In unicast mode, the keep-alives are handled per-peer, and so is
   * sending of Trickle state.
   */
  bool unicast_only;

  /* Is unicast stream + reliable? */
  bool unicast_is_reliable_stream;
};

/**
 * Find or create an endpoint that matches the name.
 */
dncp_ep dncp_find_ep_by_name(dncp o, const char *name);

/**
 * Find an endpoint that matches the id, or NULL if it does not exist.
 */
dncp_ep dncp_find_ep_by_id(dncp o, ep_id_t ep_id);

/**
 * Does the current DNCP instance have highest ID on the given endpoint?
 */
bool dncp_ep_has_highest_id(dncp_ep ep);

/**
 * Get next DNCP endpoint.
 */
dncp_ep dncp_ep_get_next(dncp_ep ep);

#define dncp_for_each_ep(o, ep)                                         \
  for (ep = dncp_get_first_ep(o) ; ep ; ep = dncp_ep_get_next(ep))

#define dncp_for_each_enabled_ep(o, ep)                 \
  dncp_for_each_ep(o, ep) if (dncp_ep_is_enabled(ep))

/* Various accessors */
dncp dncp_ep_get_dncp(dncp_ep ep);
ep_id_t dncp_ep_get_id(dncp_ep ep);
bool dncp_ep_is_enabled(dncp_ep ep);

/************************************************ API for whole dncp instance */

/**
 * Create DNCP instance.
 *
 * This call will create the dncp object, and register it to uloop. In
 * case of error, NULL is returned.
 */
dncp dncp_create(dncp_ext ext);

/**
 * Destroy DNCP instance
 *
 * This call will destroy the previous created DNCP object.
 */
void dncp_destroy(dncp o);

/**
 * Get first DNCP node.
 */
dncp_node dncp_get_first_node(dncp o);

/**
 * Get first DNCP endpoint.
 */
dncp_ep dncp_get_first_ep(dncp o);

/**
 * Publish a single TLV.
 *
 * @return The newly allocated TLV, which is valid until
 * dncp_remove_tlv is called for it. Otherwise NULL.
 */
dncp_tlv dncp_add_tlv(dncp o,
                      uint16_t type, void *data, uint16_t len,
                      int extra_bytes);

#define dncp_add_tlv_attr(o, a, bytes)                          \
  dncp_add_tlv(o, tlv_id(a), tlv_data(a), tlv_len(a), bytes)

/**
 * Find TLV with exact match (if any).
 */
dncp_tlv dncp_find_tlv(dncp o, uint16_t type, void *data, uint16_t len);

/**
 * Find node with matching node identifier (if any).
 *
 * The returned node may not be currently reachable.
 * TBD: API to check for reachability?
 */
dncp_node dncp_find_node_by_node_id(dncp o, void *nibuf, bool create);

/**
 * Stop publishing a TLV.
 */
void dncp_remove_tlv(dncp o, dncp_tlv tlv);

#define dncp_remove_tlv_matching(o, t, d, dlen)         \
  dncp_remove_tlv(o, dncp_find_tlv(o, t, d, dlen))

/**
 * Remove all TLVs of particular type.
 *
 * @return The number of TLVs removed.
 */
int dncp_remove_tlvs_by_type(dncp o, int type);

/**
 * Set the local node identifier.
 *
 * 'nibuf' must be of same size as the given node_id_length.
 */
bool dncp_set_own_node_id(dncp o, void *nibuf);

/**
 * Subscribe to DNCP state change events.
 *
 * This call will register the caller as subscriber to DNCP state
 * changes. It will also trigger a series of add notifications for
 * existing state.
 */
void dncp_subscribe(dncp o, dncp_subscriber s);

/**
 * Unsubscribe from DNCP state change events.
 *
 * Inverse of dncp_subscribe (including calls to pretend to remove all
 * state).
 */
void dncp_unsubscribe(dncp o, dncp_subscriber s);

/* Accessors */
dncp_ext dncp_get_ext(dncp o);
dncp_node dncp_get_own_node(dncp o);

/************************************************************** Per-node API */

/**
 * Get next DNCP node (in order, from DNCP).
 */
dncp_node dncp_node_get_next(dncp_node n);

/**
 * Check if the DNCP node is ourselves (may require different handling).
 */
bool dncp_node_is_self(dncp_node n);

/**
 * Get the TLVs for particular DNCP node.
 */
struct tlv_attr *dncp_node_get_tlvs(dncp_node n);

#define dncp_for_each_node(o, n)                                        \
  for (n = dncp_get_first_node(o) ; n ; n = dncp_node_get_next(n))

#define dncp_node_for_each_tlv(n, a)            \
  tlv_for_each_attr(a, dncp_node_get_tlvs(n))

/* Accessors */
void *dncp_node_get_id(dncp_node n);
dncp dncp_node_get_dncp(dncp_node n);
hnetd_time_t dncp_node_get_origination_time(dncp_node n);

/* Assorted node handling utilities */
const char *dncp_node_repr(dncp_node n, char *to_buf);
int dncp_node_cmp(dncp_node n1, dncp_node n2);

struct tlv_attr *dncp_node_get_tlv_with_type(dncp_node n, uint16_t type,
                                             bool first, bool valid);

/* Iterate through TLVs of particular type (that have been validated
 * to conform to the current profile, if valid is set). */
#define dncp_node_for_each_tlv_with_t_v(n, a, t, v)             \
  for (a = dncp_node_get_tlv_with_type(n, t, true, v) ;         \
       a && a != dncp_node_get_tlv_with_type(n, t, false, v) ;  \
       a = tlv_next(a))

#define dncp_node_for_each_tlv_with_type(n, a, t) \
  dncp_node_for_each_tlv_with_t_v(n, a, t, true)

/******************************************************* Per-(local) tlv API */

/**
 * Get the extra byte pointer associated with the tlv (extra_bytes).
 *
 * As length is not stored anywhere, it is up to the caller to be
 * consistent. If extra_bytes is zero, the first byte pointed by the
 * return value may already be invalid.
 */
void *dncp_tlv_get_extra(dncp_tlv tlv);

dncp_tlv dncp_get_next_tlv(dncp o, dncp_tlv tlv);

struct tlv_attr *dncp_tlv_get_attr(dncp_tlv tlv);

#define dncp_for_each_tlv(o, t)                                         \
  for (t = dncp_get_first_tlv(o) ; t ; t = dncp_get_next_tlv(o, t))

#define dncp_for_each_tlv_safe(o, t, t2)                                \
  for (t = dncp_get_first_tlv(o), t2 = dncp_get_next_tlv(o, t) ; t;     \
       t = t2, t2 = dncp_get_next_tlv(o, t))

dncp_tlv dncp_get_first_tlv(dncp o);

/**************************************************** dncp external bits API */

/*
 * Change these if you need bigger; however, by default, we wind up
 * wasting some memory (but as dynamic allocations are not really free
 * either, I do not care). (And we have ~2 of these per node, so
 * memory overhead in typical small networks is not large.)
 */
#define DNCP_HASH_MAX_LEN 32
#define DNCP_NI_MAX_LEN 32

/* These cover i/o, profile, and system interface. Notably, we assume
 * sockaddr_in6 is sufficient encoding for addresses, and if it is
 * not, someone needs to do some refactoring. As DNCP code itself does
 * not use it for anything else than just storing it, it should be
 * _relatively_ straightforward to abstract further if the need
 * comes. */

struct dncp_ext_configuration_struct {
  /* Per-endpoint configuration defaults to what is provided here. */
  dncp_ep_s per_ep;

  /* Size of the node identifier; MUST be <= DNCP_NI_MAX_LEN */
  uint8_t node_id_length;

  /* Hash length; MUST be <= DNCP_HASH_MAX_LEN */
  uint8_t hash_length;

  /* Keepalive multiplier (as percent of keepalive interval) */
  uint16_t keepalive_multiplier_percent;

  /* How recently node has to have been reachable before prune kills
   * it for real. */
  hnetd_time_t grace_interval;

  /* How often frequently the pruning is done at most; it should be
   * less than minimum Trickle interval, as non-valid state will not
   * be used to respond to node data requests. */
  hnetd_time_t minimum_prune_interval;

  /* How much memory do we allocate for external code parts per node? */
  size_t ext_node_data_size;

  /* How much memory do we allocate for external code parts per ep? */
  size_t ext_ep_data_size;
};

/* While the code uses sockaddr_in6 for now, it intentionally does not
 * use any of the internal semantics within dncp*. Therefore, the I/O
 * is responsible for setting following flags:
 *
 * Note also that 'NULL' dst is mapped to the multicast address, but
 * as dncp does not need to know about it, it does not.
 */

/* IN6_IS_ADDR_LINKLOCAL result on src/dst */
#define DNCP_RECV_FLAG_SRC_LINKLOCAL 0x1
#define DNCP_RECV_FLAG_DST_LINKLOCAL 0x2

/* Whether or not the packet was actually received using secure means. */
#define DNCP_RECV_FLAG_SECURE        0x4

/* Whether or not security was available. If this is set, but
 * FLAG_SECURE is not, packet should be probably ignored. */
#define DNCP_RECV_FLAG_SECURE_TRIED  0x8

struct dncp_ext_cbs_struct {
  /* I/O-related callbacks */

  /** Receive bytes from the network. ep, src, dst are set as appropriate. */
  ssize_t (*recv)(dncp_ext e, dncp_ep *ep,
                  struct sockaddr_in6 **src,
                  struct sockaddr_in6 **dst,
                  int *flags,
                  void *buf, size_t buf_len);

  /** Send bytes to the network. */
  void (*send)(dncp_ext e, dncp_ep ep,
               struct sockaddr_in6 *src,
               struct sockaddr_in6 *dst,
               void *buf, size_t buf_len);

  /* Profile-related callbacks */

  /**
   * Callback to perform hashing.
   *
   * It MUST write only hash_length (see above) bytes to dst after
   * running hash over buf[:len].
   */
  void (*hash)(const void *buf, size_t len, void *dst);

  /**
   * Validate node data.
   */
  struct tlv_attr *(*validate_node_data)(dncp_node n, struct tlv_attr *a);

  /**
   * Handle node identifier collision.
   *
   * If it returns true, the collision should be ignored (=the code
   * did something); if it returns false, the current node's TLV data
   * should be republished (with higher update number - 'we are right,
   * we are not moving').
   */
  bool (*handle_collision)(dncp_ext e);

  /* Platform abstraction layer (facilitates unit testing etc.) */
  int (*get_hwaddrs)(dncp_ext e, unsigned char *buf, int buf_left);
  hnetd_time_t (*get_time)(dncp_ext e);
  void (*schedule_timeout)(dncp_ext e, int msecs);
};

struct dncp_ext_struct {
  struct dncp_ext_configuration_struct conf;
  struct dncp_ext_cbs_struct cb;
};

/**
 * Get the external node data pointer of an endpoint. If endpoint is
 * NULL, extdata is also NULL.
 */
void *dncp_ep_get_ext_data(dncp_ep n);

/**
 * Get the external node data pointer of a node. If node is NULL,
 * extdata is also NULL.
 */
void *dncp_node_get_ext_data(dncp_node n);

/**
 * Reverse operation - convert ext data pointer to node.
 */
dncp_node dncp_node_from_ext_data(void *ext_data);

/**
 * Notification from i/o that the endpoint is ready.
 */
void dncp_ext_ep_ready(dncp_ep ep, bool ready);

/**
 * Reverse operation - convert ext data pointer to ep.
 */
dncp_ep dncp_ep_from_ext_data(void *ext_data);

/**
 * Notification from i/o that a peer state has changed.
 *
 * These will occur only on connection-oriented transport. The 'local'
 * (and possibly even remote) MAY be NULL if the transport warrants
 * it. Any peer (defined by (local, remote) in 'connected' state) is
 * assumed to be reachable and DNCP MAY attempt to send packets to it.
 */
void dncp_ext_ep_peer_state(dncp_ep ep,
                            struct sockaddr_in6 *local,
                            struct sockaddr_in6 *remote,
                            bool connected);

/**
 * Notification from the i/o that there is something new available to be read.
 */
void dncp_ext_readable(dncp dncp);

/**
 * Notification from the platform that the timeout has expired.
 */
void dncp_ext_timeout(dncp dncp);

/****************************************** For profile implementation use.. */

/* Subscription stuff (dncp_notify.c) */
void dncp_notify_subscribers_tlvs_changed(dncp_node n,
                                          struct tlv_attr *a_old,
                                          struct tlv_attr *a_new);
void dncp_notify_subscribers_node_changed(dncp_node n, bool add);
void dncp_notify_subscribers_about_to_republish_tlvs(dncp_node n);
void dncp_notify_subscribers_local_tlv_changed(dncp o,
                                               struct tlv_attr *a,
                                               bool add);
void dncp_notify_subscribers_ep_changed(dncp_ep ep,
                                        enum dncp_subscriber_event event);


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

<TITLE>
BirthdayEvaluator (JCalendar API)
</TITLE>

<META NAME="date" CONTENT="2011-07-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.toedter.calendar.demo

Class BirthdayEvaluator

java.lang.Object
  com.toedter.calendar.demo.BirthdayEvaluator

All Implemented Interfaces:
IDateEvaluator

public class BirthdayEvaluator
extends java.lang.Object
implements IDateEvaluator

Constructor Summary

BirthdayEvaluator()

Method Summary

 java.awt.Color
getInvalidBackroundColor()

 java.awt.Color
getInvalidForegroundColor()

 java.lang.String
getInvalidTooltip()

 java.awt.Color
getSpecialBackroundColor()

 java.awt.Color
getSpecialForegroundColor()

 java.lang.String
getSpecialTooltip()

 boolean
isInvalid(java.util.Date date)

          Checks if a date is invalid for selection

 boolean
isSpecial(java.util.Date date)

          Checks if a date is a special date (might have different colors and tooltips)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BirthdayEvaluator

public BirthdayEvaluator()

Method Detail

isSpecial

public boolean isSpecial(java.util.Date date)

Description copied from interface: IDateEvaluator

Checks if a date is a special date (might have different colors and tooltips)

Specified by:
isSpecial in interface IDateEvaluator

Parameters:
date - the date to check

Returns:
true, if the date can be selected

getSpecialForegroundColor

public java.awt.Color getSpecialForegroundColor()

Specified by:
getSpecialForegroundColor in interface IDateEvaluator

Returns:
the foreground color (used by JDayChooser)

getSpecialBackroundColor

public java.awt.Color getSpecialBackroundColor()

Specified by:
getSpecialBackroundColor in interface IDateEvaluator

Returns:
the background color (used by JDayChooser)

getSpecialTooltip

public java.lang.String getSpecialTooltip()

Specified by:
getSpecialTooltip in interface IDateEvaluator

Returns:
the tooltip (used by JDayChooser)

isInvalid

public boolean isInvalid(java.util.Date date)

Description copied from interface: IDateEvaluator

Checks if a date is invalid for selection

Specified by:
isInvalid in interface IDateEvaluator

Parameters:
date - the date to check

Returns:
true, if the date is invalid and cannot be selected

getInvalidForegroundColor

public java.awt.Color getInvalidForegroundColor()

Specified by:
getInvalidForegroundColor in interface IDateEvaluator

Returns:
the foreground color (used by JDayChooser)

getInvalidBackroundColor

public java.awt.Color getInvalidBackroundColor()

Specified by:
getInvalidBackroundColor in interface IDateEvaluator

Returns:
the background color (used by JDayChooser)

getInvalidTooltip

public java.lang.String getInvalidTooltip()

Specified by:
getInvalidTooltip in interface IDateEvaluator

Returns:
the tooltip (used by JDayChooser)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 1999 - 2011 Kai Toedter.


text:
"""
 Collects JMX metrics from the Jolokia Agent. Jolokia is an HTTP bridge that
provides access to JMX MBeans without the need to write Java code. See the
[Reference Guide](http://www.jolokia.org/reference/html/index.html) for more
information.

By default, all MBeans will be queried for metrics. All numerical values will
be published to Graphite; anything else will be ignored. JolokiaCollector will
create a reasonable namespace for each metric based on each MBeans domain and
name. e.g) ```java.lang:name=ParNew,type=GarbageCollector``` would become
```java.lang.name_ParNew.type_GarbageCollector```.

#### Dependencies

 * Jolokia
 * A running JVM with Jolokia installed/configured

#### Example Configuration

If desired, JolokiaCollector can be configured to query specific MBeans by
providing a list of ```mbeans```. If ```mbeans``` is not provided, all MBeans
will be queried for metrics.  Note that the mbean prefix is checked both
with and without rewrites (including fixup re-writes) applied.  This allows
you to specify "java.lang:name=ParNew,type=GarbageCollector" (the raw name from
jolokia) or "java.lang.name_ParNew.type_GarbageCollector" (the fixed name
as used for output)

If the ```regex``` flag is set to True, mbeans will match based on regular
expressions rather than a plain textual match.

The ```rewrite``` section provides a way of renaming the data keys before
it sent out to the handler.  The section consists of pairs of from-to
regular expressions.  If the resultant name is completely blank, the
metric is not published, providing a way to exclude specific metrics within
an mbean.

```
    host = localhost
    port = 8778
    mbeans = "java.lang:name=ParNew,type=GarbageCollector",
     "org.apache.cassandra.metrics:name=WriteTimeouts,type=ClientRequestMetrics"
    [rewrite]
    java = coffee
    "-v\d+\.\d+\.\d+" = "-AllVersions"
    ".*GetS2Activities.*" = ""
```
"""

import diamond.collector
import base64
from contextlib import closing
import json
import re
import urllib
import urllib2

class JolokiaCollector(diamond.collector.Collector):

    LIST_URL = "/list"

    """
    These domains contain MBeans that are for management purposes,
    or otherwise do not contain useful metrics
    """
    IGNORE_DOMAINS = ['JMImplementation', 'jmx4perl', 'jolokia',
                      'com.sun.management', 'java.util.logging']

    def get_default_config_help(self):
        config_help = super(JolokiaCollector,
                            self).get_default_config_help()
        config_help.update({
            'domains': "Pipe delimited list of JMX domains from which to"
                       " collect stats. If not provided, the list of all"
                       " domains will be downloaded from jolokia.",
            'mbeans':  "Pipe delimited list of MBeans for which to collect"
                       " stats. If not provided, all stats will"
                       " be collected.",
            'regex': "Contols if mbeans option matches with regex,"
                       " False by default.",
            'username': "Username for authentication",
            'password': "Password for authentication",
            'host': 'Hostname',
            'port': 'Port',
            'rewrite': "This sub-section of the config contains pairs of"
                       " from-to regex rewrites.",
            'path': 'Path component of the reported metrics.',
            # https://github.com/rhuss/jolokia/blob/959424888a82abc2b1906c60547cd4df280f3b71/client/java/src/main/java/org/jolokia/client/request/J4pQueryParameter.java#L68
            'use_canonical_names': 'Whether property keys of ObjectNames'
                                   ' should be ordered in the canonical way'
                                   ' or in the way that they are created. The'
                                   ' allowed values are either "True" in'
                                   ' which case the canonical key order (=='
                                   ' alphabetical sorted) is used or "False"'
                                   ' for getting the keys as registered.'
                                   ' Default is "True',
            'jolokia_path': 'Path to jolokia.  typically "jmx" or "jolokia".'
                            ' Defaults to the value of "path" variable.',
        })
        return config_help

    def get_default_config(self):
        config = super(JolokiaCollector, self).get_default_config()
        config.update({
            'mbeans': [],
            'regex': False,
            'rewrite': [],
            'path': 'jolokia',
            'jolokia_path': None,
            'username': None,
            'password': None,
            'host': 'localhost',
            'port': 8778,
            'use_canonical_names': True,
        })
        return config

    def __init__(self, *args, **kwargs):
        super(JolokiaCollector, self).__init__(*args, **kwargs)
        self.mbeans = []
        if isinstance(self.config['mbeans'], basestring):
            for mbean in self.config['mbeans'].split('|'):
                self.mbeans.append(mbean.strip())
        elif isinstance(self.config['mbeans'], list):
            self.mbeans = self.config['mbeans']
        if self.config['regex'] is not None:
            self.mbeans = [re.compile(mbean) for mbean in self.mbeans]

        self.rewrite = [
            (re.compile('["\'(){}<>\[\]]'), ''),
            (re.compile('[:,.]+'), '.'),
            (re.compile('[^a-zA-Z0-9_.+-]+'), '_'),
        ]
        if isinstance(self.config['rewrite'], dict):
            self.rewrite.extend([(re.compile(old), new) for old, new in
                                 self.config['rewrite'].items()])

        self.domains = []
        if 'domains' in self.config:
            if isinstance(self.config['domains'], basestring):
                for domain in self.config['domains'].split('|'):
                    self.domains.append(domain.strip())
            elif isinstance(self.config['domains'], list):
                self.domains = self.config['domains']

        if self.config['jolokia_path'] is not None:
            self.jolokia_path = self.config['jolokia_path']
        else:
            self.jolokia_path = self.config['path']

        if not isinstance(self.config['use_canonical_names'], bool):
            if self.config['use_canonical_names'] == 'True':
                self.config['use_canonical_names'] = True
            elif self.config['use_canonical_names'] == 'False':
                self.config['use_canonical_names'] = False
            else:
                self.log.error('Unexpected value "%s" for "use_canonical_names"'
                               ' setting. Expected "True" or "False". Using'
                               ' default value.',
                               self.config['use_canonical_names'])
                default = self.get_default_config()['use_canonical_names']
                self.config['use_canonical_names'] = default

    def _get_domains(self):
        # if not set it __init__
        if not self.domains:
            listing = self._list_request()
            try:
                if listing['status'] == 200:
                    self.domains = listing['value'].keys()
                else:
                    self.log.error('Jolokia status %s while retrieving MBean '
                                   'listing.', listing['status'])
            except KeyError:
                # The reponse was totally empty, or not an expected format
                self.log.error('Unable to retrieve MBean listing.')

    def _check_mbean(self, mbean):
        if not self.mbeans:
            return True
        mbeanfix = self.clean_up(mbean)
        if self.config['regex'] is not None:
            for chkbean in self.mbeans:
                if chkbean.match(mbean) is not None or \
                   chkbean.match(mbeanfix) is not None:
                    return True
        else:
            if mbean in self.mbeans or mbeanfix in self.mbeans:
                return True

    def collect(self):
        if not self.domains:
            self._get_domains()
        for domain in self.domains:
            if domain not in self.IGNORE_DOMAINS:
                obj = self._read_request(domain)
                try:
                    mbeans = obj['value'] if obj['status'] == 200 else {}
                except KeyError:
                    # The reponse was totally empty, or not an expected format
                    self.log.error('Unable to retrieve domain %s.', domain)
                    continue
                for k, v in mbeans.iteritems():
                    if self._check_mbean(k):
                        self.collect_bean(k, v)

    def _read_json(self, request):
        json_str = request.read()
        return json.loads(json_str)

    def _list_request(self):
        """Returns a dictionary with JMX domain names as keys"""
        try:
            # https://jolokia.org/reference/html/protocol.html
            #
            # A maxDepth of 1 restricts the return value to a map with the JMX
            # domains as keys. The values of the maps don't have any meaning
            # and are dummy values.
            #
            # maxCollectionSize=0 means "unlimited". This works around an issue
            # prior to Jolokia 1.3 where results were truncated at 1000
            #
            url = "http://%s:%s/%s%s?maxDepth=1&maxCollectionSize=0" % (
                self.config['host'],
                self.config['port'],
                self.jolokia_path,
                self.LIST_URL)
            # need some time to process the downloaded metrics, so that's why
            # timeout is lower than the interval.
            timeout = max(2, float(self.config['interval']) * 2 / 3)
            with closing(urllib2.urlopen(self._create_request(url),
                                         timeout=timeout)) as response:
                return self._read_json(response)
        except (urllib2.HTTPError, ValueError) as e:
            self.log.error('Unable to read JSON response: %s', str(e))
            return {}

    def _read_request(self, domain):
        try:
            url_path = '/?%s' % urllib.urlencode({
                'maxCollectionSize': '0',
                'ignoreErrors': 'true',
                'canonicalNaming':
                    'true' if self.config['use_canonical_names'] else 'false',
                'p': 'read/%s:*' % self._escape_domain(domain),
            })
            url = "http://%s:%s/%s%s" % (self.config['host'],
                                         self.config['port'],
                                         self.jolokia_path,
                                         url_path)
            # need some time to process the downloaded metrics, so that's why
            # timeout is lower than the interval.
            timeout = max(2, float(self.config['interval']) * 2 / 3)
            with closing(urllib2.urlopen(self._create_request(url),
                                         timeout=timeout)) as response:
                return self._read_json(response)
        except (urllib2.HTTPError, ValueError):
            self.log.error('Unable to read JSON response.')
            return {}

    # escape JMX domain per https://jolokia.org/reference/html/protocol.html
    # the Jolokia documentation suggests that when using the p query parameter,
    # simply urlencoding should be sufficient, but in practice, the '!' appears
    # necessary (and not harmful)
    def _escape_domain(self, domain):
        domain = re.sub('!', '!!', domain)
        domain = re.sub('/', '!/', domain)
        domain = re.sub('"', '!"', domain)
        domain = urllib.quote(domain)
        return domain

    def _create_request(self, url):
        req = urllib2.Request(url)
        username = self.config["username"]
        password = self.config["password"]
        if username is not None and password is not None:
            base64string = base64.encodestring('%s:%s' % (
                username, password)).replace('\n', '')
            req.add_header("Authorization", "Basic %s" % base64string)
        return req

    def clean_up(self, text):
        for (oldregex, newstr) in self.rewrite:
            text = oldregex.sub(newstr, text)
        return text

    def collect_bean(self, prefix, obj):
        for k, v in obj.iteritems():
            if type(v) in [int, float, long]:
                key = "%s.%s" % (prefix, k)
                key = self.clean_up(key)
                if key != "":
                    self.publish(key, v)
            elif type(v) in [dict]:
                self.collect_bean("%s.%s" % (prefix, k), v)
            elif type(v) in [list]:
                self.interpret_bean_with_list("%s.%s" % (prefix, k), v)

    # There's no unambiguous way to interpret list values, so
    # this hook lets subclasses handle them.
    def interpret_bean_with_list(self, prefix, values):
        pass