text:
#include <typeinfo>

#if defined(_MSC_VER)
#pragma warning( push , 0 )
#endif

#include "llvm/Transforms/Utils/Cloning.h"

#if defined(_MSC_VER)
#pragma warning( pop )
#endif

#include "CodeGenContext.h"
#include "parser.hpp"
#include "FunctionDeclaration.h"
#include "Declaration.h"

using namespace std;
using namespace llvm;

namespace liquid {

FunctionDeclaration::FunctionDeclaration(const FunctionDeclaration& other)
{
   type = new Identifier(*other.type);
   id = new Identifier(*other.id);
   arguments = new VariableList();
   for( auto arg : *other.arguments ) {
      arguments->push_back(new VariableDeclaration(new Identifier(arg->getVariablenTypeName(), arg->getLocation()), new Identifier(arg->getVariablenName(), arg->getLocation()), arg->getLocation()));
   }
   block = other.block;
   location = other.location;
   isaCopy = true; // Quick hack, a copy contains the origin block and shouldn't be deleted.
}

FunctionDeclaration::FunctionDeclaration(Identifier* type, Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc)
   : type(type), id(id), arguments(arguments), block(block), location(loc)
{
   checkForTemplateParameter();
}

FunctionDeclaration::FunctionDeclaration(Identifier* id, VariableList* arguments, Block* block, YYLTYPE loc)
   : type(new Identifier("var", loc)), id(id), arguments(arguments), block(block), location(loc)
{
   checkForTemplateParameter();
}

FunctionDeclaration::~FunctionDeclaration()
{
    for( auto i : *arguments ) {
        delete i;
    }
    delete type;
    delete id;
    delete arguments;
    if( !isaCopy ) { // Don't delete the origin block
       delete block;
    }
}

void FunctionDeclaration::checkForTemplateParameter()
{
   auto found = std::find_if(std::begin(*arguments), std::end(*arguments), [](auto vardecl) { return vardecl->getVariablenTypeName() == "var"; });
   if(found != std::end(*arguments)) {
      hasTemplateParameter = true;
   }
}

Value* FunctionDeclaration::codeGen( CodeGenContext& context )
{
   if( hasTemplateParameter && !context.codeGenTheTemplatedFunction()) {
      // This function declaration has at least one unknown parameter type.
      // Postpone the creation until they are known (call).
      context.addTemplateFunction( id->getName(), this );
      return nullptr;
   }

   vector<Type*> argTypes;
    if( !context.getKlassName().empty() ) {
        // add the self pointer of the class as first argument..
        Type* self_ty = context.typeOf( context.getKlassName() );
        argTypes.push_back( PointerType::get( self_ty, 0 ) );
    }

    for( auto varDecl : *arguments ) {
        Type* ty = context.typeOf( varDecl->getIdentifierOfVariablenType() );
        if( ty->isStructTy() ) {
            ty = PointerType::get( ty, 0 );
        }
        argTypes.push_back( ty );
    }

    // TODO check return type if it is a structure type !!! May be it should be a ptr to the structure!
    FunctionType *ftype = FunctionType::get( context.typeOf( *type ), argTypes, false );
    std::string functionName = id->getName();
    if( type->getName() == "var" ) {
        functionName += "_del";
    }
    if( !context.getKlassName().empty() ) {
        functionName += "%" + context.getKlassName();
    }
    Function *function = Function::Create( ftype, GlobalValue::InternalLinkage, functionName.c_str(), context.getModule() );
    BasicBlock *bblock = BasicBlock::Create( context.getGlobalContext(), "entry", function, 0 );
    context.newScope( bblock, ScopeType::FunctionDeclaration );

    // Put the parameter onto the stack in order to be accessed in the function.
    Function::arg_iterator actualArgs = function->arg_begin();
    // First check if a elf ptr has to be put as first argument.
    if( !context.getKlassName().empty() ) {
        actualArgs->setName( "this" );
        //Value* ptr_this = actualArgs++;
        Type* self_ty = context.typeOf( context.getKlassName() );
        Type* self_ptr_ty = PointerType::get( self_ty, 0 );
        AllocaInst* alloca = new AllocaInst( self_ptr_ty, 0, "self_addr", context.currentBlock() );
        new StoreInst( &(*actualArgs) /*ptr_this*/, alloca, context.currentBlock() );
        context.locals()["self"] = alloca;
        ++actualArgs;
    }
    // Now the remaining arguments
    for( auto varDecl : *arguments ) {
        AllocaInst* alloca = llvm::dyn_cast< AllocaInst >(varDecl->codeGen( context ));
        std::string valName = varDecl->getVariablenName();
        // TODO a struct is coming as struct alloca, but needed to be a pointer to a struct alloca.
        if( alloca ) {
            if( alloca->getAllocatedType()->isPointerTy() ) {
                valName += "_addr";
            }
            actualArgs->setName( valName );
            new StoreInst( &(*actualArgs), alloca, context.currentBlock() );
        }
        ++actualArgs;
    }

    // Generate the function body.
    auto blockValue = block->codeGen( context );
    if( blockValue == nullptr ) {
       Node::printError(location, " " + id->getStructName() + "::" + id->getName() + "(): Function block returns nothing");
       context.addError();
       return nullptr;
    }
    auto retTy = blockValue->getType();

    // If the function doesn't have a return type and doesn't have a return statement, make a ret void.
    // Obsolete default is var.
    if( type->getName() == "void" ) {
        if( context.currentBlock()->getTerminator() == nullptr ) {
            ReturnInst::Create( context.getGlobalContext(), 0, context.currentBlock() );
        }
    }

    // If the now return instruction is generated so far ...
    if( context.currentBlock()->getTerminator() == nullptr ) {
        if( type->getName() == "var" && !retTy->isVoidTy() ) {
            // Generate one according to the value of the function body.
            ReturnInst::Create( context.getGlobalContext(), blockValue, context.currentBlock() );
        } else {
            // Or a ret void.
            ReturnInst::Create( context.getGlobalContext(), 0, context.currentBlock() );
        }
    }

    if( type->getName() == "var" ) {
        if( retTy->isLabelTy() || retTy->isMetadataTy() ) {
            context.endScope();
            Node::printError( location, " Function w/ var return type and multiple return statements are not supported: " + id->getName() + "(...)" );
            context.addError();
            return nullptr;
        }

        // Now create the a new function (the real one) since we know the return type now.
        auto terminator = context.currentBlock()->getTerminator();
        auto retInstr = dyn_cast<ReturnInst>(terminator);
        auto retval = retInstr->getReturnValue();
        Type* retValTy = nullptr;
        if( retval == nullptr ) {
           // The return instruction has no operand and no type it is a ret void.
           retValTy = Type::getVoidTy(context.getGlobalContext());
        } else {
           retValTy = retval->getType();
        }

        std::string functionNameNew = id->getName();
        if( context.codeGenTheTemplatedFunction() ) {
           // Now all types are known, check if this type of function already exist
           auto constructedFctName = buildFunctionName(retValTy, argTypes);
           auto fct = context.getModule()->getFunction(constructedFctName);
           if( fct != nullptr ) {
              // Yes, take that one and remove the newly generated.
              function->eraseFromParent();
              context.endScope();
              return fct;
           }
           functionNameNew = constructedFctName;
        }

        FunctionType* ftypeNew = FunctionType::get(retValTy, argTypes, false);
        if( !context.getKlassName().empty() ) {
            functionNameNew += "%" + context.getKlassName();
        }

        Function *functionNew = Function::Create( ftypeNew, GlobalValue::InternalLinkage, functionNameNew, context.getModule() );

        // Create a value map for all arguments to be mapped to the new function.
        ValueToValueMapTy VMap;
        Function::arg_iterator DestI = functionNew->arg_begin();

        for( Function::const_arg_iterator J = function->arg_begin(); J != function->arg_end(); ++J ) {
            DestI->setName( J->getName() ); // Copy name of argument to the argument of the new function.
            VMap[&*J] = &*DestI++; // Map the value
        }

        // Clone the function to the new (real) function w/ the correct return type.
        SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
        CloneFunctionInto( functionNew, function, VMap, CloneFunctionChangeType::LocalChangesOnly, Returns );

        // Remove the old one.
        function->eraseFromParent();

        function = functionNew;
    }

    context.endScope();
    return function;
}

std::string FunctionDeclaration::toString()
{
   std::stringstream s;
   s << "function declaration: " << id->getName();
   return s.str();
}

std::string FunctionDeclaration::buildFunctionName(llvm::Type* retType, std::vector<llvm::Type*> argTypes)
{
   std::string constructedName = id->getName() + "_";
   constructedName += std::to_string(retType->getTypeID());
   for( auto t : argTypes ) {
      constructedName += "_" + std::to_string(t->getTypeID());
   }
   return constructedName;
}

}


text:
require 'spec_helper'

RSpec.describe Stoplight::Notifier::Base do
  let(:notifier) { described_class.new }

  it 'is a class' do
    expect(described_class).to be_a(Class)
  end

  describe '#notify' do
    it 'is not implemented' do
      expect { notifier.notify(nil, nil, nil, nil) }
        .to raise_error(NotImplementedError)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package io.reactivex.rxjava3.internal.operators.completable;

import java.util.concurrent.atomic.*;

import org.reactivestreams.*;

import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.disposables.*;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
import io.reactivex.rxjava3.internal.util.AtomicThrowable;

public final class CompletableMerge extends Completable {
    final Publisher<? extends CompletableSource> source;
    final int maxConcurrency;
    final boolean delayErrors;

    public CompletableMerge(Publisher<? extends CompletableSource> source, int maxConcurrency, boolean delayErrors) {
        this.source = source;
        this.maxConcurrency = maxConcurrency;
        this.delayErrors = delayErrors;
    }

    @Override
    public void subscribeActual(CompletableObserver observer) {
        CompletableMergeSubscriber parent = new CompletableMergeSubscriber(observer, maxConcurrency, delayErrors);
        source.subscribe(parent);
    }

    static final class CompletableMergeSubscriber
    extends AtomicInteger
    implements FlowableSubscriber<CompletableSource>, Disposable {

        private static final long serialVersionUID = -2108443387387077490L;

        final CompletableObserver downstream;
        final int maxConcurrency;
        final boolean delayErrors;

        final AtomicThrowable errors;

        final CompositeDisposable set;

        Subscription upstream;

        CompletableMergeSubscriber(CompletableObserver actual, int maxConcurrency, boolean delayErrors) {
            this.downstream = actual;
            this.maxConcurrency = maxConcurrency;
            this.delayErrors = delayErrors;
            this.set = new CompositeDisposable();
            this.errors = new AtomicThrowable();
            lazySet(1);
        }

        @Override
        public void dispose() {
            upstream.cancel();
            set.dispose();
            errors.tryTerminateAndReport();
        }

        @Override
        public boolean isDisposed() {
            return set.isDisposed();
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.upstream, s)) {
                this.upstream = s;
                downstream.onSubscribe(this);
                if (maxConcurrency == Integer.MAX_VALUE) {
                    s.request(Long.MAX_VALUE);
                } else {
                    s.request(maxConcurrency);
                }
            }
        }

        @Override
        public void onNext(CompletableSource t) {
            getAndIncrement();

            MergeInnerObserver inner = new MergeInnerObserver();
            set.add(inner);
            t.subscribe(inner);
        }

        @Override
        public void onError(Throwable t) {
            if (!delayErrors) {
                set.dispose();

                if (errors.tryAddThrowableOrReport(t)) {
                    if (getAndSet(0) > 0) {
                        errors.tryTerminateConsumer(downstream);
                    }
                }
            } else {
                if (errors.tryAddThrowableOrReport(t)) {
                    if (decrementAndGet() == 0) {
                        errors.tryTerminateConsumer(downstream);
                    }
                }
            }
        }

        @Override
        public void onComplete() {
            if (decrementAndGet() == 0) {
                errors.tryTerminateConsumer(downstream);
            }
        }

        void innerError(MergeInnerObserver inner, Throwable t) {
            set.delete(inner);
            if (!delayErrors) {
                upstream.cancel();
                set.dispose();

                if (errors.tryAddThrowableOrReport(t)) {
                    if (getAndSet(0) > 0) {
                        errors.tryTerminateConsumer(downstream);
                    }
                }
            } else {
                if (errors.tryAddThrowableOrReport(t)) {
                    if (decrementAndGet() == 0) {
                        errors.tryTerminateConsumer(downstream);
                    } else {
                        if (maxConcurrency != Integer.MAX_VALUE) {
                            upstream.request(1);
                        }
                    }
                }
            }
        }

        void innerComplete(MergeInnerObserver inner) {
            set.delete(inner);
            if (decrementAndGet() == 0) {
                errors.tryTerminateConsumer(downstream);
            } else {
                if (maxConcurrency != Integer.MAX_VALUE) {
                    upstream.request(1);
                }
            }
        }

        final class MergeInnerObserver
        extends AtomicReference<Disposable>
        implements CompletableObserver, Disposable {
            private static final long serialVersionUID = 251330541679988317L;

            @Override
            public void onSubscribe(Disposable d) {
                DisposableHelper.setOnce(this, d);
            }

            @Override
            public void onError(Throwable e) {
                innerError(this, e);
            }

            @Override
            public void onComplete() {
                innerComplete(this);
            }

            @Override
            public boolean isDisposed() {
                return DisposableHelper.isDisposed(get());
            }

            @Override
            public void dispose() {
                DisposableHelper.dispose(this);
            }
        }
    }
}


text:
/* global Handlebars */

Handlebars.registerHelper('score', function() {
	if(this.score) {
		var score = Math.round( this.score / 10 );
		var imageName = 'rating/s' + score + '.svg';

		return new Handlebars.SafeString('');
	}
	return new Handlebars.SafeString('');
});
Handlebars.registerHelper('level', function() {
	if(!_.isUndefined(this.level)) {
		if(this.level === 200) {
			return new Handlebars.SafeString('' + t('settings', 'Official') + '');
		} else if(this.level === 100) {
			return new Handlebars.SafeString('' + t('settings', 'Approved') + '');
		}
	}
});
Handlebars.registerHelper('md', function(text){
	var converter =  new showdown.Converter({
		strikethrough: true,
		tables : true,
		tasklists : true
	});
	return new Handlebars.SafeString(
		converter.makeHtml(text)
	);
});

OC.Settings = OC.Settings || {};
OC.Settings.Apps = OC.Settings.Apps || {
	setupGroupsSelect: function($elements) {
		OC.Settings.setupGroupsSelect($elements, {
			placeholder: t('core', 'All')
		});
	},

	State: {
		currentCategory: null,
		apps: null
	},

	loadCategories: function() {
		var categories = [
			{displayName: t('settings', 'Enabled'), ident: 'enabled', id: '0'},
			{displayName: t('settings', 'Not enabled'), ident: 'disabled', id: '1'}
		];

		var source   = $("#categories-template").html();
		var template = Handlebars.compile(source);
		var html = template(categories);
		$('#apps-categories').html(html);

		var queries = {
			category: 'enabled'
		};
		if (document.location.search) {
			$.each(document.location.search.substr(1).split('&'), function (c, q) {
				var i = q.split('=');
				queries[i[0].toString()] = i[1].toString();
			});
		}

		OC.Settings.Apps.loadCategory(queries.category);
	},

	loadCategory: function(categoryId) {
		var self = this;
		if (OC.Settings.Apps.State.currentCategory === categoryId) {
			return;
		}
		if (this._loadCategoryCall) {
			this._loadCategoryCall.abort();
		}
		$('#apps-list')
			.addClass('icon-loading')
			.removeClass('hidden')
			.html('');
		$('#apps-list-empty').addClass('hidden');
		$('#button-apps-enabled').hide();
		$('#button-apps-disabled').hide();
		OC.Settings.Apps.State.currentCategory = categoryId;

		this._loading = true;
		this._loadCategoryCall = $.ajax(OC.generateUrl('settings/apps/list?category={categoryId}', {
			categoryId: categoryId
		}), {
			type:'GET',
			success: function (apps) {
				var appListWithIndex = _.indexBy(apps.apps, 'id');
				OC.Settings.Apps.State.apps = appListWithIndex;
				var appList = _.map(appListWithIndex, function(app) {
					// default values for missing fields
					return _.extend({level: 0}, app);
				});
				var source   = $("#app-template").html();
				var template = Handlebars.compile(source);

				if (appList.length) {
					appList.sort(function(a,b) {
						var levelDiff = b.level - a.level;
						if (levelDiff === 0) {
							return OC.Util.naturalSortCompare(a.name, b.name);
						}
						return levelDiff;
					});

					var firstExperimental = false;
					_.each(appList, function(app) {
						if(app.level === 0 && firstExperimental === false) {
							firstExperimental = true;
							OC.Settings.Apps.renderApp(app, template, null, true);
						} else {
							OC.Settings.Apps.renderApp(app, template, null, false);
						}
					});
				} else {
					$('#apps-list').addClass('hidden');
					$('#apps-list-empty').removeClass('hidden').find('h2').text(t('settings', 'No apps found for your version'));
				}

				$('.enable.needs-download').tipsy({fallback: t('settings', 'The app will be downloaded from the app store')});

				$('.app-level .official').tipsy({fallback: t('settings', 'Official apps are developed by and within the ownCloud community. They offer functionality central to ownCloud and are ready for production use.')});
				$('.app-level .approved').tipsy({fallback: t('settings', 'Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use.')});
				$('.app-level .experimental').tipsy({fallback: t('settings', 'This app is not checked for security issues and is new or known to be unstable. Install at your own risk.')});
			},
			complete: function() {
				$('#apps-list').removeClass('icon-loading');
				$('#button-apps-' + (OC.Settings.Apps.State.currentCategory === 'enabled' ? 'disabled' : 'enabled')).show();
			}
		});
		this._loadCategoryCall.always(function() {
			self._loading = false;
			if (self._filterQuery) {
				// re-set filter
				self.filter(self._filterQuery);
			}
		});
		return this._loadCategoryCall;
	},

	renderApp: function(app, template, selector, firstExperimental) {
		if (!template) {
			var source   = $("#app-template").html();
			template = Handlebars.compile(source);
		}
		if (_.isString(app)) {
			app = OC.Settings.Apps.State.apps[app];
		}
		app.firstExperimental = firstExperimental;

		if (!app.preview) {
			app.preview = OC.imagePath('core', 'default-app-icon');
			app.previewAsIcon = true;
		}

		app.author = this._parseAppAuthor(app.author);

		var html = template(app);
		if (selector) {
			selector.html(html);
		} else {
			$('#apps-list').append(html);
		}

		var page = $('#app-' + app.id);

		// image loading kung-fu (IE doesn't properly scale SVGs, so disable app icons)
		if (app.preview && !OC.Util.isIE()) {
			var currentImage = new Image();
			currentImage.src = app.preview;

			currentImage.onload = function() {
				page.find('.app-image')
					.append(this)
					.fadeIn();
			};
		}

		// set group select properly
		if (OC.Settings.Apps.isProtected(app)) {
			page.find(".groups-enable").hide();
			page.find(".groups-enable__checkbox").prop('checked', false);
		} else {
			page.find('#group_select').val((app.groups || []).join('|'));
			if (app.active) {
				if (app.groups.length) {
					OC.Settings.Apps.setupGroupsSelect(page.find('#group_select'));
					page.find(".groups-enable__checkbox").prop('checked', true);
				} else {
					page.find(".groups-enable__checkbox").prop('checked', false);
				}
				page.find(".groups-enable").show();
			} else {
				page.find(".groups-enable").hide();
			}
		}
	},

	/**
	 * Parses the author(s) from the app info response.
	 *
	 * @param {(string|string[]|Object|Object[])} author - A string or an array of Objects or strings or both representing the author info from apps info.xml.
	 * @return {string}
	 */
	_parseAppAuthor: function (author) {
		if (_.isObject(author) && !_.isUndefined(author['@value'])) {
			return author['@value'];
		}

		if (_.isArray(author)) {
			var authorNames = [];
			for (var i = 0; i < author.length; i++) {
				if (_.isObject(author[i]) && !_.isUndefined(author[i]['@value'])) {
					authorNames.push(author[i]['@value']);
				} else {
					authorNames.push(author[i]);
				}
			}
			return authorNames.join(', ');
		}

		return author;
	},

	/**
	 * Checks if enable for groups should be hidden
	 * @param app
	 * @returns {boolean}
	 */
	isProtected: function(app) {
		var protectedTypes = [
			'filesystem',
			'prelogin',
			'authentication',
			'logging',
			'prevent_group_restriction',
			'theme'
		];
		for (var i=0;i<protectedTypes.length;i++) {
			if (OC.Settings.Apps.isType(app, protectedTypes[i])) {
				return true;
			}
		}
		return false;
	},

	isType: function(app, type) {
		return app.types && app.types.indexOf(type) !== -1;
	},

	/**
	 * Checks the server health.
	 *
	 * If the promise fails, the server is broken.
	 *
	 * @return {Promise} promise
	 */
	_checkServerHealth: function() {
		return $.get(OC.generateUrl('apps/files'));
	},

	enableApp:function(appId, active, element, groups) {
		var self = this;
		OC.Settings.Apps.hideErrorMessage(appId);
		groups = groups || [];
		var appItem = $('div#app-'+appId+'');
		element.val(t('settings','Please wait....'));
		if(active && !groups.length) {
			$.post(OC.filePath('settings','ajax','disableapp.php'),{appid:appId},function(result) {
				if(!result || result.status !== 'success') {
					if (result.data && result.data.message) {
						OC.Settings.Apps.showErrorMessage(appId, result.data.message);
						appItem.data('errormsg', result.data.message);
					} else {
						OC.Settings.Apps.showErrorMessage(appId, t('settings', 'Error while disabling app'));
						appItem.data('errormsg', t('settings', 'Error while disabling app'));
					}
					element.val(t('settings','Disable'));
					appItem.addClass('appwarning');
				} else {
					OC.Settings.Apps.rebuildNavigation();
					appItem.data('active',false);
					appItem.data('groups', '');
					element.data('active',false);
					appItem.removeClass('active');
					element.val(t('settings','Enable'));
					element.parent().find(".groups-enable").hide();
					element.parent().find('#group_select').hide().val(null);
					OC.Settings.Apps.State.apps[appId].active = false;
				}
			},'json');
		} else {
			// TODO: display message to admin to not refresh the page!
			// TODO: lock UI to prevent further operations
			$.post(OC.filePath('settings','ajax','enableapp.php'),{appid: appId, groups: groups},function(result) {
				if(!result || result.status !== 'success') {
					if (result.data && result.data.message) {
						OC.Settings.Apps.showErrorMessage(appId, result.data.message);
						appItem.data('errormsg', result.data.message);
					} else {
						OC.Settings.Apps.showErrorMessage(appId, t('settings', 'Error while enabling app'));
						appItem.data('errormsg', t('settings', 'Error while disabling app'));
					}
					element.val(t('settings','Enable'));
					appItem.addClass('appwarning');
				} else {
					self._checkServerHealth().done(function() {
						if (result.data.update_required) {
							OC.Settings.Apps.showReloadMessage();

							setTimeout(function() {
								location.reload();
							}, 5000);
						}

						OC.Settings.Apps.rebuildNavigation();
						appItem.data('active',true);
						element.data('active',true);
						appItem.addClass('active');
						element.val(t('settings','Disable'));
						var app = OC.Settings.Apps.State.apps[appId];
						app.active = true;

						if (OC.Settings.Apps.isType(app, 'filesystem') || OC.Settings.Apps.isType(app, 'prelogin') ||
							OC.Settings.Apps.isType(app, 'authentication') || OC.Settings.Apps.isType(app, 'logging')) {
							element.parent().find(".groups-enable").prop('checked', true);
							element.parent().find(".groups-enable").hide();
							element.parent().find('#group_select').hide().val(null);
						} else {
							element.parent().find("#groups-enable").show();
							if (groups) {
								appItem.data('groups', JSON.stringify(groups));
							} else {
								appItem.data('groups', '');
							}
						}
					}).fail(function() {
						// server borked, emergency disable app
						$.post(OC.webroot + '/index.php/disableapp', {appid: appId}, function() {
							OC.Settings.Apps.showErrorMessage(
								appId,
								t('settings', 'Error: this app cannot be enabled because it makes the server unstable')
							);
							appItem.data('errormsg', t('settings', 'Error while enabling app'));
							element.val(t('settings','Enable'));
							appItem.addClass('appwarning');
						}).fail(function() {
							OC.Settings.Apps.showErrorMessage(
								appId,
								t('settings', 'Error: could not disable broken app')
							);
							appItem.data('errormsg', t('settings', 'Error while disabling broken app'));
							element.val(t('settings','Enable'));
						});
					});
				}
			},'json')
				.fail(function() {
					OC.Settings.Apps.showErrorMessage(appId, t('settings', 'Error while enabling app'));
					appItem.data('errormsg', t('settings', 'Error while enabling app'));
					appItem.data('active',false);
					appItem.addClass('appwarning');
					element.val(t('settings','Enable'));
				});
		}
	},

	updateApp:function(appId, element) {
		var oldButtonText = element.val();
		element.val(t('settings','Updating....'));
		OC.Settings.Apps.hideErrorMessage(appId);
		$.post(OC.filePath('settings','ajax','updateapp.php'),{appid:appId},function(result) {
			if(!result || result.status !== 'success') {
				if (result.data && result.data.message) {
					OC.Settings.Apps.showErrorMessage(appId, result.data.message);
				} else {
					OC.Settings.Apps.showErrorMessage(appId, t('settings','Error while updating app'));
				}
				element.val(oldButtonText);
			}
			else {
				element.val(t('settings','Updated'));
				element.hide();
			}
		},'json');
	},

	uninstallApp:function(appId, element) {
		OC.Settings.Apps.hideErrorMessage(appId);
		element.val(t('settings','Uninstalling ....'));
		$.post(OC.filePath('settings','ajax','uninstallapp.php'),{appid:appId},function(result) {
			if(!result || result.status !== 'success') {
				OC.Settings.Apps.showErrorMessage(appId, t('settings','Error while uninstalling app'));
				element.val(t('settings','Uninstall'));
			} else {
				OC.Settings.Apps.rebuildNavigation();
				element.parent().fadeOut(function() {
					element.remove();
				});
			}
		},'json');
	},

	rebuildNavigation: function() {
		$.getJSON(OC.filePath('settings', 'ajax', 'navigationdetect.php')).done(function(response){
			if(response.status === 'success'){
				var idsToKeep = {};
				var navEntries=response.nav_entries;
				var container = $('#apps ul');
				for(var i=0; i< navEntries.length; i++){
					var entry = navEntries[i];
					idsToKeep[entry.id] = true;

					if(container.children('li[data-id="'+entry.id+'"]').length === 0){
						var li=$('

');
						li.attr('data-id', entry.id);
						var img= $('').attr({ src: entry.icon});
						var a=$('').attr('href', entry.href);
						var filename=$('');
						var loading = $('

').css('display', 'none');
						filename.text(entry.name);
						a.prepend(filename);
						a.prepend(loading);
						a.prepend(img);
						li.append(a);

						// append the new app as last item in the list
						// which is the "add apps" entry with the id
						// #apps-management
						$('#apps-management').before(li);

						// scroll the app navigation down
						// so the newly added app is seen
						$('#navigation').animate({
							scrollTop: $('#navigation').height()
						}, 'slow');

						// draw attention to the newly added app entry
						// by flashing it twice
						$('#header .menutoggle')
							.animate({opacity: 0.5})
							.animate({opacity: 1})
							.animate({opacity: 0.5})
							.animate({opacity: 1})
							.animate({opacity: 0.75});

						if (!OC.Util.hasSVGSupport() && entry.icon.match(/\.svg$/i)) {
							$(img).addClass('svg');
							OC.Util.replaceSVG();
						}
					}
				}

				container.children('li[data-id]').each(function(index, el) {
					if (!idsToKeep[$(el).data('id')]) {
						$(el).remove();
					}
				});
			}
		});
	},

	showErrorMessage: function(appId, message) {
		$('div#app-'+appId+' .warning')
			.show()
			.text(message);
	},

	hideErrorMessage: function(appId) {
		$('div#app-'+appId+' .warning')
			.hide()
			.text('');
	},

	showReloadMessage: function() {
		OC.dialogs.info(
			t(
				'settings',
				'The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds.'
			),
			t('settings','App update'),
			function () {
				window.location.reload();
			},
			true
		);
	},

	filter: function(query) {
		// FIXME: the caller doesn't properly set the "this" context
		var self = OC.Settings.Apps;
		self._filterQuery = query;

		var $appList = $('#apps-list'),
			$emptyList = $('#apps-list-empty');
		$appList.removeClass('hidden');
		$appList.find('.section').removeClass('hidden');
		$emptyList.addClass('hidden');

		if (self._loading) {
			return;
		}

		if (query === '') {
			return;
		}

		query = query.toLowerCase();
		$appList.find('.section').addClass('hidden');

		// App Name
		var apps = _.filter(OC.Settings.Apps.State.apps, function (app) {
			return app.name.toLowerCase().indexOf(query) !== -1;
		});

		// App ID
		apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
			return app.id.toLowerCase().indexOf(query) !== -1;
		}));

		// App Description
		apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
			return app.description.toLowerCase().indexOf(query) !== -1;
		}));

		// Author Name
		apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
			if (_.isUndefined(app.author)) {
				return false;
			}
			return self._parseAppAuthor(app.author).toLowerCase().indexOf(query) !== -1;
		}));

		// App status
		if (t('settings', 'Official').toLowerCase().indexOf(query) !== -1) {
			apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
				return app.level === 200;
			}));
		}
		if (t('settings', 'Approved').toLowerCase().indexOf(query) !== -1) {
			apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
				return app.level === 100;
			}));
		}
		if (t('settings', 'Experimental').toLowerCase().indexOf(query) !== -1) {
			apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
				return app.level !== 100 && app.level !== 200;
			}));
		}

		apps = _.uniq(apps, function(app){return app.id;});

		if (apps.length === 0) {
			$appList.addClass('hidden');
			$emptyList.removeClass('hidden');
			$emptyList.removeClass('hidden').find('h2').text(t('settings', 'No apps found for {query}', {
				query: query
			}));
		} else {
			_.each(apps, function (app) {
				$('#app-' + app.id).removeClass('hidden');
			});

			$('#searchresults').hide();
		}
	},

	_onPopState: function(params) {
		params = _.extend({
			category: 'enabled'
		}, params);

		OC.Settings.Apps.loadCategory(params.category);
	},

	/**
	 * Initializes the apps list
	 */
	initialize: function($el) {
		OC.Plugins.register('OCA.Search', OC.Settings.Apps.Search);
		OC.Settings.Apps.loadCategories();
		OC.Util.History.addOnPopStateHandler(_.bind(this._onPopState, this));

		$(document).on('click', '#apps-header button', function () {
			var categoryId = $(this).data('category');
			OC.Settings.Apps.loadCategory(categoryId);
			OC.Util.History.pushState({
				sectionid: 'apps',
				category: categoryId
			});
			$('#searchbox').val('');
		});

		$(document).on('click', '.app-description-toggle-show', function () {
			$(this).addClass('hidden');
			$(this).siblings('.app-description-toggle-hide').removeClass('hidden');
			$(this).siblings('.app-description-container').slideDown();
		});
		$(document).on('click', '.app-description-toggle-hide', function () {
			$(this).addClass('hidden');
			$(this).siblings('.app-description-toggle-show').removeClass('hidden');
			$(this).siblings('.app-description-container').slideUp();
		});

		$(document).on('click', '#apps-list input.enable', function () {
			var appId = $(this).data('appid');
			var element = $(this);
			var active = $(this).data('active');

			OC.Settings.Apps.enableApp(appId, active, element);
		});

		$(document).on('click', '#apps-list input.uninstall', function () {
			var appId = $(this).data('appid');
			var element = $(this);

			OC.Settings.Apps.uninstallApp(appId, element);
		});

		$(document).on('click', '#apps-list input.update', function () {
			var appId = $(this).data('appid');
			var element = $(this);

			OC.Settings.Apps.updateApp(appId, element);
		});

		$(document).on('change', '#group_select', function() {
			var element = $(this).parent().find('input.enable');
			var groups = $(this).val();
			if (groups && groups !== '') {
				groups = groups.split('|');
			} else {
				groups = [];
			}

			var appId = element.data('appid');
			if (appId) {
				OC.Settings.Apps.enableApp(appId, false, element, groups);
				OC.Settings.Apps.State.apps[appId].groups = groups;
			}
		});

		$(document).on('change', ".groups-enable__checkbox", function() {
			var $select = $(this).closest('.section').find('#group_select');
			$select.val('');

			if (this.checked) {
				OC.Settings.Apps.setupGroupsSelect($select);
			} else {
				$select.select2('destroy');
			}

			$select.change();
		});
	}
};

OC.Settings.Apps.Search = {
	attach: function (search) {
		search.setFilter('settings', OC.Settings.Apps.filter);
	}
};

$(document).ready(function () {
	// HACK: FIXME: use plugin approach
	if (!window.TESTING) {
		OC.Settings.Apps.initialize($('#apps-list'));
	}
});


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

namespace HCEngine
{
    /// <summary>
    ///     Interface for loaded scripts
    /// </summary>
    public interface IScript
    {
        /// <summary>
        ///     Expected arguments types for the script, keyed by identifiers
        /// </summary>
        IDictionary<string, Type> ExpectedArguments { get; }

        /// <summary>
        ///     Creates a <see cref="IScriptExecution" /> for this script with the given arguments
        /// </summary>
        /// <param name="arguments">The arguments to give to the script execution, as a map from identifier to instance</param>
        /// <returns>The execution object</returns>
        IScriptExecution Run(IDictionary<string, object> arguments);
    }
}


text:
package eu.hansolo.enzo.experimental.pbutton;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.BooleanPropertyBase;
import javafx.css.PseudoClass;
import javafx.scene.control.Control;

public class PushButton extends Control {
    private static final PseudoClass SELECTED_PSEUDO_CLASS = PseudoClass.getPseudoClass("selected");
    private boolean                  keepAspect;
    private BooleanProperty          selected;

    // ******************** Constructors **************************************
    public PushButton() {
        getStyleClass().add("push-button");
        keepAspect    = true;
    }

    // ******************** Methods *******************************************
    public final boolean isKeepAspect() {
        return keepAspect;
    }
    public final void setKeepAspect(final boolean KEEP_ASPECT) {
        keepAspect = KEEP_ASPECT;
    }

    public final boolean isSelected() {
        return null == selected ? false : selected.get();
    }
    public final void setSelected(final boolean SELECTED) {
        selectedProperty().set(SELECTED);
    }
    public final BooleanProperty selectedProperty() {
        if (null == selected) {
            selected = new BooleanPropertyBase(false) {
                @Override protected void invalidated() { pseudoClassStateChanged(SELECTED_PSEUDO_CLASS, get()); }
                @Override public Object getBean() { return this; }
                @Override public String getName() { return "selected"; }
            };
        }
        return selected;
    }

    @Override public boolean isResizable() {
        return true;
    }

    // ******************** Style related *************************************
    @Override public String getUserAgentStylesheet() {
        return getClass().getResource(getClass().getSimpleName().toLowerCase() + ".css").toExternalForm();
    }
}


text:
package com.evanzeimet.queryinfo.jpa.join;

public class QueryInfoJoinInfoBuilder {

	private QueryInfoJoinInfo builderReferenceInstance = new DefaultQueryInfoJoinInfo();

	public QueryInfoJoinInfoBuilder() {

	}

	public QueryInfoJoinInfo build() {
		QueryInfoJoinInfo result = new DefaultQueryInfoJoinInfo();

		result.setEntityClass(builderReferenceInstance.getEntityClass());
		result.setJpaAttributeName(builderReferenceInstance.getJpaAttributeName());
		result.setJoinType(builderReferenceInstance.getJoinType());
		result.setName(builderReferenceInstance.getName());

		return result;
	}

	public QueryInfoJoinInfoBuilder annotation(QueryInfoJoin annotation) {
		String name = annotation.name();

		Class<?> entityClass = annotation.entityClass();
		if (QueryInfoJoin.class.equals(entityClass)) {
			entityClass = null;
		}

		QueryInfoJoinType joinType = annotation.joinType();

		return joinType(joinType)
				.entityClass(entityClass)
				.name(name);
	}

	public static QueryInfoJoinInfoBuilder create() {
		return new QueryInfoJoinInfoBuilder();
	}

	public QueryInfoJoinInfoBuilder entityClass(Class<?> entityClass) {
		builderReferenceInstance.setEntityClass(entityClass);
		return this;
	}

	public QueryInfoJoinInfoBuilder jpaAttributeName(String jpaAttributeName) {
		builderReferenceInstance.setJpaAttributeName(jpaAttributeName);
		return this;
	}

	public QueryInfoJoinInfoBuilder joinType(QueryInfoJoinType joinType) {
		builderReferenceInstance.setJoinType(joinType);
		return this;
	}

	public QueryInfoJoinInfoBuilder name(String name) {
		builderReferenceInstance.setName(name);
		return this;
	}

}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M19 10.41V15h2V7h-8v2h4.59L12 14.59 4.41 7 3 8.41l9 9z"
}), 'CallMissedOutgoingTwoTone');
exports.default = _default;


text:
package vtk.repository.search.query;

import java.util.Objects;

/**
 * Term query (exact match) on resource URI.
 */
public class UriTermQuery implements UriQuery {

    private static final long serialVersionUID = 2960145039692424376L;

    private final String uri;
    private final TermOperator op;

    public UriTermQuery(String uri, TermOperator operator) {
        this.uri = uri;
        this.op = operator;
    }

    public String getUri() {
        return this.uri;
    }

    public TermOperator getOperator() {
        return this.op;
    }

    @Override
    public Object accept(QueryVisitor visitor, Object data) {
        return visitor.visit(this, data);
    }

    @Override
    public String toString() {
        return "UriTermQuery{" + "uri=" + uri + ", op=" + op + '}';
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 61 * hash + Objects.hashCode(this.uri);
        hash = 61 * hash + Objects.hashCode(this.op);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final UriTermQuery other = (UriTermQuery) obj;
        if (!Objects.equals(this.uri, other.uri)) {
            return false;
        }
        if (this.op != other.op) {
            return false;
        }
        return true;
    }

}


text:
<?php

namespace Symfony\Component\Messenger\Transport;

use Symfony\Component\Messenger\Envelope;

/**
 * @author Tobias Schultze <http://tobion.de>
 */
class ChainSender implements SenderInterface
{
    private $senders;

    /**
     * @param SenderInterface[] $senders
     */
    public function __construct(iterable $senders)
    {
        $this->senders = $senders;
    }

    /**
     * {@inheritdoc}
     */
    public function send(Envelope $message): void
    {
        foreach ($this->senders as $sender) {
            $sender->send($message);
        }
    }
}


text:
describe('Creating a program', function() {

  it('should navigate to create program page', function() {
    browser.get('http://localhost:9000/admin/programs');
    var create = element(by.buttonText('Create New Program'));
    create.click();

    expect(browser.getCurrentUrl()).toEqual('http://localhost:9000/admin/programs/create');
  });

  it('should fill in the name of the program', function() {
  	var name = element(by.model('newProgram.name'));
  	name.sendKeys('Tae Kwon Do Test');

  	expect(name.getText()).toEqual('Tae Kwon Do Test');
  });

  it('should create program', function() {
  	var create = element(by.buttonText('Create Program'));
  	create.click();

  	expect(browser.getCurrentUrl()).toEqual('http://localhost:9000/admin/programs');
  });

  it('should appear in the list of programs', function() {
  	var pros = element.all(by.repeater('row in renderedRows'));

  	expect(pros.count()).toEqual(1);
  });

});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UmbracoDataGenerator.Library.Services.Interfaces
{
    public interface INodeService
    {
        /// <summary>
        /// Returns generated Node Ids
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="docType"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        IEnumerable<int> CreateNodes(int parentId, string docType, int count);
    }
}


text:
"""
This script is intended to be used to automate the application of
configurations, via a console connection, for devices that
support Cisco's IOx platform.

It assumes that there are one or more devices connected, typically via a mini-USB
cable, to the machine upon which this script is running. For example, a MacBookPro
with three such devices connected with a USB hub.

The script uses pyserial to connect to the serial ports and carry out a set of
interactions. The style is very reminiscent of "expect". That also means, though,
that things don't always work as expected because the CLI wasn't really meant for
automation like this, hence the copious logging.

Note that these drivers will likely be required for pyserial:

https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.aspx#mac

Copyright 2016 Nathan John Sowatskey

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.

"""
from __future__ import print_function

import serial
import time
import sys
import logging
from logging.config import fileConfig
import os
from pyserial_util.cli_utils import *

usb_port_base = "cu.SLAB_USBtoUART"
enable_password = "cisco123"

def main(argv=None):

    device_serial_ports = get_console_ports(usb_port_base)

    logger.info("About to start on these serial ports and devices:\n")
    for dev_ser_port in device_serial_ports:
        logger.info("Port = " + str(dev_ser_port.serial_port) + " device type = " +
                    str(dev_ser_port.device_type) + "\n")

    summary = []

    device_counter = 1
    first_net_tuple = "10"
    second_net_tuple = 42
    lan_dhcp_upper = "2"
    process_images = False

    for dev_ser_port in device_serial_ports:
        skip_device = False

        logger.info("Configuring a " + dev_ser_port.device_type + " at " + dev_ser_port.serial_port.port + ".")

        config = []
        try:
            with open("configs/" + dev_ser_port.device_type + ".cfgtmpl") as config_file:
                for line in config_file:
                    config.append(line)
        except Exception as e:
            logger.error("%s" % e)
            continue

        enable(dev_ser_port.serial_port, enable_password)

        #TODO Refactor to device info class
        num_ports = {'IR829GW-LTE-GA-EK9' : 4, 'IR809G-LTE-GA-K9' : 2}[dev_ser_port.device_type]

        lan_dhcp_upper = str(1+num_ports)

        for line in config:

            if line.startswith("!"):
                continue

            original_line = line

            line = line.replace("<NT1>", first_net_tuple)
            line = line.replace("<NT2>", str(second_net_tuple))
            line = line.replace("<LDU>", lan_dhcp_upper)

            if (process_images):
                if ("#Process images:" in line):
                    line = line.replace("#Process images:", "")

            if (line != original_line):
                logger.debug("Processed config line is " + line)

            if (line.startswith("hostname")):
                line = strip_cr_nl(line) + "-SN" + first_net_tuple + "." + str(second_net_tuple) + ".1.0EN"

            dev_ser_port.serial_port.write(line)

            while True:
                dev_ser_port.serial_port.write("\r")
                time.sleep(1)
                response = strip_cr_nl(dev_ser_port.serial_port.read(dev_ser_port.serial_port.inWaiting()))
                logger.debug("The response is " + response + " whilst adding configuration.")
                if "Invalid" in response:
                    logger.error("The response contained \"Invalid\", which is not OK, so returning.")
                    return 1
                if (response.endswith("#")):
                    logger.debug("Back to # prompt, carrying on.")
                    break
                if (response.endswith(">")):
                    logger.error("We have a > prompt, which is not OK, so skipping this device.")
                    skip_device = True
                    break

            if(skip_device):
                break

        if not skip_device:
            dev_ser_port.serial_port.write("write memory\r")
            time.sleep(1)
            second_net_tuple += 1
            device_counter += 1
            summary.append("Configured a " + dev_ser_port.device_type + " at " + dev_ser_port.serial_port.port + ".")

    logger.info("The summary is:\n")
    for result in summary:
        logger.info(str(result) + "\n")

    return 0

if __name__ == "__main__":
    sys.exit(main())


text:
import '../../broker';

import { api } from '../../../../server/sdk/api';
import { DDPStreamer } from './DDPStreamer';

api.registerService(new DDPStreamer());


text:
import IPoint, { clonePoint } from '../interfaces/point';
import getRandomShape from '../services/random-shape';
import Shape from './shape';

export default class Player {
    private _shape!: Shape;
    public get shape() {
        return this._shape;
    }

    public position!: IPoint;
    private _startingPos: IPoint;

    public softDropPoints = 0;

    constructor(startingPosition: IPoint) {
        this._startingPos = startingPosition;
        this.reset();
    }

    public reset(): void {
        this.position = clonePoint(this._startingPos);
        this._shape = getRandomShape();
        this.softDropPoints = 0;
    }
}


text:
package com.jpeterson.virtlcd.swing;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class DefaultDotMatrixDisplayModelTest extends TestCase {
	/**
	 * Create the test case
	 *
	 * @param testName
	 *            name of the test case
	 */
	public DefaultDotMatrixDisplayModelTest(String testName) {
		super(testName);
	}

	/**
	 * @return the suite of tests being tested
	 */
	public static Test suite() {
		return new TestSuite(DefaultDotMatrixDisplayModelTest.class);
	}

	/**
	 * Test getting/setting the character.
	 */
	public void test_char() {
		DotMatrixDisplayModel model = new DefaultDotMatrixDisplayModel();

		assertEquals("Unexpected text", "", model.getText());
		model.setText("Unit test");
		assertEquals("Unexpected char", "Unit test", model.getText());
	}

	/**
	 * Test adding/removing change listener.
	 */
	public void test_changeListener() {
		DefaultDotMatrixDisplayModel model = new DefaultDotMatrixDisplayModel();
		ChangeListener changeListener = new TestChangeListener();
		ChangeListener[] changeListeners;

		changeListeners = model.getChangeListeners();
		assertEquals("Unexpected number of change listeners", 0,
				changeListeners.length);

		model.addChangeListener(changeListener);

		changeListeners = model.getChangeListeners();
		assertEquals("Unexpected number of change listeners", 1,
				changeListeners.length);
		assertEquals("Unexpected change listener", changeListener,
				changeListeners[0]);

		model.removeChangeListener(changeListener);

		changeListeners = model.getChangeListeners();
		assertEquals("Unexpected number of change listeners", 0,
				changeListeners.length);
	}

	private class TestChangeListener implements ChangeListener {

		public void stateChanged(ChangeEvent e) {
		}

	}
}


text:
package io.mifos.portfolio.api.v1.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * @author Myrle Krantz
 */
@SuppressWarnings("unused")
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = {CheckValidWeek.class}
)
public @interface ValidWeek {
  String message() default "Only weeks 0, 1, 2, or 4, are allowed.";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};
}


text:
@import Foundation;

NS_ASSUME_NONNULL_BEGIN

@protocol ENEncryptorDelegate;
@interface ENEncryptor : NSObject

- (instancetype)initWithSourceURLs:(NSArray <NSURL *> *)sourceURLs;
+ (instancetype)encryptorWithSourceURLs:(NSArray <NSURL *> *)sourceURLs;

@property (weak, nonatomic, nullable) id <ENEncryptorDelegate> delegate;

- (void)encryptWithPassword:(NSString *)password hint:(NSString *)hint preview:(nullable NSImage *)preview;
- (void)cancel;

@end

@protocol ENEncryptorDelegate <NSObject>
@optional

- (void)encryptor:(ENEncryptor *)encryptor didStartWithURLs:(NSArray *)sourceFiles;
- (void)encryptor:(ENEncryptor *)encryptor didFailWithError:(NSError *)error;
- (void)encryptor:(ENEncryptor *)encryptor didFinishWithResultURL:(NSURL *)resultURL;

- (void)encryptor:(ENEncryptor *)encryptor didUpdateProgress:(float)progress;
- (void)encryptor:(ENEncryptor *)encryptor didUpdateEstimationTime:(NSTimeInterval)estimationTime;

@end

NS_ASSUME_NONNULL_END


text:
require "cookies/cookies"
require "ab_test/ab_test"

class SelectRoute
  def initialize(experiment_name, route, config = { experiment_loa: nil,
                                                    trial_enabled: false })
    @experiment_name = experiment_name
    @experiment_route = "#{@experiment_name}_#{route}"
    @experiment_loa = config[:experiment_loa]
    @trial_enabled = config[:trial_enabled]
  end

  def matches?(request)
    if cookie_matches_experiment?(request)
      AbTest.report_ab_test_details(request, @experiment_name) if loa_matches_experiment?(request)
      true
    else
      false
    end
  end

private

  def cookie_matches_experiment?(request)
    request_experiment_route = extract_experiment_route_from_cookie(request.cookies[CookieNames::AB_TEST])
    if @trial_enabled && request.cookies[CookieNames::AB_TEST_TRIAL] == @experiment_name
      true
    else
      @experiment_route == request_experiment_route
    end
  end

  def loa_matches_experiment?(request)
    @experiment_loa.nil? || request.session[:requested_loa] == @experiment_loa
  end

  def extract_experiment_route_from_cookie(ab_test_cookie)
    experiment_name = Cookies.parse_json(ab_test_cookie)[@experiment_name]

    AB_TESTS[@experiment_name] ? AB_TESTS[@experiment_name].alternative_name(experiment_name) : "default"
  end
end


text:
package com.kind.samples.netty.protocal;

/**
 * 说明:
 *
 * @author waylau.com 2015年11月5日
 */
public class ClientTask implements Runnable {

    /**
     *
     */
    public ClientTask() {
        // TODO Auto-generated constructor stub
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            ProtocolClient client = new ProtocolClient("localhost", 8082);

            client.run();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


text:
Retrieves the creation/burned date from a CD (ISO9660/CDFS and UDF formats).

![scdinfo](https://cloud.githubusercontent.com/assets/5137410/5890813/fa79d68a-a4a9-11e4-976e-beabdce08457.png)

Usage requirements:
* None (or more like XP and newer and one or more physical and/or virtual CD drives)

Compilation Requirements:
* Visual Studio 2013
* Possibly the Windows platform SDK

Based on information from:
* [A SuperUser/StackExchange question](http://superuser.com/questions/559031/how-to-find-out-when-a-disc-dvd-has-been-written-burned)
* [ISO 9960 specs](http://wiki.osdev.org/ISO_9660)
* [The UDF 2.60 standard](http://www.osta.org/specs/pdf/udf260.pdf)
* [A Microsoft article on reading sectors from CDs](http://support.microsoft.com/kb/KbView/138434)


text: Syntax grammar for the Jesusonic FX language (EEL2)


text:
package com.bbn.kbp.events2014;

import com.bbn.bue.common.annotations.MoveToBUECommon;
import com.bbn.bue.common.collections.MapUtils;
import com.bbn.bue.common.scoring.Scored;
import com.bbn.bue.common.scoring.Scoreds;
import com.bbn.bue.common.symbols.Symbol;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import static com.bbn.bue.common.collections.IterableUtils.allEqual;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.all;
import static com.google.common.collect.Iterables.getFirst;
import static com.google.common.collect.Iterables.isEmpty;
import static com.google.common.collect.Iterables.transform;

/**
 * Represents a KBP 2014 event argument attachment system's output on a document.
 */
public final class ArgumentOutput {

  public static String DEFAULT_METADATA = "";
  private final Symbol docId;
  private final ImmutableSet<Response> responses;
  private final ImmutableMap<Response, Double> confidences;
  private final ImmutableMap<Response, String> metadata;

  private ArgumentOutput(final Symbol docId, final Iterable<Response> responses,
      final Map<Response, Double> confidences, final Map<Response, String> metadata) {
    this.docId = checkNotNull(docId);
    this.responses = ImmutableSet.copyOf(responses);
    for (final Response response : responses) {
      checkArgument(docId == response.docID(),
          "System output %s contains response with non-matching docid %s",
          docId, response.docID());
    }
    this.confidences = ImmutableMap.copyOf(confidences);
    checkArgument(all(confidences.values(), Range.closed(0.0, 1.0)),
        "System output %s contains confidences outside [0.0,1.0]", docId);
    this.metadata = ImmutableMap.copyOf(metadata);

    checkArgument(metadata.keySet().containsAll(this.responses),
        "Metadata is missing for some responses");
    checkArgument(confidences.keySet().containsAll(this.responses),
        "Confidences are missing for some responses");
  }

  /**
   * All system responses.
   */
  public ImmutableSet<Response> responses() {
    return responses;
  }

  /**
   * All system responses with corresponding scores.  Scores are kept separately from the responses
   * themselves because they do not determine the identity of a response.
   */
  public ImmutableSet<Scored<Response>> scoredResponses() {
    final ImmutableSet.Builder<Scored<Response>> ret = ImmutableSet.builder();

    for (final Response response : responses) {
      ret.add(Scored.from(response, confidence(response)));
    }

    return ret.build();
  }

  public Symbol docId() {
    return docId;
  }

  /**
   * The number of system responses.
   */
  public int size() {
    return responses().size();
  }

  /**
   * Returns the system score/confidence for a response. Throws an exception if the provided
   * response is not found in this assessment store.
   */
  public double confidence(final Response response) {
    checkNotNull(response);
    final Double ret = confidences.get(response);
    if (ret != null) {
      return ret;
    } else {
      throw new RuntimeException(String.format(
          "Tried to lookup confidence of response %s which was not withAdditionalJustifications this system output",
          response));
    }
  }

  /**
   * Same as {@code confidence()} but returns a {@link com.bbn.bue.common.scoring.Scored} object.
   */
  public Scored<Response> score(final Response response) {
    return Scored.from(response, confidence(response));
  }

  public ImmutableMap<Response, String> allMetadata() {
    return metadata;
  }

  public String metadata(final Response response) {
    checkNotNull(response);
    return metadata.get(response);
  }

  /**
   * Implements the selection strategy to use when the system provides the same response with
   * multiple justifications.  From the provided responses, it prefers the response with the highest
   * score.  If there is a tie, it prefers the response with the higher hash code. If no responses
   * are provided, {@code Optional.absent()} is returned.
   */
  public Optional<Response> selectFromMultipleSystemResponses(final Collection<Response> args) {
    if (args.isEmpty()) {
      return Optional.absent();
    }
    if (args.size() == 1) {
      // will never return null because size is 1
      return Optional.of(getFirst(args, null));
    }

    return Optional.of(Collections.max(args, ByConfidenceThenOld2014ID));
  }

  public static ArgumentOutput createWithoutMetadata(final Symbol docId,
      final Iterable<Scored<Response>> scoredResponses) {
    final Map<Response, String> emptyMetadata = Maps.asMap(FluentIterable.from(scoredResponses)
        .transform(Scoreds.<Response>itemsOnly()).toSet(), Functions.constant(DEFAULT_METADATA));
    return from(docId, scoredResponses, emptyMetadata);
  }

  /**
   * Deprecated due to the addition of metadata tracking - older Functions which filtered responses
   * and constructed new SystemOutputs are now broken for analystics use because they do not
   * preserve metadata use @see ArgumentOutput#createWithoutMetadata
   */
  @Deprecated
  public static ArgumentOutput from(final Symbol docId,
      final Iterable<Scored<Response>> scoredResponses) {
    return createWithoutMetadata(docId, scoredResponses);
  }

  /**
   * retains only metadata pertaining to responses for which we have a score.
   */
  public static ArgumentOutput from(final Symbol docId,
      final Iterable<Scored<Response>> scoredResponses, final Map<Response, String> metadata) {
    ImmutableSet<Response> responses =
        ImmutableSet.copyOf(transform(scoredResponses, Scoreds.<Response>itemsOnly()));
    return new ArgumentOutput(docId, responses, Scoreds.asMapKeepingHigestScore(scoredResponses),
        Maps.filterKeys(metadata, Predicates.in(responses)));
  }

  public static ArgumentOutput createFromScoredAndMetadata(final Symbol docId,
      final Iterable<Scored<Response>> scoredResponses,
      final Map<Scored<Response>, String> metadata) {
    final Map<Response, Double> scores = Scoreds.asMapKeepingHigestScore(scoredResponses);
    final Iterable<Scored<Response>> highest =
        transform(scores.entrySet(), Scoreds.<Response>mapEntryToDoubleToScored());
    final Map<Response, String> responseToMetadata = MapUtils.copyWithKeysTransformedByInjection(
        Maps.filterKeys(metadata, Predicates.in(ImmutableSet.copyOf(highest))),
        Scoreds.<Response>itemsOnly());
    return new ArgumentOutput(docId, scores.keySet(), scores, responseToMetadata);
  }

  private final Ordering<Response> ByConfidenceThenOld2014ID = new Ordering<Response>() {
    @Override
    public int compare(final Response left, final Response right) {
      return ComparisonChain.start()
          .compare(confidence(left), confidence(right))
          .compare(left.old2014ResponseID(),
              right.old2014ResponseID())
          .result();
    }
  };

  public static final Function<ArgumentOutput, Symbol> DocID = new Function<ArgumentOutput, Symbol>() {
    @Override
    public Symbol apply(ArgumentOutput input) {
      return input.docId();
    }
  };

  public static final Function<ArgumentOutput, ImmutableSet<Response>> Responses =
      new Function<ArgumentOutput, ImmutableSet<Response>>() {
        @Override
        public ImmutableSet<Response> apply(ArgumentOutput input) {
          return input.responses();
        }
      };

  /**
   * keeps the metadata associated with the highest score for a given Response, e.g. in the case of
   * multiple derivations
   */
  public static ArgumentOutput unionKeepingMaximumScore(Iterable<ArgumentOutput> systemOutputs) {
    checkArgument(!isEmpty(systemOutputs), "Cannot take union of zero system outputs");
    checkArgument(allEqual(transform(systemOutputs, DocID)),
        "Cannot take the union of system outputs with different docids");
    final Map<Response, Double> responseToScore = new HashMap<Response, Double>();
    final Map<Response, Scored<Response>> scoredResponses =
        new HashMap<Response, Scored<Response>>();
    final Map<Response, String> responseToMetadata = new HashMap<Response, String>();
    for (final ArgumentOutput output : systemOutputs) {
      for (final Scored<Response> scoredResponse : output.scoredResponses()) {
        final Double score = responseToScore.get(scoredResponse.item());
        if (score == null || score < scoredResponse.score()) {
          responseToScore.put(scoredResponse.item(), scoredResponse.score());
          responseToMetadata.put(scoredResponse.item(), output.metadata(scoredResponse.item()));
          scoredResponses.put(scoredResponse.item(), scoredResponse);
        }
      }
    }

    return ArgumentOutput
        .from(getFirst(systemOutputs, null).docId(), scoredResponses.values(), responseToMetadata);
  }

  public ArgumentOutput copyWithFilteredResponses(Predicate<Scored<Response>> predicate) {
    final Iterable<Scored<Response>> scoredResponses =
        Iterables.filter(scoredResponses(), predicate);
    final ImmutableSet<Response> responses = ImmutableSet.copyOf(
        transform(scoredResponses, Scoreds.<Response>itemsOnly()));
    final Predicate<Response> retainedResponse = Predicates.in(responses);
    // retain only the responses and metadata that this predicate filters
    return ArgumentOutput
        .from(docId(), scoredResponses, Maps.filterKeys(metadata, retainedResponse));
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(docId, responses, confidences);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
      return false;
    }
    final ArgumentOutput other = (ArgumentOutput) obj;
    return Objects.equal(this.docId, other.docId) && Objects.equal(this.responses, other.responses)
        && Objects.equal(this.confidences, other.confidences);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this).add("docID", docId).add("scoredResponses",
        scoredResponses()).toString();
  }

  /**
   * For testing
   */
  public static ArgumentOutput createWithConstantScore(final Symbol docID,
      final Iterable<Response> responses, final double score) {
    return createWithoutMetadata(docID,
        Iterables.transform(responses, ArgumentOutput.<Response>withConstantScoreFunction(
            score)));
  }

  @MoveToBUECommon
  private static <T> Function<T, Scored<T>> withConstantScoreFunction(final double score) {
    return new Function<T, Scored<T>>() {
      @Override
      public Scored<T> apply(final T input) {
        return Scored.from(input, score);
      }
    };
  }

  public Builder modifiedCopyBuilder() {
    return new Builder(docId(), Sets.newHashSet(responses), Maps.newHashMap(confidences),
        Maps.newHashMap(metadata));
  }

  public static final class Builder {

    private final Symbol docId;
    private final Set<Response> responses;
    private final Map<Response, Double> confidences;
    private final Map<Response, String> metadata;

    private Builder(final Symbol docId, final Set<Response> responses,
        final Map<Response, Double> confidences,
        final Map<Response, String> metadata) {
      this.confidences = confidences;
      this.docId = docId;
      this.responses = responses;
      this.metadata = metadata;
    }

    /**
     * Replaces {@code oldResponse} with {@code newResponse}. {@code oldResponse} must have been
     * previously added or a {@link NoSuchElementException} will be thrown.  If {@code newResponse}
     * is already present, we compare the score of {@code oldResponse} and {@code newResponse} and use
     * the score and metadata of the higher one. Otherwise, {@code
     * newResponse} will inherit {@code oldResponse}'s score and metadata.
     */
    public void replaceResponseKeepingBestScoreAndMetadata(Response oldResponse,
        Response newResponse) {
      if (!responses.contains(oldResponse)) {
        throw new NoSuchElementException("Cannot replace response " + oldResponse
            + " because it is not present");
      }

      if (oldResponse.equals(newResponse)) {
        return;
      }

      if (!responses.contains(newResponse) || confidences.get(oldResponse)>confidences.get(newResponse)) {
        confidences.put(newResponse, confidences.get(oldResponse));
        metadata.put(newResponse, metadata.get(oldResponse));
      }

      responses.add(newResponse);
      responses.remove(oldResponse);
      confidences.remove(oldResponse);
      metadata.remove(oldResponse);
    }

    public Builder remove(Response response) {
      responses.remove(response);
      confidences.remove(response);
      metadata.remove(response);
      return this;
    }

    public ArgumentOutput build() {
      return new ArgumentOutput(docId, responses, confidences, metadata);
    }
  }
}


text:
<?php

namespace Lrhost\Frontend\Controllers;

class ServicosController extends ControllerBase {

    public function initialize() {
        //Set the document title
        $this->tag->setTitle('Serviços');
        parent::initialize();
    }

    public function indexAction() {

    }

    public function webAction() {

    }

    public function automacaoAction() {

    }

    public function mobileAction() {

    }

    public function consultoriaAction() {

    }

    public function seoAction() {

    }

    public function redesAction() {

    }

    public function cursosAction() {

    }

    public function manutencaoAction() {

    }

}


text:
NOTE: This is a DRAFT of the Go 1.6 release notes, prepared for the Go 1.6 beta.
Go 1.6 has NOT yet been released.
By our regular schedule, it is expected some time in February 2016.

Introduction to Go 1.6

The latest Go release, version 1.6, arrives six months after 1.5.
Most of its changes are in the implementation of the language, runtime, and libraries.
There are no changes to the language specification.
As always, the release maintains the Go 1 promise of compatibility.
We expect almost all Go programs to continue to compile and run as before.

The release adds new ports to Linux on 64-bit MIPS and Android on 32-bit x86;
defined and enforced rules for sharing Go pointers with C;
transparent, automatic support for HTTP/2;
and a new mechanism for template reuse.

Changes to the language

There are no language changes in this release.

Ports

Go 1.6 adds experimental ports to
Linux on 64-bit MIPS (linux/mips64 and linux/mips64le).
These ports support cgo but only with internal linking.

Go 1.6 also adds an experimental port to Android on 32-bit x86 (android/386).

On FreeBSD, Go 1.6 defaults to using clang, not gcc, as the external C compiler.

On Linux on little-endian 64-bit PowerPC (linux/ppc64le),
Go 1.6 now supports cgo with external linking and
is roughly feature complete.

On NaCl, Go 1.5 required SDK version pepper-41.
Go 1.6 adds support for later SDK versions.

TODO: CX no longer available on 386 assembly? (https://golang.org/cl/16386)

Tools

Cgo

There is one major change to cgo, along with one minor change.

The major change is the definition of rules for sharing Go pointers with C code,
to ensure that such C code can coexist with Go's garbage collector.
Briefly, Go and C may share memory allocated by Go
when a pointer to that memory is passed to C as part of a cgo call,
provided that the memory itself contains no pointers to Go-allocated memory,
and provided that C does not retain the pointer after the call returns.
These rules are checked by the runtime during program execution:
if the runtime detects a violation, it prints a diagnosis and crashes the program.
The checks can be disabled by setting the environment variable
GODEBUG=cgocheck=0, but note that the vast majority of
code identified by the checks is subtly incompatible with garbage collection
in one way or another.
Disabling the checks will typically only lead to more mysterious failure modes.
Fixing the code in question should be strongly preferred
over turning off the checks.
See the cgo documentation for more details.

The minor change is
the addition of explicit C.complexfloat and C.complexdouble types,
separate from Go's complex64 and complex128.
Matching the other numeric types, C's complex types and Go's complex type are
no longer interchangeable.

Compiler Toolchain

The compiler toolchain is mostly unchanged.
Internally, the most significant change is that the parser is now hand-written
instead of generated from yacc.

The compiler, linker, and go command have new flag -msan,
analogous to -race and only available on linux/amd64,
that enables interoperation with the Clang MemorySanitizer.
Such interoperation useful mainly for testing a program containing suspect C or C++ code.

The linker has a new option -libgcc to set the expected location
of the C compiler support library when linking cgo code.
The option is only consulted when using -linkmode=internal,
and it may be set to none to disable the use of a support library.

TODO: Something about build modes.

As a reminder, the linker's -X flag changed in Go 1.5.
In Go 1.4 and earlier, it took two arguments, as in

-X importpath.name value

Go 1.5 added an alternative syntax using a single argument
that is itself a name=value pair:

-X importpath.name=value

In Go 1.5 the old syntax was still accepted, after printing a warning
suggesting use of the new syntax instead.
Go 1.6 continues to accept the old syntax and print the warning.
Go 1.7 will remove support for the old syntax.

Gccgo

The release schedules for the GCC and Go projects do not coincide.
GCC release 5 contains the Go 1.4 version of gccgo.
The next release, GCC 6, will have the Go 1.5 version of gccgo.
Due to release scheduling, it is likely that
Go 1.6 will not be in a GCC release until GCC 7.

Go command

The go command's basic operation
is unchanged, but there are a number of changes worth noting.

Go 1.5 introduced experimental support for vendoring,
enabled by setting the GO15VENDOREXPERIMENT environment variable to 1.
Go 1.6 keeps the vendoring support, no longer considered experimental,
and enables it by default.
It can be disabled explicitly by setting
the GO15VENDOREXPERIMENT environment variable to 0.
Go 1.7 will remove support for the environment variable.

The most likely problem caused by enabling vendoring by default happens
in source trees containing an existing directory named vendor that
does not expect to be interpreted according to new vendoring semantics.
In this case, the simplest fix is to rename the directory to anything other
than vendor and update any affected import paths.

For details about vendoring,
see the documentation for the go command
and the design document.

There is a new build flag, -msan,
that compiles Go with support for the LLVM memory sanitizer.
This is intended mainly for use when linking against C or C++ code
that is being checked with the memory sanitizer.

Go doc command

Go 1.5 introduced the
go doc command,
which allows references to packages using only the package name, as in
go doc http.
In the event of ambiguity, the Go 1.5 behavior was to use the package
with the lexicographically earliest import path.
In Go 1.6, ambiguity is resolved by preferring import paths with
fewer elements, breaking ties using lexicographic comparison.
An important effect of this change is that original copies of packages
are now preferred over vendored copies.
Successful searches also tend to run faster.

Go vet command

The go vet command now diagnoses
passing function or method values as arguments to Printf,
such as when passing f where f() was intended.

Performance

As always, the changes are so general and varied that precise statements
about performance are difficult to make.
Some programs may run faster, some slower.
On average the programs in the Go 1 benchmark suite run a few percent faster in Go 1.6
than they did in Go 1.5.
The garbage collector's pauses are even lower than in Go 1.5,
although the effect is likely only noticeable for programs using
a large amount of memory.

There have been significant optimizations bringing more than 10% improvements
to implementations of the
compress/bzip2,
compress/gzip,
crypto/aes,
crypto/elliptic,
crypto/ecdsa, and
sort packages.

Core library

HTTP/2

Go 1.6 adds transparent support in the
net/http package
for the new HTTP/2 protocol.
Go clients and servers will automatically use HTTP/2 as appropriate when using HTTPS.
There is no exported API specific to details of the HTTP/2 protocol handling,
just as there is no exported API specific to HTTP/1.1.

Programs that must disable HTTP/2 can do so by setting
Transport.TLSNextProto (for clients)
or
Server.TLSNextProto (for servers)
to a non-nil, empty map.

Programs that must adjust HTTP/2 protocol-specific details can import and use
golang.org/x/net/http2,
in particular its
ConfigureServer
and
ConfigureTransport
functions.

Runtime

The runtime has added lightweight, best-effort detection of concurrent misuse of maps.
As always, if one goroutine is writing to a map, no other goroutine should be
reading or writing the map concurrently.
If the runtime detects this condition, it prints a diagnosis and crashes the program.
The best way to find out more about the problem is to run the program
under the
race detector,
which will more reliably identify the race
and give more detail.

For program-ending panics, the runtime now by default
prints only the stack of the running goroutine,
not all existing goroutines.
Usually only the current goroutine is relevant to a panic,
so omitting the others significantly reduces irrelevant output
in a crash message.
To see the stacks from all goroutines in crash messages, set the environment variable
GOTRACEBACK to all
or call
debug.SetTraceback
before the crash, and rerun the program.
See the runtime documentation for details.

Updating:
Uncaught panics intended to dump the state of the entire program,
such as when a timeout is detected or when explicitly handling a received signal,
should now call debug.SetTraceback("all") before panicking.
Searching for uses of
signal.Notify may help identify such code.

Reflect

The
reflect package has
resolved a long-standing incompatibility
between the gc and gccgo toolchains
regarding embedded unexported struct types containing exported fields.
Code that walks data structures using reflection, especially to implement
serialization in the spirit
of the
encoding/json and
encoding/xml packages,
may need to be updated.

The problem arises when using reflection to walk through
an embedded unexported struct-typed field
into an exported field of that struct.
In this case, reflect had incorrectly reported
the embedded field as exported, by returning an empty Field.PkgPath.
Now it correctly reports the field as unexported
but ignores that fact when evaluating access to exported fields
contained within the struct.

Updating:
Typically, code that previously walked over structs and used

f.PkgPath != ""

to exclude inaccessible fields
should now use

f.PkgPath != "" && !f.Anonymous

For example, see the changes to the implementations of
encoding/json and
encoding/xml.

Sorting

In the
sort
package,
the implementation of
Sort
has been rewritten to make about 10% fewer calls to the
Interface's
Less and Swap
methods, with a corresponding overall time savings.
The new algorithm does choose a different ordering than before
for values that compare equal (those pairs for which Less(i, j) and Less(j, i) are false).

Updating:
The definition of Sort makes no guarantee about the final order of equal values,
but the new behavior may still break programs that expect a specific order.
Such programs should either refine their Less implementations
to report the desired order
or should switch to
Stable,
which preserves the original input order
of equal values.

Templates

In the
text/template package,
there are two significant new features to make writing templates easier.

First, it is now possible to trim spaces around template actions,
which can make template definitions more readable.
A minus sign at the beginning of an action says to trim space before the action,
and a minus sign at the end of an action says to trim space after the action.
For example, the template

{{"{{"}}23 -}}
   <
{{"{{"}}- 45}}

formats as 23<45.

Second, the new {{"{{"}}block}} action,
combined with allowing redefinition of named templates,
provides a simple way to define pieces of a template that
can be replaced in different instantiations.
For example, the template

<title>{{"{{"}}block "title"}}Page Title{{"{{"}}end}}</title>
<body>
<h1>{{"{{"}}template "title"}}</h1>
{{"{{"}}block "page"}}Main text{{"{{"}}end}}

defines the basic formatting of a web page. A program can then
overlay that template with new definitions for the "title"
and "page" blocks to reuse the formatting for another page.

Minor changes to the library

In the archive/zip package, the
Reader type now has a
RegisterDecompressor method,
and the
Writer type now has a
RegisterCompressor method,
enabling control over compression options for individual zip files.
These take precedence over the pre-existing global
RegisterDecompressor and
RegisterCompressor functions.

The bufio package's
Scanner type now has a
Buffer method,
to specify an initial buffer and maximum buffer size to use during scanning.
This makes it possible, when needed, to scan tokens larger than
MaxScanTokenSize.
Also for the Scanner, the package now defines the
ErrFinalToken error value, for use by
split functions to abort processing or to return a final empty token.

The compress/flate package
has deprecated its
ReadError and
WriteError error implementations.
In Go 1.5 they were only rarely returned when an error was encountered;
now they are never returned, although they remain defined for compatibility.

The compress/flate,
compress/gzip, and
compress/zlib packages
now report
io.ErrUnexpectedEOF for truncated input streams, instead of
io.EOF.

The crypto/tls package
has a variety of minor changes.
It now allows
Listen
to succeed when the
Config
has a nil Certificates, as long as the GetCertificate callback is set,
it adds support for RSA with AES-GCM cipher suites,
and
it adds a
RecordHeaderError
to allow clients (in particular, the net/http package)
to report a better error when attempting a TLS connection to a non-TLS server.

The crypto/x509 package
now permits certificates to contain negative serial numbers
(technically an error, but unfortunately common in practice),
and it defines a new
InsecureAlgorithmError
to give a better error message when rejecting a certificate
signed with an insecure algorithm like MD5.

The debug/dwarf and
debug/elf packages
together add support for compressed DWARF sections.
User code needs no updating: the sections are decompressed automatically when read.

The debug/elf package
adds support for general compressed ELF sections.
User code needs no updating: the sections are decompressed automatically when read.
However, compressed
Section's do not support random access:
they have a nil ReaderAt field.

The encoding/asn1 package
now exports
tag and class constants
useful for advanced parsing of ASN.1 structures.

Also in the encoding/asn1 package,
Unmarshal now rejects various non-standard integer and length encodings.

The encoding/json package
now checks the syntax of a
Number
before marshaling it, requiring that it conforms to the JSON specification for numeric values.
As in previous releases, the zero Number (an empty string) is marshaled as a literal 0 (zero).

The encoding/xml package's
Marshal
function now supports a cdata attribute, such as chardata
but encoding its argument in one or more <![CDATA[ ... ]]> tags.

Also in the encoding/xml package,
Decoder's
Token method
now reports an error when encountering EOF before seeing all open tags closed,
consistent with its general requirement that tags in the input be properly matched.
To avoid that requirement, use
RawToken.

The fmt package now allows
any integer type as an argument to
Printf's * width and precision specification.
In previous releases, the argument to * was required to have type int.

Also in the fmt package,
Scanf can now scan hexadecimal strings using %X, as an alias for %x.
Both formats accept any mix of upper- and lower-case hexadecimal.
TODO: Keep?

The image
and
The image/color packages
add
NYCbCrA
and
NYCbCrA
types, to support Y'CbCr images with non-premultiplied alpha.

The io package's
MultiWriter
implementation now implements a WriteString method,
for use by
WriteString.

In the math/big package,
Int adds
Append
and
Text
methods to give more control over printing.

Also in the math/big package,
Float now implements
encoding.TextMarshaler and
encoding.TextUnmarshaler,
allowing it to be serialized in a natural form by the
encoding/json and
encoding/xml packages.

Also in the math/big package,
Float's
Append method now supports the special precision argument -1.
As in
strconv.ParseFloat,
precision -1 means to use the smallest number of digits necessary such that
Parse
reading the result into a Float of the same precision
will yield the original value.

The math/rand package
adds a
Read
function, and likewise
Rand adds a
Read method.
These make it easier to generate pseudorandom test data.
Note that, like the rest of the package,
these should not be used in cryptographic settings;
for such purposes, use the crypto/rand package instead.

The net package's
ParseMAC function now accepts 20-byte IP-over-InfiniBand (IPoIB) link-layer addresses.

Also in the net package,
there have been a few changes to DNS lookups.
First, the
DNSError error implementation now implements
Error,
and in particular its new
IsTemporary
method returns true for DNS server errors.
Second, DNS lookup functions such as
LookupAddr
now return rooted domain names (with a trailing dot)
on Plan 9 and Windows, to match the behavior of Go on Unix systems.
TODO: Third, lookups satisfied from /etc/hosts now add a trailing dot as well,
so that looking up 127.0.0.1 typically now returns “localhost.” not “localhost”.
This is arguably a mistake but is not yet fixed. See https://golang.org/issue/13564.

The net/http package has
a number of minor additions beyond the HTTP/2 support already discussed.
First, the
FileServer now sorts its generated directory listings by file name.
Second, the
Client now allows user code to set the
Expect: 100-continue header.
Third, there are
four new error codes from RFC 6585:
StatusPreconditionRequired (428),
StatusTooManyRequests (429),
StatusRequestHeaderFieldsTooLarge (431),
and
StatusNetworkAuthenticationRequired (511).

Also in the net/http package,
there are a few changes related to the handling of a
Request data structure with its Method field set to the empty string.
An empty Method field has always been documented as an alias for "GET"
and it remains so.
However, Go 1.6 fixes a few routines that did not treat an empty
Method the same as an explicit "GET".
Most notably, in previous releases
Client followed redirects only with
Method set explicitly to "GET";
in Go 1.6 Client also follows redirects for the empty Method.
Finally,
NewRequest accepts a method argument that has not been
documented as allowed to be empty.
In past releases, passing an empty method argument resulted
in a Request with an empty Method field.
In Go 1.6, the resulting Request always has an initialized
Method field: if its argument is an empty string, NewRequest
sets the Method field in the returned Request to "GET".

The net/http/httptest package's
ResponseRecorder now initializes a default Content-Type header
using the same content-sniffing algorithm as in
http.Server.

The net/url package's
Parse is now stricter and more spec-compliant regarding the parsing
of host names.
For example, spaces in the host name are no longer accepted.

Also in the net/url package,
the Error type now implements
net.Error.

The os package's
IsExist,
IsNotExist,
and
IsPermission
now return correct results when inquiring about an
SyscallError.

In the os/exec package,
Cmd's
Output method continues to return an
ExitError when a command exits with an unsuccessful status.
If standard error would otherwise have been discarded,
the returned ExitError now holds a prefix
(currently 32 kB) of the failed command's standard error output,
for debugging or for inclusion in error messages.
The ExitError's
String
method does not show the captured standard error;
programs must retrieve it from the data structure
separately.

On Windows, the path/filepath package's
Join function now correctly handles the case when the base is a relative drive path.
For example, Join(`c:`, `a`) now
returns `c:a` instead of `c:\a` as in past releases.
This may affect code that expects the incorrect result.

In the regexp package,
the
Regexp type has always been safe for use by
concurrent goroutines.
It uses a sync.Mutex to protect
a cache of scratch spaces used during regular expression searches.
Some high-concurrency servers using the same Regexp from many goroutines
have seen degraded performance due to contention on that mutex.
To help such servers, Regexp now has a
Copy method,
which makes a copy of a Regexp that shares most of the structure
of the original but has its own scratch space cache.
Two goroutines can use different copies of a Regexp
without mutex contention.
A copy does have additional space overhead, so Copy
should only be used when contention has been observed.

The strconv package adds
IsGraphic,
QuoteToGraphic,
QuoteRuneToGraphic,
AppendQuoteToGraphic,
and
AppendQuoteRuneToGraphic,
analogous to
IsPrint,
QuoteToPrint,
and so on.
The Print family escapes all space characters except ASCII space (U+0020).
In contrast, the Graphic family does not escape any Unicode space characters (category Zs).

In the testing package,
when a test calls
t.Parallel,
that test is paused until all non-parallel tests complete, and then
that test continues execution with all other parallel tests.
Go 1.6 changes the time reported for such a test:
previously the time counted only the parallel execution,
but now it also counts the time from the start of testing
until the call to t.Parallel.

The text/template package
contains two minor changes, in addition to the major changes
described above.
First, it adds a new
ExecError type
returned for any error during
Execute
that does not originate in a Write to the underlying writer.
Callers can distinguish template usage errors from I/O errors by checking for
ExecError.
Second, the
Funcs method
now checks that the names used as keys in the
FuncMap
are identifiers that can appear in a template function invocation.
If not, Funcs panics.

The time package's
Parse function has always rejected any day of month larger than 31,
such as January 32.
In Go 1.6, Parse now also rejects February 29 in non-leap years,
February 30, February 31, April 31, June 31, September 31, and November 31.


text:
package com.bwssystems.HABridge.plugins.mqtt;

import org.apache.commons.lang3.StringEscapeUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bwssystems.HABridge.NamedIP;

public class MQTTHandler {
    private static final Logger log = LoggerFactory.getLogger(MQTTHandler.class);
	private NamedIP myConfig;
	private MqttClient myClient;
    private int qos             = 1;

	public MQTTHandler(NamedIP aConfig) {
		super();
		log.info("Setting up handler for name: " + aConfig.getName());
        MemoryPersistence persistence = new MemoryPersistence();
		myConfig = aConfig;
        try {
			myClient = new MqttClient("tcp://" + myConfig.getIp(), myConfig.getName(), persistence);
		} catch (MqttException e) {
			log.error("Could not create MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage());
		}
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setAutomaticReconnect(true);
        if(aConfig.getUsername() != null && aConfig.getUsername().trim().length() > 0) {
        	if(aConfig.getPassword() != null && aConfig.getPassword().trim().length() > 0) {
        		connOpts.setUserName(aConfig.getUsername().trim());
        		connOpts.setPassword(aConfig.getPassword().trim().toCharArray());
        	}
        }
        try {
			myClient.connect(connOpts);
		} catch (MqttSecurityException e) {
			log.error("Could not connect MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage());
		} catch (MqttException e) {
			log.error("Could not connect MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage());
		}
	}

	public void publishMessage(String topic, String content) {
        MqttMessage message = new MqttMessage(StringEscapeUtils.unescapeJava(content).getBytes());
        message.setQos(qos);
        try {
			myClient.publish(topic, message);
		} catch (MqttPersistenceException e) {
			log.error("Could not publish to MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage());
		} catch (MqttException e) {
			log.error("Could not publish to MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage());
		}
	}

	public NamedIP getMyConfig() {
		return myConfig;
	}

	public void shutdown() {
		try {
			myClient.disconnect();
		} catch (MqttException e) {
			log.warn("Could not disconnect MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp());
		}
		myClient = null;
	}
}