text:
        <?php $images = get_sub_field('galleria_immagini_slideshow'); ?>
        <?php if ($images): ?>
            <?php $n_page = 0;
            foreach ($images as $image): ?>
                <li class="slider-item" ng-class="{current:pos==<?php echo $n_page ?>}">

<?php echo wp_get_attachment_image($image["id"], "large"); ?>

                <?php $n_page++; endforeach; ?>

        <?php endif ?>


text:
gamepadclj
==========

Game pad interaction in Clojure

jinput is a java library that provides access to game controllers.

Controllers are composed from components.

Components can report their state as either distinct values or as values in a range.
Components that report their state in a range are called analog.
Some analog components are not stable in the value they report, even if the user
has not interacted with them. So for example an analog stick may report a series
of values 0.01, -0.0999, 0.0012, 0.0005 when at "rest".

Sometimes interaction with one component, such as pushing a button, can create vibrations
in the controller that register with the analog components.

    describe-controller

returns a snapshot of the state of all the components of a controller.

This may be all you need.

If you want to compare this snapshot with a previous one, there is a function clojure.data/diff
that will be useful.

gamepadclj is part of a re-write of [jinput-overtone][3] following the advice in Stuart Halloway's talk
[Radical Simplicity][1]. Also inspired by Jan Monschke's talk on [Making Music with Javascript and Gamepads][2].

[1]: http://skillsmatter.com/podcast/java-jee/radical-simplicity "Radical Simplicity"
[2]: http://www.youtube.com/watch?v=0MigafMWLh0 "Making Music with Javascript and Gamepads"
[3]: https://github.com/gavilancomun/jinput-overtone

redpajama_set_name: RedPajamaGithub


text:
var models = require('../models/models.js');

exports.calculate = function(req,res,next){
	var with_comments=[];
	var no_comments;
	models.Quiz.count().then(function(quizes){
		models.Comment.findAll({where: {publicado: true}}).then(function(comments){
			no_comments=quizes;
			for (var i=0; i<comments.length; i++){
				if(with_comments[comments[i].QuizId]===undefined){
					no_comments--;
				}
				with_comments[comments[i].QuizId]=1;
			}
			res.render('statistics',
			{quizes: quizes,
				comments: comments.length,
				avg: comments.length/quizes,
				no_comments: no_comments,
				with_comments: quizes-no_comments,
				errors: []
			});
		});
	});
}


text:
    <button type="button" class="btn btn-primary">Left</button>
    <button type="button" class="btn btn-success">Middle</button>
    <button type="button" class="btn btn-default">Right</button>


text:
ReactiveTemplates.onCreated('collections.comments.index', function() {

  var sub = this.subscribe('posts', {sort: {submitted: -1, _id: -1}, limit: 0});

  if( sub.ready() ){
  	debugger
  	console.log('subscription ready!');
  };

});


text:
package com.livescribe.base.dao;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Deprecated
public @interface Mappable {

}


text:
require('dotenv-safe').load();

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

var routes = require('./routes/index');
var users = require('./routes/users');

var passport = require('passport');
var TwitterStrategy = require('passport-twitter').Strategy;

var USERS = {};

passport.use(new TwitterStrategy({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callbackURL: '/auth/twitter/callback'
}, function(token, tokenSecret, profile, done) {
  USERS[profile.id] = {
    token: token,
    tokenSecret: tokenSecret,
    profile: profile
  };
  done(null, USERS[profile.id]);
}));

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
  secret: process.env.SESSION_SECRET
}));

app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', {
  failureRedirect: 'http://localhost:4200'
}), function (req, res) {
  var user = {
    id: req.user.profile.id,
    username: req.user.profile.username,
    displayName: req.user.profile.displayName,
    profileImage: req.user.profile._json.profile_image_url_https
  };
  res.redirect('http://localhost:4200?code=' + encodeURIComponent(JSON.stringify(user)));
});

app.get('/me', function (req, res) {
  if (req.user) {
    var user = {
      id: req.user.profile.id,
      username: req.user.profile.username,
      displayName: req.user.profile.displayName,
      profileImage: req.user.profile._json.profile_image_url_https
    };
    res.jsonp(user);
  } else {
    res.send(401);
  }
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;


text:
package com.helger.ubl21.codelist;

import com.helger.commons.annotation.CodingStyleguideUnaware;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.id.IHasID;
import com.helger.commons.lang.EnumHelper;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * This file was automatically generated from Genericode file ExceptionStatusCode-2.1.gc. Do NOT edit!
 * It contains a total of 5 entries!
 * @author com.helger.ubl21.main.MainCreateEnumsGenericode21
 */
@CodingStyleguideUnaware
public enum EExceptionStatusCode21
    implements IHasID<String>
{
    ACKNOWLEDGED("ACKNOWLEDGED"),
    NEW("NEW"),
    RESOLVED("RESOLVED"),
    SUPERSEDED("SUPERSEDED"),
    UNRESOLVABLE("UNRESOLVABLE");
    public static final String AGENCY_ID = "UBL";
    public static final String AGENCY_LONG_NAME = "OASIS Universal Business Language";
    public static final String LIST_VERSION = "2.1";
    private final String m_sID;

    private EExceptionStatusCode21(@Nonnull @Nonempty final String sID) {
        m_sID = sID;
    }

    @Nonnull
    @Nonempty
    public String getID() {
        return m_sID;
    }

    @Nullable
    public static EExceptionStatusCode21 getFromIDOrNull(@Nullable final String sID) {
        return EnumHelper.getFromIDOrNull(EExceptionStatusCode21 .class, sID);
    }
}


text:
namespace lua
{
    /// Lua table type
    struct Table {};

    /// Any Lua function, C function, or table/userdata with __call metamethod
    struct Callable {};

    using Number = lua_Number;

    using Integer = lua_Integer;

    using Unsigned = std::make_unsigned<lua_Integer>::type;

    using Boolean = bool;

    using String = const char*;

    using Nil = std::nullptr_t;

    using Pointer = void*;
}


text:
package com.koch.ambeth.merge.config;

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import com.koch.ambeth.ioc.annotation.Autowired;
import com.koch.ambeth.ioc.typeinfo.MethodPropertyInfo;
import com.koch.ambeth.ioc.typeinfo.TypeInfoItemUtil;
import com.koch.ambeth.log.ILogger;
import com.koch.ambeth.log.LogInstance;
import com.koch.ambeth.merge.compositeid.CompositeIdMember;
import com.koch.ambeth.merge.compositeid.ICompositeIdFactory;
import com.koch.ambeth.merge.metadata.IIntermediateMemberTypeProvider;
import com.koch.ambeth.merge.model.EntityMetaData;
import com.koch.ambeth.merge.orm.CompositeMemberConfig;
import com.koch.ambeth.merge.orm.IEntityConfig;
import com.koch.ambeth.merge.orm.IMemberConfig;
import com.koch.ambeth.merge.orm.IOrmConfig;
import com.koch.ambeth.merge.orm.IRelationConfig;
import com.koch.ambeth.merge.orm.MemberConfig;
import com.koch.ambeth.service.merge.model.IEntityMetaData;
import com.koch.ambeth.service.metadata.EmbeddedMember;
import com.koch.ambeth.service.metadata.IEmbeddedMember;
import com.koch.ambeth.service.metadata.IPrimitiveMemberWrite;
import com.koch.ambeth.service.metadata.Member;
import com.koch.ambeth.service.metadata.PrimitiveMember;
import com.koch.ambeth.service.metadata.RelationMember;
import com.koch.ambeth.util.collections.ArrayList;
import com.koch.ambeth.util.collections.HashMap;
import com.koch.ambeth.util.collections.HashSet;
import com.koch.ambeth.util.collections.IList;
import com.koch.ambeth.util.collections.IMap;
import com.koch.ambeth.util.collections.ISet;
import com.koch.ambeth.util.collections.IdentityHashSet;
import com.koch.ambeth.util.collections.IdentityLinkedSet;
import com.koch.ambeth.util.collections.LinkedHashMap;
import com.koch.ambeth.util.collections.LinkedHashSet;
import com.koch.ambeth.util.typeinfo.IPropertyInfo;
import com.koch.ambeth.util.typeinfo.IPropertyInfoProvider;
import com.koch.ambeth.util.typeinfo.IRelationProvider;

public class EntityMetaDataReader implements IEntityMetaDataReader {
	@LogInstance
	private ILogger log;

	private static final Pattern containsDot = Pattern.compile("\\.");

	@Autowired
	protected ICompositeIdFactory compositeIdFactory;

	@Autowired
	protected IIntermediateMemberTypeProvider intermediateMemberTypeProvider;

	@Autowired
	protected IPropertyInfoProvider propertyInfoProvider;

	@Autowired
	protected IRelationProvider relationProvider;

	@Override
	public void addMembers(EntityMetaData metaData, IEntityConfig entityConfig) {
		Class<?> realType = entityConfig.getRealType();

		HashSet<String> memberNamesToIgnore = new HashSet<>();
		HashSet<String> explicitBasicMemberNames = new HashSet<>();
		ArrayList<IMemberConfig> embeddedMembers = new ArrayList<>();
		HashMap<String, IMemberConfig> nameToMemberConfig = new HashMap<>();
		HashMap<String, IRelationConfig> nameToRelationConfig = new HashMap<>();
		LinkedHashMap<String, Member> nameToMemberMap = new LinkedHashMap<>();

		fillNameCollections(entityConfig, memberNamesToIgnore, explicitBasicMemberNames,
				embeddedMembers, nameToMemberConfig, nameToRelationConfig);

		LinkedHashSet<PrimitiveMember> alternateIdMembers = new LinkedHashSet<>();
		LinkedHashSet<PrimitiveMember> primitiveMembers = new LinkedHashSet<>();
		LinkedHashSet<RelationMember> relationMembers = new LinkedHashSet<>();
		LinkedHashSet<Member> notMergeRelevant = new IdentityLinkedSet<>();

		LinkedHashSet<Member> containedInAlternateIdMember = new IdentityLinkedSet<>();

		IPropertyInfo[] properties = propertyInfoProvider.getProperties(realType);

		LinkedHashMap<String, Member> explicitlyConfiguredMemberNameToMember =
				new LinkedHashMap<>();

		HashMap<String, IOrmConfig> nameToConfigMap = new HashMap<>();
		// Resolve members for all explicit configurations - both simple and composite ones, each with
		// embedded
		// functionality (dot-member-path)
		for (IMemberConfig memberConfig : entityConfig.getMemberConfigIterable()) {
			putNameToConfigMap(memberConfig, nameToConfigMap);
			if (memberConfig.isIgnore()) {
				continue;
			}
			handleMemberConfig(metaData, realType, memberConfig, explicitlyConfiguredMemberNameToMember,
					nameToMemberMap);
		}
		for (IRelationConfig relationConfig : entityConfig.getRelationConfigIterable()) {
			putNameToConfigMap(relationConfig, nameToConfigMap);
			handleRelationConfig(realType, relationConfig, explicitlyConfiguredMemberNameToMember);
		}
		putNameToConfigMap(entityConfig.getIdMemberConfig(), nameToConfigMap);
		putNameToConfigMap(entityConfig.getVersionMemberConfig(), nameToConfigMap);
		putNameToConfigMap(entityConfig.getCreatedByMemberConfig(), nameToConfigMap);
		putNameToConfigMap(entityConfig.getCreatedOnMemberConfig(), nameToConfigMap);
		putNameToConfigMap(entityConfig.getUpdatedByMemberConfig(), nameToConfigMap);
		putNameToConfigMap(entityConfig.getUpdatedOnMemberConfig(), nameToConfigMap);

		metaData.setIdMember(handleMemberConfig(metaData, realType, entityConfig.getIdMemberConfig(),
				explicitlyConfiguredMemberNameToMember, nameToMemberMap));
		metaData.setVersionMember(
				handleMemberConfig(metaData, realType, entityConfig.getVersionMemberConfig(),
						explicitlyConfiguredMemberNameToMember, nameToMemberMap));
		metaData.setCreatedByMember(
				handleMemberConfig(metaData, realType, entityConfig.getCreatedByMemberConfig(),
						explicitlyConfiguredMemberNameToMember, nameToMemberMap));
		metaData.setCreatedOnMember(
				handleMemberConfig(metaData, realType, entityConfig.getCreatedOnMemberConfig(),
						explicitlyConfiguredMemberNameToMember, nameToMemberMap));
		metaData.setUpdatedByMember(
				handleMemberConfig(metaData, realType, entityConfig.getUpdatedByMemberConfig(),
						explicitlyConfiguredMemberNameToMember, nameToMemberMap));
		metaData.setUpdatedOnMember(
				handleMemberConfig(metaData, realType, entityConfig.getUpdatedOnMemberConfig(),
						explicitlyConfiguredMemberNameToMember, nameToMemberMap));

		IdentityHashSet<Member> idMembers = new IdentityHashSet<>();
		Member idMember = metaData.getIdMember();
		if (idMember instanceof CompositeIdMember) {
			idMembers.addAll(((CompositeIdMember) idMember).getMembers());
		}
		else if (idMember != null) {
			idMembers.add(idMember);
		}

		// Handle all explicitly configured members
		for (Entry<String, Member> entry : explicitlyConfiguredMemberNameToMember) {
			String memberName = entry.getKey();
			IOrmConfig ormConfig = nameToConfigMap.get(memberName);

			Member member = entry.getValue();

			if (idMembers.contains(member)) {
				continue;
			}
			if (ormConfig.isExplicitlyNotMergeRelevant()) {
				notMergeRelevant.add(member);
			}
			if (ormConfig instanceof IRelationConfig) {
				if (!relationMembers.add((RelationMember) member)) {
					throw new IllegalStateException(
							"Member has been registered as relation multiple times: " + member.getName());
				}
				continue;
			}
			if (!(ormConfig instanceof IMemberConfig)) {
				continue;
			}
			if (((IMemberConfig) ormConfig).isAlternateId()) {
				if (!alternateIdMembers.add((PrimitiveMember) member)) {
					throw new IllegalStateException(
							"Member has been registered as alternate id multiple times: " + member.getName());
				}
				if (member instanceof CompositeIdMember) {
					Member[] containedMembers = ((CompositeIdMember) member).getMembers();
					containedInAlternateIdMember.addAll(containedMembers);
				}
			}
			if (!(member instanceof CompositeIdMember) && metaData.getVersionMember() != member) {
				// Alternate Ids are normally primitives, too. But Composite Alternate Ids not - only their
				// composite
				// items are primitives
				primitiveMembers.add((PrimitiveMember) member);
			}
		}
		IdentityHashSet<String> explicitTypeInfoItems =
				IdentityHashSet.<String>create(explicitlyConfiguredMemberNameToMember.size());
		for (Entry<String, Member> entry : explicitlyConfiguredMemberNameToMember) {
			Member member = entry.getValue();
			explicitTypeInfoItems.add(member.getName());
			if (member instanceof IEmbeddedMember) {
				explicitTypeInfoItems.add(((IEmbeddedMember) member).getMemberPath()[0].getName());
			}
		}
		// Go through the available members to look for potential auto-mapping (simple, no embedded)
		for (int i = 0; i < properties.length; i++) {
			IPropertyInfo property = properties[i];
			String memberName = property.getName();
			if (memberNamesToIgnore.contains(memberName)) {
				continue;
			}
			if (explicitTypeInfoItems.contains(memberName)) {
				// already configured, no auto mapping needed for this member
				continue;
			}

			MethodPropertyInfo mProperty = (MethodPropertyInfo) property;
			Class<?> elementType = TypeInfoItemUtil.getElementTypeUsingReflection(
					mProperty.getGetter().getReturnType(), mProperty.getGetter().getGenericReturnType());
			if (nameToMemberMap.get(property.getName()) instanceof RelationMember
					|| relationProvider.isEntityType(elementType)) {
				RelationMember member =
						getRelationMember(metaData.getEntityType(), property, nameToMemberMap);
				relationMembers.add(member);
				continue;
			}
			PrimitiveMember member =
					getPrimitiveMember(metaData.getEntityType(), property, nameToMemberMap);
			if (metaData.getIdMember() == null && memberName.equals(EntityMetaData.DEFAULT_NAME_ID)) {
				metaData.setIdMember(member);
				continue;
			}
			if (idMembers.contains(member) && !alternateIdMembers.contains(member)
					&& !containedInAlternateIdMember.contains(member)) {
				continue;
			}
			if (member.equals(metaData.getIdMember()) || member.equals(metaData.getVersionMember())
					|| member.equals(metaData.getCreatedByMember())
					|| member.equals(metaData.getCreatedOnMember())
					|| member.equals(metaData.getUpdatedByMember())
					|| member.equals(metaData.getUpdatedOnMember())) {
				continue;
			}
			if (metaData.getVersionMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_VERSION)) {
				metaData.setVersionMember(member);
				continue;
			}
			if (metaData.getCreatedByMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_CREATED_BY)) {
				metaData.setCreatedByMember(member);
			}
			else if (metaData.getCreatedOnMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_CREATED_ON)) {
				metaData.setCreatedOnMember(member);
			}
			else if (metaData.getUpdatedByMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_UPDATED_BY)) {
				metaData.setUpdatedByMember(member);
			}
			else if (metaData.getUpdatedOnMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_UPDATED_ON)) {
				metaData.setUpdatedOnMember(member);
			}
			primitiveMembers.add(member);
		}
		for (PrimitiveMember member : primitiveMembers) {
			String memberName = member.getName();
			if (explicitBasicMemberNames.contains(memberName)) {
				// Even if the name would match, this member was explicitly configured as "basic"
				continue;
			}
			if (metaData.getCreatedByMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_CREATED_BY)) {
				metaData.setCreatedByMember(member);
			}
			else if (metaData.getCreatedOnMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_CREATED_ON)) {
				metaData.setCreatedOnMember(member);
			}
			else if (metaData.getUpdatedByMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_UPDATED_BY)) {
				metaData.setUpdatedByMember(member);
			}
			else if (metaData.getUpdatedOnMember() == null
					&& memberName.equals(EntityMetaData.DEFAULT_NAME_UPDATED_ON)) {
				metaData.setUpdatedOnMember(member);
			}
		}
		filterWrongRelationMappings(relationMembers);
		// Order of setter calls is important
		PrimitiveMember[] primitives = primitiveMembers.toArray(PrimitiveMember.class);
		PrimitiveMember[] alternateIds = alternateIdMembers.toArray(PrimitiveMember.class);
		RelationMember[] relations = relationMembers.toArray(RelationMember.class);
		Arrays.sort(primitives);
		Arrays.sort(alternateIds);
		Arrays.sort(relations);
		metaData.setPrimitiveMembers(primitives);
		metaData.setAlternateIdMembers(alternateIds);
		metaData.setRelationMembers(relations);

		for (Member member : notMergeRelevant) {
			metaData.setMergeRelevant(member, false);
		}
		if (metaData.getIdMember() == null) {
			throw new IllegalStateException(
					"No ID member could be resolved for entity of type " + metaData.getRealType());
		}
	}

	protected void putNameToConfigMap(IOrmConfig config, Map<String, IOrmConfig> nameToConfigMap) {
		if (config == null) {
			return;
		}
		nameToConfigMap.put(config.getName(), config);
		if (config instanceof CompositeMemberConfig) {
			for (MemberConfig member : ((CompositeMemberConfig) config).getMembers()) {
				putNameToConfigMap(member, nameToConfigMap);
			}
		}
	}

	protected void filterWrongRelationMappings(ISet<RelationMember> relationMembers) {
		// filter all relations which can not be a relation because of explicit embedded property
		// mapping
		IdentityHashSet<RelationMember> toRemove = new IdentityHashSet<>();
		for (RelationMember relationMember : relationMembers) {
			String[] memberPath = EmbeddedMember.split(relationMember.getName());
			for (RelationMember otherRelationMember : relationMembers) {
				if (relationMember == otherRelationMember || toRemove.contains(otherRelationMember)) {
					continue;
				}
				if (!(otherRelationMember instanceof IEmbeddedMember)) {
					// only embedded members can help identifying other wrong relation members
					continue;
				}
				String[] otherMemberPath = ((IEmbeddedMember) otherRelationMember).getMemberPathToken();
				if (memberPath.length > otherMemberPath.length) {
					continue;
				}
				boolean match = true;
				for (int a = 0, size = memberPath.length; a < size; a++) {
					if (!memberPath[a].equals(otherMemberPath[a])) {
						match = false;
						break;
					}
				}
				if (match) {
					toRemove.add(relationMember);
					break;
				}
			}
		}
		relationMembers.removeAll(toRemove);
	}

	protected PrimitiveMember getPrimitiveMember(Class<?> entityType, IPropertyInfo property,
			Map<String, Member> nameToMemberMap) {
		PrimitiveMember member = (PrimitiveMember) nameToMemberMap.get(property.getName());
		if (member != null) {
			return member;
		}
		member = intermediateMemberTypeProvider.getIntermediatePrimitiveMember(entityType,
				property.getName());
		nameToMemberMap.put(property.getName(), member);
		return member;
	}

	protected RelationMember getRelationMember(Class<?> entityType, IPropertyInfo property,
			Map<String, Member> nameToMemberMap) {
		RelationMember member = (RelationMember) nameToMemberMap.get(property.getName());
		if (member != null) {
			return member;
		}
		member = intermediateMemberTypeProvider.getIntermediateRelationMember(entityType,
				property.getName());
		nameToMemberMap.put(property.getName(), member);
		return member;
	}

	protected PrimitiveMember handleMemberConfigIfNew(Class<?> entityType, String memberName,
			Map<String, Member> memberConfigToInfoItem) {
		PrimitiveMember member = (PrimitiveMember) memberConfigToInfoItem.get(memberName);
		if (member != null) {
			return member;
		}
		member = intermediateMemberTypeProvider.getIntermediatePrimitiveMember(entityType, memberName);
		if (member == null) {
			throw new RuntimeException("No member with name '" + memberName + "' found on entity type '"
					+ entityType.getName() + "'");
		}
		memberConfigToInfoItem.put(memberName, member);
		return member;
	}

	protected PrimitiveMember handleMemberConfig(IEntityMetaData metaData, Class<?> realType,
			IMemberConfig memberConfig, Map<String, Member> explicitMemberNameToMember,
			Map<String, Member> allMemberNameToMember) {
		if (memberConfig == null) {
			return null;
		}
		if (!(memberConfig instanceof CompositeMemberConfig)) {
			PrimitiveMember member =
					handleMemberConfigIfNew(realType, memberConfig.getName(), allMemberNameToMember);
			explicitMemberNameToMember.put(memberConfig.getName(), member);
			((IPrimitiveMemberWrite) member).setTransient(memberConfig.isTransient());

			PrimitiveMember definedBy = memberConfig.getDefinedBy() != null
					? handleMemberConfigIfNew(realType, memberConfig.getDefinedBy(), allMemberNameToMember)
					: null;
			((IPrimitiveMemberWrite) member).setDefinedBy(definedBy);
			return member;
		}
		MemberConfig[] memberConfigs = ((CompositeMemberConfig) memberConfig).getMembers();
		PrimitiveMember[] members = new PrimitiveMember[memberConfigs.length];
		for (int a = memberConfigs.length; a-- > 0;) {
			MemberConfig memberPart = memberConfigs[a];
			PrimitiveMember member =
					handleMemberConfigIfNew(realType, memberPart.getName(), explicitMemberNameToMember);
			members[a] = member;
		}
		PrimitiveMember compositeIdMember =
				compositeIdFactory.createCompositeIdMember(metaData, members);
		explicitMemberNameToMember.put(memberConfig.getName(), compositeIdMember);
		allMemberNameToMember.put(memberConfig.getName(), compositeIdMember);
		((IPrimitiveMemberWrite) compositeIdMember).setTransient(memberConfig.isTransient());

		PrimitiveMember definedBy = memberConfig.getDefinedBy() != null
				? handleMemberConfigIfNew(realType, memberConfig.getDefinedBy(), allMemberNameToMember)
				: null;
		((IPrimitiveMemberWrite) compositeIdMember).setDefinedBy(definedBy);
		return compositeIdMember;
	}

	protected Member handleRelationConfig(Class<?> realType, IRelationConfig relationConfig,
			Map<String, Member> relationConfigToInfoItem) {
		if (relationConfig == null) {
			return null;
		}
		Member member = relationConfigToInfoItem.get(relationConfig.getName());
		if (member != null) {
			return member;
		}
		member = intermediateMemberTypeProvider.getIntermediateRelationMember(realType,
				relationConfig.getName());
		if (member == null) {
			throw new RuntimeException("No member with name '" + relationConfig.getName()
					+ "' found on entity type '" + realType.getName() + "'");
		}
		relationConfigToInfoItem.put(relationConfig.getName(), member);
		return member;
	}

	protected void fillNameCollections(IEntityConfig entityConfig, ISet<String> memberNamesToIgnore,
			HashSet<String> explicitBasicMemberNames, IList<IMemberConfig> embeddedMembers,
			IMap<String, IMemberConfig> nameToMemberConfig,
			IMap<String, IRelationConfig> nameToRelationConfig) {
		for (IMemberConfig memberConfig : entityConfig.getMemberConfigIterable()) {
			if (!(memberConfig instanceof MemberConfig)
					&& !(memberConfig instanceof CompositeMemberConfig)) {
				throw new IllegalStateException("Member configurations of type '"
						+ memberConfig.getClass().getName() + "' not yet supported");
			}

			String memberName = memberConfig.getName();

			if (memberConfig.isIgnore()) {
				memberNamesToIgnore.add(memberName);
				memberNamesToIgnore.add(memberName + "Specified");
				continue;
			}

			explicitBasicMemberNames.add(memberName);

			String[] parts = containsDot.split(memberName, 2);
			boolean isEmbeddedMember = parts.length > 1;

			if (isEmbeddedMember) {
				embeddedMembers.add(memberConfig);
				memberNamesToIgnore.add(parts[0]);
				memberNamesToIgnore.add(parts[0] + "Specified");
				continue;
			}
			nameToMemberConfig.put(memberName, memberConfig);
		}

		for (IRelationConfig relationConfig : entityConfig.getRelationConfigIterable()) {
			String relationName = relationConfig.getName();

			nameToRelationConfig.put(relationName, relationConfig);
		}
	}
}


text:
/**
 * @generated SignedSource<<3a0f8219b63d5df921c6ad4d6dc670e9>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { ConcreteRequest, Query } from 'relay-runtime';
export type buildClientAppTestQuery$variables = {};
export type buildClientAppTestQuery$data = {
  readonly me: {
    readonly id: string;
  } | null;
};
export type buildClientAppTestQuery = {
  response: buildClientAppTestQuery$data;
  variables: buildClientAppTestQuery$variables;
};

const node: ConcreteRequest = (function(){
var v0 = [
  {
    "alias": null,
    "args": null,
    "concreteType": "Me",
    "kind": "LinkedField",
    "name": "me",
    "plural": false,
    "selections": [
      {
        "alias": null,
        "args": null,
        "kind": "ScalarField",
        "name": "id",
        "storageKey": null
      }
    ],
    "storageKey": null
  }
];
return {
  "fragment": {
    "argumentDefinitions": [],
    "kind": "Fragment",
    "metadata": null,
    "name": "buildClientAppTestQuery",
    "selections": (v0/*: any*/),
    "type": "Query",
    "abstractKey": null
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": [],
    "kind": "Operation",
    "name": "buildClientAppTestQuery",
    "selections": (v0/*: any*/)
  },
  "params": {
    "cacheID": "b21d943fb883a7693887b01b773ad5e9",
    "id": null,
    "metadata": {
      "relayTestingSelectionTypeInfo": {
        "me": {
          "enumValues": null,
          "nullable": true,
          "plural": false,
          "type": "Me"
        },
        "me.id": {
          "enumValues": null,
          "nullable": false,
          "plural": false,
          "type": "ID"
        }
      }
    },
    "name": "buildClientAppTestQuery",
    "operationKind": "query",
    "text": "query buildClientAppTestQuery {\n  me {\n    id\n  }\n}\n"
  }
};
})();

(node as any).hash = "3c905c887770618ef318f43d80e4b464";

export default node;


text:
package me.mattem.formation.calibration;

public interface FormationInterfaceCalibrationInterface {

}


text: <!DOCTYPE html>


text:
Title: Chocolatey VsCode Extension Release 0.4.1
Published: 27/11/2018
Tags:
- chocolatey
- vscode
- release
---

## Release Notes

### Bug

- [__#22__](https://github.com/gep13/chocolatey-vscode/issues/22) Fix dependency vulnerability alerts


text:
Bucky
-----

:info: Bucky Statsd and Collectd server for Graphite

.. image:: https://travis-ci.org/trbs/bucky.png?branch=master
   :target: https://travis-ci.org/trbs/bucky

.. image:: https://coveralls.io/repos/trbs/bucky/badge.png?branch=master
   :target: https://coveralls.io/r/trbs/bucky?branch=master

Bucky is a small server for collecting and translating metrics for
Graphite. It can current collect metric data from CollectD daemons
and from StatsD clients.

Bucky is a fork of the excellent, although seemingly abandoned, cloudant
project Bucky. (https://github.com/cloudant/bucky/)

Installation
------------

You can install with `easy_install` or `pip` as per normal modus
operandi::

    $ easy_install bucky
    # or
    $ pip install bucky

After installing, you can run Bucky like::

    $ bucky

By default, Bucky will open a CollectD UDP socket on 127.0.0.1:25826,
a StatsD socket on 127.0.0.1:8125 as well as attempt to connect to a
local Graphite (Carbon) daemon on 127.0.0.1:2003.

These are all optional as illustrated below. You can also disable the
CollectD or StatsD servers completely if you so desire.

Process Names
-------------

If the py-setproctitle_ module is installed Bucky will use it to set
user readable process names. This will make the child processes of Bucky
easier to identify. Please note that this is completely optional.

To install py-setproctitle_ run::

    $ easy_install setproctitle
    # or
    $ pip install setproctitle

.. _py-setproctitle: https://github.com/dvarrazzo/py-setproctitle

Running Bucky For Real
----------------------

The astute observer will notice that Bucky has no flags for
daemonization. This is quite on purpose. The recommended way to
run Bucky in production is via runit. There's an example service
directory in Bucky's source repository.

Python 3 Support
----------------

Bucky supports Python 3. However this support is still very young
and we would like to hear from you if you are running Bucky on
Python3 and help us improve the support in real production environments.

Command Line Options
--------------------

The command line options are limited to controlling the network
parameters. If you want to configure some of the more intricate
workings you'll need to use a config file. Here's the `bucky -h`
output::

    Usage: main.py [OPTIONS] [CONFIG_FILE]

    Options:
      --debug               Put server into debug mode. [False]
      --metricsd-ip=IP      IP address to bind for the MetricsD UDP socket
                            [127.0.0.1]
      --metricsd-port=INT   Port to bind for the MetricsD UDP socket [23632]
      --disable-metricsd    Disable the MetricsD UDP server
      --collectd-ip=IP      IP address to bind for the CollectD UDP socket
                            [127.0.0.1]
      --collectd-port=INT   Port to bind for the CollectD UDP socket [25826]
      --collectd-types=FILE
                            Path to the collectd types.db file, can be specified
                            multiple times
      --disable-collectd    Disable the CollectD UDP server
      --statsd-ip=IP        IP address to bind for the StatsD UDP socket
                            [127.0.0.1]
      --statsd-port=INT     Port to bind for the StatsD UDP socket [8125]
      --disable-statsd      Disable the StatsD server
      --graphite-ip=IP      IP address of the Graphite/Carbon server [127.0.0.1]
      --graphite-port=INT   Port of the Graphite/Carbon server [2003]
      --full-trace          Display full error if config file fails to load
      --log-level=NAME      Logging output verbosity [INFO]
      --version             show program's version number and exit
      -h, --help            show this help message and exit

Config File Options
-------------------

The configuration file is a normal Python file that defines a number of
variables. Most of command line options can also be specified in this
file (remove the "--" prefix and replace "-" with "_") but if specified
in both places, the command line takes priority. The defaults as a
config file::

    # Standard debug and log level
    debug = False
    log_level = "INFO"

    # Whether to print the entire stack trace for errors encountered
    # when loading the config file
    full_trace = False

    # Basic metricsd conifguration
    metricsd_ip = "127.0.0.1"
    metricsd_port = 23632
    metricsd_enabled = True

    # The default interval between flushes of metric data to Graphite
    metricsd_default_interval = 10.0

    # You can specify the frequency of flushes to Graphite based on
    # the metric name used for each metric. These are specified as
    # regular expressions. An entry in this list should be a 3-tuple
    # that is: (regexp, frequency, priority)
    #
    # The regexp is applied with the match method. Frequency should be
    # in seconds. Priority is used to break ties when a metric name
    # matches more than one handler. (The largest priority wins)
    metricsd_handlers = []

    # Basic collectd configuration
    collectd_ip = "127.0.0.1"
    collectd_port = 25826
    collectd_enabled = True

    # A list of file names for collectd types.db
    # files.
    collectd_types = []

    # A mapping of plugin names to converter callables. These are
    # explained in more detail in the README.
    collectd_converters = {}

    # Whether to load converters from entry points. The entry point
    # used to define converters is 'bucky.collectd.converters'.
    collectd_use_entry_points = True

    # Basic statsd configuration
    statsd_ip = "127.0.0.1"
    statsd_port = 8125
    statsd_enabled = True

    # How often stats should be flushed to Graphite.
    statsd_flush_time = 10.0

    # If the legacy namespace is enabled, the statsd backend uses the
    # default prefixes except for counters, which are stored directly
    # in stats.NAME for the rate and stats_counts.NAME for the
    # absolute count.  If legacy names are disabled, the prefixes are
    # configurable, and counters are stored under
    # stats.counters.{rate,count} by default.  Any prefix can be set
    # to None to skip it.
    statsd_legacy_namespace = True
    statsd_global_prefix = "stats"
    statsd_prefix_counter = "counters"
    statsd_prefix_timer = "timers"
    statsd_prefix_gauge = "gauges"

    # Basic Graphite configuration
    graphite_ip = "127.0.0.1"
    graphite_port = 2003

    # If the Graphite connection fails these numbers define how it
    # will reconnect. The max reconnects applies each time a
    # disconnect is encountered and the reconnect delay is the time
    # in seconds between connection attempts. Setting max reconnects
    # to a negative number removes the limit.
    graphite_max_reconnects = 3
    graphite_reconnect_delay = 5

    # Configuration for sending metrics to Graphite via the pickle
    # interface. Be sure to edit graphite_port to match the settings
    # on your Graphite cache/relay.
    graphite_pickle_enabled = False
    graphite_pickle_buffer_size = 500

    # Bucky provides these settings to allow the system wide
    # configuration of how metric names are processed before
    # sending to Graphite.
    #
    # Prefix and postfix allow to tag all values with some value.
    name_prefix = None
    name_postfix = None

    # The replacement character is used to munge any '.' characters
    # in name components because it is special to Graphite. Setting
    # this to None will prevent this step.
    name_replace_char = '_'

    # Optionally strip duplicates in path components. For instance
    # a.a.b.c.c.b would be rewritten as a.b.c.b
    name_strip_duplicates = True

    # Bucky reverses hostname components to improve the locality
    # of metric values in Graphite. For instance, "node.company.tld"
    # would be rewritten as "tld.company.node". This setting allows
    # for the specification of hostname components that should
    # be stripped from hostnames. For instance, if "company.tld"
    # were specified, the previous example would end up as "node".
    name_host_trim = []

Configuring CollectD
--------------------

You should only need to add something like this to your collectd.conf::

    LoadPlugin "network"

    <Plugin "network">
      Server "127.0.0.1" "25826"
    </Plugin>

Obviously, you'll want to match up the IP addresses and ports and make
sure that your firewall's are configured to allow UDP packets through.

Configuring StatsD
------------------

Just point your StatsD clients at Bucky's IP/Port and you should be
good to go.

Configuring MetricsD
--------------------

TODO

A note on CollectD converters
-----------------------------

CollectD metrics aren't exactly directly translatable to Graphite
metric names. The default translator attempts to make a best guess
but this can result in slightly less than pretty Graphite trees.

For this reason, Bucky has configurable converters. These are
keyed off the CollectD plugin name. The input to these functions is
a representation of the CollectD metric that looks like such::

    {
      'host': 'toroid.local',
      'interval': 10.0,
      'plugin': 'memory',
      'plugin_instance': '',
      'time': 1320970329.175534,
      'type': 'memory',
      'type_instance': 'inactive',
      'value': 823009280.0,
      'value_name': 'value',
      'value_type': 1
    }

The result of this function should be a list of strings that represent
part of the Graphite metric name or `None` to drop sample
entirely. For instance, if a converter returned `["foo", "bar"]`, the
final metric name will end up as:
`$prefix.$hostname.foo.bar.$postfix`.

An example builtin converter looks like such::

    # This might be how you define a converter in
    # your config file

    class MemoryConverter(object):
        PRIORITY = 0
        def __call__(self, sample):
            return ["memory", sample["type_instance"]]

    collectd_converters = {"memory": MemoryConverter()}

Converters can either be declared and/or imported in the optional
config file, or they can be autodiscovered via entry points. The
entry point that is searched is "bucky.collectd.converters". The
entry point name should be the CollectD plugin name.

`collectd_converters` in config file should be a mapping of collectd
plugin name to converter instance. The default catch-all converter
(used when no special converter is defined for a plugin) can be
overidden by specifying `_default` as the plugin name.

Converters also have a notion of priority in order to resolve
conflicts. This is merely a property on the callable named
"PRIORITY" and larger priorities are preferred. I don't imagine
this will need to be used very often, but its there just in
case.


text:
<?php
/*
 *
 */

namespace RDF\JobDefinitionFormatBundle\Model\JDF\Resource;

use Doctrine\OXM\Mapping as OXM;

/**
 * RDF\JobDefinitionFormatBundle\Model\JDF\Resource\ColorantAlias
 *
 * @OXM\XmlEntity(xml="ColorantAlias")
 */
class ColorantAlias extends Resource
{

}


text:
Rails.application.configure do
  config.cache_classes = true
  config.eager_load = false
  config.public_file_server.enabled = true

  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=3600',
  }

  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_dispatch.show_exceptions = false
  config.action_controller.allow_forgery_protection = false
  config.action_mailer.perform_caching = false
  config.action_mailer.delivery_method = :test
  config.active_support.deprecation = :stderr

  config.after_initialize do
    Bullet.enable = true
    Bullet.bullet_logger = true
  end
end


text:
extern "C" {
#endif

//------------------------------------------------------------------------------

const uint8_t* VP8DecompressAlphaRows(VP8Decoder* const dec,
                                      int row, int num_rows) {
  uint8_t* output = dec->alpha_plane_;
  const int stride = dec->pic_hdr_.width_;
  if (row < 0 || row + num_rows > dec->pic_hdr_.height_) {
    return NULL;    // sanity check
  }
  if (row == 0) {
    // TODO(skal): for now, we just decompress everything during the first call.
    // Later, we'll decode progressively, but we need to store the
    // z_stream state.
    const uint8_t* data = dec->alpha_data_;
    size_t data_size = dec->alpha_data_size_;
    const size_t output_size = stride * dec->pic_hdr_.height_;
    int ret = Z_OK;
    z_stream strm;

    memset(&strm, 0, sizeof(strm));
    if (inflateInit(&strm) != Z_OK) {
      return 0;
    }
    strm.avail_in = data_size;
    strm.next_in = (unsigned char*)data;
    do {
      strm.avail_out = output_size;
      strm.next_out = output;
      ret = inflate(&strm, Z_NO_FLUSH);
      if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) {
        break;
      }
    } while (strm.avail_out == 0);

    inflateEnd(&strm);
    if (ret != Z_STREAM_END) {
      return NULL;    // error
    }
  }
  return output + row * stride;
}

#if defined(__cplusplus) || defined(c_plusplus)
}    // extern "C"
#endif

#endif    // WEBP_EXPERIMENTAL_FEATURES


text:
<?php

namespace Spaark\CompositeUtils\Factory;
/**
 * Spaark
 *
 * Copyright (C) 2012 Emily Shepherd
 * emily@emilyshepherd.me
 */

class BaseFactory
{

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.05 at 10:14:54 오후 KST
//

package com.athena.chameleon.engine.entity.xml.ejbjar.jeus.v6_0;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;

/**
 *
Java class for security-interopElementType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="security-interopElementType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
 *     <enumeration value="NotSupported"/>
 *     <enumeration value="Supports"/>
 *     <enumeration value="Requires"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlEnum
public enum SecurityInteropElementType {

    @XmlEnumValue("NotSupported")
    NOT_SUPPORTED("NotSupported"),
    @XmlEnumValue("Requires")
    REQUIRES("Requires"),
    @XmlEnumValue("Supports")
    SUPPORTS("Supports");
    private final String value;

    SecurityInteropElementType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static SecurityInteropElementType fromValue(String v) {
        for (SecurityInteropElementType c: SecurityInteropElementType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v.toString());
    }

}


text:
import os
import sys
from setuptools import setup

f = open(os.path.join(os.path.dirname(__file__), 'README.rst'))
long_description = f.read()
f.close()

setup(
    name='wordbook',
    version='1.0.0',
    description='Python client for DICT Servers',
    long_description=long_description,
    url='http://github.com/tomplus/wordbook',
    author='Tomasz Prus',
    author_email='tomasz.prus@gmail.com',
    keywords=['DICT', 'dictionary'],
    license='MIT',
    packages=['wordbook'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ]
)


text:
class ApplicationMailer < ActionMailer::Base
  default from: 'foo@foo.com', to: 'bar@bar.com'

  def from_other_class
    mail template_path: 'notifier', template_name: 'custom_template'
  end
end


text:
import unittest
import textwrap
import antlr3
import antlr3.tree
import stringtemplate3
import testbase
import sys
import os
from StringIO import StringIO

# FIXME: port other tests from TestLexer.java

class T(testbase.ANTLRTest):
    def execParser(self, grammar, grammarEntry, input):
        lexerCls, parserCls = self.compileInlineGrammar(grammar)

        cStream = antlr3.StringStream(input)
        lexer = lexerCls(cStream)
        tStream = antlr3.CommonTokenStream(lexer)
        parser = parserCls(tStream)
        result = getattr(parser, grammarEntry)()
        return result

    def testRefToRuleDoesNotSetChannel(self):
        # this must set channel of A to HIDDEN.  $channel is local to rule
        # like $type.
        grammar = textwrap.dedent(
            r'''
            grammar P;
            options {
              language=Python;
            }
            a returns [foo]: A EOF { $foo = '\%s, channel=\%d' \% ($A.text, $A.channel); } ;
            A : '-' WS I ;
            I : '0'..'9'+ ;
            WS : (' '|'\n') {$channel=HIDDEN;} ;
            ''')

        found = self.execParser(
            grammar, 'a',
            "- 34"
            )

        self.failUnlessEqual("- 34, channel=0", found)

if __name__ == '__main__':
    unittest.main()


text:
import numpy as np
import sys

import lib.naive_bayes as nb
import lib.preprocessing as prep
import lib.validation as valid
import lib.binarization as bin

from config.constants import *

def case2(indexes=CASE_2_ATTRIBUTE_INDEXES,output=True):

    # does not distinguish between emails where an attribute appears more than
    # once as opposed to those where said attribute appears only once.

    # note that we're not using equiprobabilities for the priors.
    # we'll simulate the population priors using the sample priors.

    accuracy_in_each_turn = list()

    precision_in_each_turn_spam = list()
    recall_in_each_turn_spam = list()

    precision_in_each_turn_ham = list()
    recall_in_each_turn_ham = list()

    # just ones and zeros
    m = np.loadtxt(open("resources/binarized_data.csv","rb"),delimiter=',')

    shuffled = np.random.permutation(m)

    valid.validate_cross_validation(NUMBER_OF_ROUNDS,TRAIN_TEST_RATIO)

    for i in xrange(NUMBER_OF_ROUNDS):

        train_set,test_set = prep.split_sets(shuffled,TRAIN_TEST_RATIO,i)

        prior_spam = nb.take_p_spam(train_set,SPAM_ATTR_INDEX)
        prior_ham = nb.take_p_ham(train_set,SPAM_ATTR_INDEX)

        hits = 0.0
        misses = 0.0

        #number of instances correctly evaluated as spam
        correctly_is_spam = 0.0

        #total number of spam instances
        is_spam = 0.0

        #total number of instances evaluated as spam
        guessed_spam = 0.0

        #number of instances correctly evaluated as ham
        correctly_is_ham = 0.0

        #total number of ham instances
        is_ham = 0.0

        #total number of instances evaluated as ham
        guessed_ham = 0.0

        # we will pre-calculate these in order to save processing
        ps_attribute_spam = map(lambda elem: nb.take_p_attribute_spam(train_set,indexes[elem],SPAM_ATTR_INDEX),xrange(10))
        ps_attribute_ham = map(lambda elem: nb.take_p_attribute_ham(train_set,indexes[elem],SPAM_ATTR_INDEX),xrange(10))

        # now we test the hypothesis against the test set
        for row in test_set:

            # esses sao os valores do produtorio das probabilidades condicionais para spam e para ham, respectivamente.
            product_p_spam_attributes = reduce(lambda acc,elem: acc * ps_attribute_spam[elem] if row[indexes[elem]] == 1 else acc, xrange(10),1.0)
            product_p_ham_attributes = reduce(lambda acc,elem: acc * ps_attribute_ham[elem] if row[indexes[elem]] == 1 else acc, xrange(10),1.0)

            # o posterior eh igual ao prior vezes o produtorio das probabilidades condicionais
            p_spam_attribute = prior_spam * product_p_spam_attributes
            p_ham_attribute = prior_ham * product_p_ham_attributes

            # whichever is greater - that will be our prediction
            if p_spam_attribute > p_ham_attribute:
                guess = 1
            else:
                guess = 0

            # all these values should in theory be divided by the number
            # of features we're using, but we just want to know which
            # of the two (spam or ham) is more likely so even though the result
            # will be skewed by a constant, both classes will be multiplied
            # by that constant hence the comparison between the two is
            # still valid
            if (row[SPAM_ATTR_INDEX] == 0) and (guess == 0):
                is_ham += 1
                guessed_ham += 1
                correctly_is_ham += 1
                hits += 1
            elif (row[SPAM_ATTR_INDEX] == 0) and (guess == 1):
                is_ham += 1
                guessed_spam += 1
                misses += 1
            elif (row[SPAM_ATTR_INDEX] == 1) and (guess == 0):
                is_spam += 1
                guessed_ham += 1
                misses += 1
            elif (row[SPAM_ATTR_INDEX] == 1) and (guess == 1):
                is_spam += 1
                guessed_spam += 1
                correctly_is_spam += 1
                hits += 1

        #accuracy = number of correctly evaluated instances/
        #           number of instances
        #
        #
        accuracy = hits/(hits+misses)

        #precision_spam = number of correctly evaluated instances as spam/
        #            number of spam instances
        #
        #
        # in order to avoid divisions by zero in case nothing was found
        if(is_spam == 0):
            precision_spam = 0
        else:
            precision_spam = correctly_is_spam/is_spam

        #recall_spam = number of correctly evaluated instances as spam/
        #         number of evaluated instances como spam
        #
        #
        # in order to avoid divisions by zero in case nothing was found
        if(guessed_spam == 0):
            recall_spam = 0
        else:
            recall_spam = correctly_is_spam/guessed_spam

        #precision_ham = number of correctly evaluated instances as ham/
        #            number of ham instances
        #
        #
        # in order to avoid divisions by zero in case nothing was found
        if(is_ham == 0):
            precision_ham = 0
        else:
            precision_ham = correctly_is_ham/is_ham

        #recall_ham = number of correctly evaluated instances as ham/
        #         number of evaluated instances como ham
        #
        #
        # in order to avoid divisions by zero in case nothing was found
        if(guessed_ham == 0):
            recall_ham = 0
        else:
            recall_ham = correctly_is_ham/guessed_ham

        accuracy_in_each_turn.append(accuracy)

        precision_in_each_turn_spam.append(precision_spam)
        recall_in_each_turn_spam.append(recall_spam)

        precision_in_each_turn_ham.append(precision_ham)
        recall_in_each_turn_ham.append(recall_ham)

    mean_accuracy = np.mean(accuracy_in_each_turn)
    std_dev_accuracy = np.std(accuracy_in_each_turn)
    variance_accuracy = np.var(accuracy_in_each_turn)

    mean_precision_spam = np.mean(precision_in_each_turn_spam)
    std_dev_precision_spam = np.std(precision_in_each_turn_spam)
    variance_precision_spam = np.var(precision_in_each_turn_spam)

    mean_recall_spam = np.mean(recall_in_each_turn_spam)
    std_dev_recall_spam = np.std(recall_in_each_turn_spam)
    variance_recall_spam = np.var(recall_in_each_turn_spam)

    mean_precision_ham = np.mean(precision_in_each_turn_ham)
    std_dev_precision_ham = np.std(precision_in_each_turn_ham)
    variance_precision_ham = np.var(precision_in_each_turn_ham)

    mean_recall_ham = np.mean(recall_in_each_turn_ham)
    std_dev_recall_ham = np.std(recall_in_each_turn_ham)
    variance_recall_ham = np.var(recall_in_each_turn_ham)

    if output:
        print "\033[1;32m"
        print '============================================='
        print 'CASE 2 - TEN ATTRIBUTES - USING BERNOULLI MODEL'
        print '============================================='
        print "\033[00m"
        print 'MEAN ACCURACY: '+str(round(mean_accuracy,5))
        print 'STD. DEV. OF ACCURACY: '+str(round(std_dev_accuracy,5))
        print 'VARIANCE OF ACCURACY: '+str(round(variance_accuracy,8))
        print ''
        print 'MEAN PRECISION FOR SPAM: '+str(round(mean_precision_spam,5))
        print 'STD. DEV. OF PRECISION FOR SPAM: '+str(round(std_dev_precision_spam,5))
        print 'VARIANCE OF PRECISION FOR SPAM: '+str(round(variance_precision_spam,8))
        print ''
        print 'MEAN RECALL FOR SPAM: '+str(round(mean_recall_spam,5))
        print 'STD. DEV. OF RECALL FOR SPAM: '+str(round(std_dev_recall_spam,5))
        print 'VARIANCE OF RECALL FOR SPAM: '+str(round(variance_recall_spam,8))
        print ''
        print 'MEAN PRECISION FOR HAM: '+str(round(mean_precision_ham,5))
        print 'STD. DEV. OF PRECISION FOR HAM: '+str(round(std_dev_precision_ham,5))
        print 'VARIANCE OF PRECISION FOR HAM: '+str(round(variance_precision_ham,8))
        print ''
        print 'MEAN RECALL FOR HAM: '+str(round(mean_recall_ham,5))
        print 'STD. DEV. OF RECALL FOR HAM: '+str(round(std_dev_recall_ham,5))
        print 'VARIANCE OF RECALL FOR HAM: '+str(round(variance_recall_ham,8))

case2()


text:
package com.google.android.libraries.mobiledatadownload;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.mobiledatadownload.ClientConfigProto.ClientFileGroup;

/**
 * Runs custom validation routine on the file group. The file group is not allowed to become active
 * unless this returns true.
 *
 *
This callback is invoked for all file groups in the MDD instance. It is up to the implementor
 * to handle file groups that don't need validation by, eg, returning true immediately.
 *
 *
The ClientFileGroup account field is never populated during validation. The status field will
 * be set to PENDING_CUSTOM_VALIDATION.
 */
@CheckReturnValue
public interface CustomFileGroupValidator {
  ListenableFuture<Boolean> validateFileGroup(ClientFileGroup fileGroup);
}


text:
package com.stratio.decision.functions.dal;

import com.stratio.decision.commons.constants.ReplyCode;
import com.stratio.decision.commons.constants.STREAM_OPERATIONS;
import com.stratio.decision.commons.constants.StreamAction;
import com.stratio.decision.commons.messages.StratioStreamingMessage;
import com.stratio.decision.functions.ActionBaseFunction;
import com.stratio.decision.functions.validator.ActionEnabledValidation;
import com.stratio.decision.functions.validator.RequestValidation;
import com.stratio.decision.functions.validator.StreamNameNotEmptyValidation;
import com.stratio.decision.functions.validator.StreamNotExistsValidation;
import com.stratio.decision.service.StreamOperationService;

import java.util.Set;

public class SaveToSolrStreamFunction extends ActionBaseFunction {

    private static final long serialVersionUID = -689381870050478255L;

    public SaveToSolrStreamFunction(StreamOperationService streamOperationService, String zookeeperHost) {
        super(streamOperationService, zookeeperHost);
    }

    @Override
    protected String getStartOperationCommand() {
        return STREAM_OPERATIONS.ACTION.SAVETO_SOLR;
    }

    @Override
    protected String getStopOperationCommand() {
        return STREAM_OPERATIONS.ACTION.STOP_SAVETO_SOLR;
    }

    @Override
    protected boolean startAction(StratioStreamingMessage message) {
        getStreamOperationService().enableAction(message.getStreamName(), StreamAction.SAVE_TO_SOLR);
        return true;
    }

    @Override
    protected boolean stopAction(StratioStreamingMessage message) {
        getStreamOperationService().disableAction(message.getStreamName(), StreamAction.SAVE_TO_SOLR);
        return true;
    }

    @Override
    protected void addStopRequestsValidations(Set<RequestValidation> validators) {
        validators.add(new StreamNameNotEmptyValidation());
        validators.add(new StreamNotExistsValidation(getStreamOperationService()));
    }

    @Override
    protected void addStartRequestsValidations(Set<RequestValidation> validators) {
        validators.add(new StreamNameNotEmptyValidation());
        validators.add(new ActionEnabledValidation(getStreamOperationService(), StreamAction.SAVE_TO_SOLR,
                ReplyCode.KO_ACTION_ALREADY_ENABLED.getCode()));
        validators.add(new StreamNotExistsValidation(getStreamOperationService()));
    }

}


text:
path: /blog/easy-caching-with-nginx
title: Easy Caching with Nginx
date: 08/25/2019
categories: Nginx, OpenResty, Caching
---

Web response time has a clear impact on if potential prospects will stay on your site and become engaged with your product. What happens when a website is slower than desired? They leave before you can woo them. Obviously, website reliability is very key as well. When we make an api request, or request a remote stylesheet or javascript asset, we expect it to given to us. What happens when the resource is not available or the upstream server that has the resource is down? Not good.

These two problems can be addressed very elegantly and succinctly by using out of the box nginx caching capabilities.

Caching can be hard, and introduces complexity. When we begin to work out our caching strategy there are important questions we must answer. Some of these include:

 1. **Do we do an in-process cache for one service or an out-of-process cache that multiple services can benefit from?**

 2. **If we want to do out-of-process caching. How do we do it?**

 3. **What if an upstream service is failing, how can we continue to serve the response if cached?**

 4. **How can we ignore the cache and get the result from the upstream?**

There tons of ways we could go about solving these problems using different software packages, caching applications, etc... It would also depend on the skills of your team, the throughput demands your system, and assuming you are not starting from scratch, leveraging what you have already built. If you are starting from scratch... Nice! Have fun!

For the purposes of this article we will only be focused on caching "safe" requests (`GET`, `HEAD`, `OPTIONS`). Caching non-safe request methods like `POST`, requires other considerations when it comes to both fast response time, resilliency, and managing complexity. In these cases you might investigate using a more involved `cache-aside` or `read-through/write-through` pattern. Both of these topics could posts by themselves.

This blog is also focused caching the types of things that don't change often. Meaning, it's focused on eventual consistency and not strong consistency. If you are unfamiliar with these two terms here is a quick catch-up:

***Strong consistency***: data in a store of record gets updated to all consumers as soon as a write is made. Real world example. If I deposit money into your bank account you can see that money and use it right away.

***Eventual consistency***: data that gets updated in a store of record and gets propagated to consumers eventually, but not at the time of write neccesarily. Real world example. A rules engine on streaming platform. Everytime you press play, it determines if you can listen to a song based on your billing address, copyright laws, and distribution agreements. The computation to determine this does not change often. When implemented with an eventual consistenct cache you get to listen to your music faster with minimal complexity on the backend.

I've found that typically eventual consistency in caching for much web development is just fine. For those cases that are not, you might need to use a more complicated approach than what I describe below.

Lastly, for simplicity, this blog will ignore the implementation of the `Cache-Control` header which is used to tell any application with an HTTP Cache how to cache a request/response.

### In-Process vs Out-of-Process Application Cache

In the world of software architecture. Less is more! When you are building a solution, an important question to ask is: Could it be simplier? If you have one node.js service for example, it might make more sense to have an in memory store as opposed to spinning up a separate cache. This might be better considering the inherit complexity when you create an in memory cache. I've definitely gotten bitten on a couple occasions from using code that leveraged an in process cache. This was due to the over-complexity of the implementation, stemming from what I think is a lack of a standard approach to this problem. There are alot of different ways to set up an in memory cache! In any case, simplicity is your best friend! This is the huge benefit for setting up caching with nginx. It's easy.

**Will multiple services be making requests, and where is the upstream server?**

If you already have a reverse proxy or an API gateway in front of the service calls (I hope you do), then it makes sense to add a cache to the "front door". This avoids duplicating in memory caches for each service being called. Especially if your team(s) are polyglot!

**Will the latency of requests to an out of process cache negate any performance gain that it would give you?**

The response time it takes to get a cached result from a cache might negate caching in the first place, as it might take longer to get the cached result, than retrieving it from upstream. Additionally, if the 99 percentile response time for the upstream service call is not very long you could maybe make your Service Level Agreement (SLA) without caching. At that point there are still benefits to the cache, such as a fallback for upstream failures. As you will see later, this is a powerful pattern and easy to implement in nginx.

**What if you have many application instances?**

Back to eventual vs strong consistency mentioned earlier. The more application instances you have with in-memory stores the more important data consistency might become, as different application instances might have different versions of the upstream response. When you use nginx as a central store, and are not using clustering or redis, this is still reduced because typically nginx can operate with fewer instances than most application servers can such as node.js.

Ultimately, remember that simplicity is your friend here. Whatever you do, make a conscious effort to make as few components with as little logic as possible, because you, or someone else, will eventually get confused by the code. It's inevitable! Minimize this.

### Setting Up Nginx Caching

[You can access the completed tutorial repo here](https://github.com/danielbh/openresty-caching-example)

A resource that rarely changes is a great candidate for caching. For example: a stylesheet or script. Depending on if your application is internet facing you could put assets behind a CDN like AWS Cloudfront as your users might be distributed around the world. In other cases it could make sense to have certain backend calls for data or assets cached on a cache you control, in a proxy, to avoid the round trip to upstream services.

**How do we setup an nginx cache?**

```conf

http {

  proxy_cache_path /tmp/my_cache keys_zone=my_cache:10m levels=1:2 inactive=600s max_size=100m;

  proxy_cache_valid 200 302 10m;
  proxy_cache_valid 404      1m;
  proxy_cache_methods GET;

  add_header X-Cache $upstream_cache_status;

  server {
      listen 80 default_server;
      location / {
        proxy_cache my_cache;
        proxy_cache_key $uri;
        proxy_pass  http://goapp:8000;
      }
  }
}

```

`proxy_cache_path`: This is how we setup the cache.

`/tmp/my_cache`: This is the path where a cache exists. The directory you use is the unique identifer for this cache when used in other directives that you want to apply to it. Here we are calling the cache "my_cache".

`keys_zone=my_cache:10m`: This is the maxium storage that is is being allocated for cache keys. This allocates 10 mb for cache keys. 10 mb is about 80,000 keys.

`levels=1:2`: This is the hierarchy of directories being used in the cache for files. Here we have a two level hiearchy. By default nginx uses a one level hiearchy. This is less efficient because items would be retrieved from the same folder which can slowdown file access.

`inactive=600s`: This is the eviction time for a cache entry. After this duration the entry will be removed from the cache. Note: This is different from `proxy_cache_valid` which states if an item is stale or not.

` max_size=100m`: Upper limit of the size of the cache. It is optional; if not specified it will use all available disk space. When cache limit reached. A process called the cache manager removes the files that were least recently used to reduce the cache size.

`proxy_cache_valid`: This directive says under what circumstances a request will be cached and how long until an entry is stale.

  - `code`: The http status codes whose corresponding response will be cached.

  - `time`: The amount of time until the cache entry is considered "stale" This is different from the `inactive` directive which will remove the item from the cache.

`proxy_cache_methods`: The REST methods whose responses will be cached.

`add_header X-Cache $upstream_cache_status`: This will tell the consumer of the request the state of the cache. The status can be either "MISS", "BYPASS", "EXPIRED", "STALE", "UPDATING", "REVALIDATED", or "HIT".

`proxy_cache my_cache`: This is the cache that this location block will use. You can set each location block to use a different cache. This is useful if you want to set different parameters for different location blocks. Perhaps you want to set `inactive` differently for different location blocks.

`proxy_cache_key:` This is the cache key for the look-up of the response. Above we are using the `$uri` variable. The `$uri` is the path used after the host. For example, if you made a request to `website.com/path` the `$uri` would be `/path`. The `$uri` variable is one of many convenience variables we can use in our nginx configurations. [Here are more variables](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_status).

### Handling Failing Upstreams with Cache

![handling failing upstreams with cache nginx](handling-failing-upstreams-with-cache.png)

This next feature I'm going to tell you about is *hands-down one of my favorite nginx features*. I love it because how powerful it is, and how easy it is to do. It applies most if you are sending "safe" requests (GET, HEAD, OPTIONS), and the upstream service you are proxying to is failing. In this case, you can set nginx to return that cached request, even if it's stale. I've seen this work in production and it is b-e-a-u-t-i-f-u-l. When you do this just be sure that you have alerting on the failing upstream service so you know there is an issue.

```conf
...

proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;

...

server {
      listen 80 default_server;

      location /cached/ {
        proxy_cache my_cache;
        proxy_cache_key $uri;
        proxy_pass  http://goapp:8000/;
      }

      location / {
        proxy_pass  http://goapp:8000;
      }
  }
```

`proxy_cache_use_stale`: These are all the error situations that you want to fallback to a stale cache.

`proxy_cache_background_update`: Allows starting a background subrequest to update an expired cache item. During this time a stale cached response is returned to the client. This is neccesary so that a stale cache will be used when an upstream is failing.

`location /cached/`: This location block will use the cache and will fallback to it when the upstream fails. Notice the trailing slash after `cached` and `http://goapp:8000`. This matters!

`location /`: This location block remains un-cached.

`http://goapp:8000`: This url maps to a go application that will fail every other request with a 500. It does this on the `/failodd` endpoint.

Let's see this in action:

```shell

# un-cached route

$ curl -D - localhost:8080/failodd

HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Sat, 24 Aug 2019 17:12:08 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 18
Connection: keep-alive

Everything is fine

$ curl -D - localhost:8080/failodd

HTTP/1.1 500 Internal Server Error
Server: openresty/1.15.8.1
Date: Sat, 24 Aug 2019 17:12:11 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 28
Connection: keep-alive

Uh oh something bad happened

# cached route

$ curl -D - localhost:8080/cached/failodd

HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Sat, 24 Aug 2019 17:12:50 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 18
Connection: keep-alive
X-Cache: MISS

Everything is fine

$ curl -D - localhost:8080/cached/failodd

HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Sat, 24 Aug 2019 17:13:17 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 18
Connection: keep-alive
X-Cache: HIT

Everything is fine

```

Notice you can tell that it was cached because the `X-Cache` response header was sent back. With either `HIT` meaning the response is cached, or `MISS` the response is fresh.

### Cache Bypass and Invalidation

Ah yes... The bane of every caching strategy. What happens when a cached resource changes and you immediately
want to use the new version... There is good new and bad news when it comes to Nginx. Bad news first. [Cache purging through exposing an endpoint from nginx requires nginx+](https://docs.nginx.com/nginx/admin-guide/content-cache/content-caching/#purge). However, fear not. There are some good work-arounds depending on your situtation. Here we will go through two use-cases. Bypassing and Invalidation.

**Bypass**

For this strategy, the pre-requisite is that you don't know if there is a new version of the cached response, but you force it through the use of the `proxy_cache_bypass` directive. You could also just send a query string through that would change the cache key, but `proxy_cache_bypass` is easier to read and more standard.

To do this you can use a cookie or header. The cookie is just prefaced with `$cookie_` then you add the name of your cookie. You could do `$cookie_yourkey` then you add `$arg_cookie`. Similarly, if you want use a header just add `$http_`. Below we are using a header called `$http_bypass_cache`. Here the value of the header does not matter, but must be set to somthing when you send it. You could just write "yes" or "true" for readability. Another important thing to note is **you must** have `underscores_in_headers on` enabled.

Quick note on the `Cache-Control` request header. You could use `$http_cache_control`, but that might be confusing for consumers since they might think the value matters which it does not. i.e. `no-cache` vs `max-age=<seconds>`. Nginx does not have this built in 😭.

```conf
server {
 ...

  underscores_in_headers on;

  ...

  location /cached/ {
    ...
    proxy_cache_bypass $http_bypass_cache;
    proxy_pass  http://goapp:8000/;
  }

  ...
}
```

Let's use the fail-odd example again. This time on the odd number of request we will pass a cache bypass header through and it fail with a 500 even though it's cached.

```conf

$ curl -H "bypass_cache:true" -D - localhost:8080/cached/failodd

HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Sat, 24 Aug 2019 18:03:05 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 18
Connection: keep-alive
X-Cache: BYPASS

Everything is fine

$ curl -H "bypass_cache:true" -D - localhost:8080/cached/failodd

HTTP/1.1 500 Internal Server Error
Server: openresty/1.15.8.1
Date: Sat, 24 Aug 2019 18:03:07 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 28
Connection: keep-alive

Uh oh something bad happened

```

**Invalidation of API calls**

Now what about API calls backed by a database? Remember that cache-purging requires an nginx+ commercial license if you want it out of the box, but you still have other options if you would rather build it than buy it.

Also, the pre-requisite for these approaches is that on every database write you need to send out a fire and forget web request to an nginx cache invalidation endpoint. In this situation would want to make sure your nginx instances are clusted so this invalidation takes effect on all instances. If you elect to use a separate distributed cache such as redis, you send the invalidation request to the cache itself, and the nginx instances would just be connected to it.

Lastly, keep in mind the consequences of purging a shared cache. You might want to add things like authorization to confirm those who attempt to purge the cache are allowed to do so.

Here are some approaches you could take:

1) This guy, FRiCKLE, [created an nginx module that enables cache purging](https://github.com/FRiCKLE/ngx_cache_purge). Disclaimer! I have not used it, but I plan to do some experiments with it. I will update with a post when I've had time to do this.

2) Another alternative could be to use an in process least-recently used (lru) cache implemented in Lua with [lua-resty-lrucache](https://github.com/openresty/lua-resty-lrucache) module.

3) You could also use the nginx or OpenResty redis module. Your microservice that is making writes to the database could be connected to an out of process cache, for example... redis. Then you just setup a cache purging endpoint which removes the entry from redis. You could also have logic to read the redis entry. You have a few options here. A disclaimer for these is that I know of only one instance using the `lua-resty-redis` module in production. The other two I have not tried.

   - [ngx http redis module](https://www.nginx.com/resources/wiki/modules/redis/)
   - [openresty-redis-module](https://github.com/openresty/redis2-nginx-module#readme)
   - [lua-resty-redis](https://github.com/openresty/lua-resty-redis)

### Conclusion

As you can see nginx offers a variety of options for any backend caching strategy that you'd like to create. Most patterns are very simple and easy to implement. For free software you get some good bang for your buck. However, some options that are more complicated than others.

Nginx and OpenResty are great technologies, but can become difficult as instances grow in complexity. I'm an Nginx and OpenResty specialist. If are working with Nginx OpenResty and would like help on your project. [Drop me a line](/contact). Happy to help.


text:
#if !PCL
using System;
using MoonSharp.Interpreter.Loaders;

namespace MoonSharp.Interpreter.REPL
{
    /// <summary>
    ///     A script loader loading scripts directly from the file system (does not go through platform object)
    ///     AND starts with module paths taken from environment variables (again, not going through the platform object).
    ///     The paths are preconstructed using :
    ///     * The MOONSHARP_PATH environment variable if it exists
    ///     * The LUA_PATH_5_2 environment variable if MOONSHARP_PATH does not exists
    ///     * The LUA_PATH environment variable if LUA_PATH_5_2 and MOONSHARP_PATH do not exists
    ///     * The "?;?.lua" path if all the above fail
    ///     Also, everytime a module is require(d), the "LUA_PATH" global variable is checked. If it exists, those paths
    ///     will be used to load the module instead of the global ones.
    /// </summary>
    public class ReplInterpreterScriptLoader : FileSystemScriptLoader
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="ReplInterpreterScriptLoader" /> class.
        /// </summary>
        public ReplInterpreterScriptLoader()
        {
            var env = Environment.GetEnvironmentVariable("MOONSHARP_PATH");
            if (!string.IsNullOrEmpty(env)) ModulePaths = UnpackStringPaths(env);

            if (ModulePaths == null)
            {
                env = Environment.GetEnvironmentVariable("LUA_PATH_5_2");
                if (!string.IsNullOrEmpty(env)) ModulePaths = UnpackStringPaths(env);
            }

            if (ModulePaths == null)
            {
                env = Environment.GetEnvironmentVariable("LUA_PATH");
                if (!string.IsNullOrEmpty(env)) ModulePaths = UnpackStringPaths(env);
            }

            if (ModulePaths == null)
            {
                ModulePaths = UnpackStringPaths("?;?.lua");
            }
        }

        /// <summary>
        ///     Resolves the name of a module to a filename (which will later be passed to OpenScriptFile).
        ///     The resolution happens first on paths included in the LUA_PATH global variable, and -
        ///     if the variable does not exist - by consulting the
        ///     ScriptOptions.ModulesPaths array. Override to provide a different behaviour.
        /// </summary>
        /// <param name="modname">The modname.</param>
        /// <param name="globalContext">The global context.</param>
        /// <returns></returns>
        public override string ResolveModuleName(string modname, Table globalContext)
        {
            var s = globalContext.RawGet("LUA_PATH");

            if (s != null && s.Type == DataType.String)
                return ResolveModuleName(modname, UnpackStringPaths(s.String));

            return base.ResolveModuleName(modname, globalContext);
        }
    }
}

#endif


text:
#pragma once

#if defined(HAVE_OMXLIB)

#if (defined HAVE_CONFIG_H) && (!defined WIN32)
  #include "config.h"
#endif
#ifndef __GNUC__
#pragma warning(push)
#pragma warning(disable:4244)
#endif

#include "DynamicDll.h"
#include "utils/log.h"

#include <IL/OMX_Core.h>
#include <IL/OMX_Component.h>
#include <IL/OMX_Index.h>
#include <IL/OMX_Image.h>
#include <IL/OMX_Video.h>
#include <IL/OMX_Broadcom.h>

////////////////////////////////////////////////////////////////////////////////////////////

class DllOMXInterface
{
public:
  virtual ~DllOMXInterface() {}

  virtual OMX_ERRORTYPE OMX_Init(void) = 0;
  virtual OMX_ERRORTYPE OMX_Deinit(void) = 0;
  virtual OMX_ERRORTYPE OMX_GetHandle(OMX_HANDLETYPE *pHandle, OMX_STRING cComponentName, OMX_PTR pAppData, OMX_CALLBACKTYPE *pCallBacks) = 0;
  virtual OMX_ERRORTYPE OMX_FreeHandle(OMX_HANDLETYPE hComponent) = 0;
  virtual OMX_ERRORTYPE OMX_GetComponentsOfRole(OMX_STRING role, OMX_U32 *pNumComps, OMX_U8 **compNames) = 0;
  virtual OMX_ERRORTYPE OMX_GetRolesOfComponent(OMX_STRING compName, OMX_U32 *pNumRoles, OMX_U8 **roles) = 0;
  virtual OMX_ERRORTYPE OMX_ComponentNameEnum(OMX_STRING cComponentName, OMX_U32 nNameLength, OMX_U32 nIndex) = 0;
  virtual OMX_ERRORTYPE OMX_SetupTunnel(OMX_HANDLETYPE hOutput, OMX_U32 nPortOutput, OMX_HANDLETYPE hInput, OMX_U32 nPortInput) = 0;

};

#if (defined USE_EXTERNAL_OMX)
class DllOMX : public DllDynamic, DllOMXInterface
{
public:
  virtual OMX_ERRORTYPE OMX_Init(void)
    { return ::OMX_Init(); };
  virtual OMX_ERRORTYPE OMX_Deinit(void)
    { return ::OMX_Deinit(); };
  virtual OMX_ERRORTYPE OMX_GetHandle(OMX_HANDLETYPE *pHandle, OMX_STRING cComponentName, OMX_PTR pAppData, OMX_CALLBACKTYPE *pCallBacks)
    { return ::OMX_GetHandle(pHandle, cComponentName, pAppData, pCallBacks); };
  virtual OMX_ERRORTYPE OMX_FreeHandle(OMX_HANDLETYPE hComponent)
    { return ::OMX_FreeHandle(hComponent); };
  virtual OMX_ERRORTYPE OMX_GetComponentsOfRole(OMX_STRING role, OMX_U32 *pNumComps, OMX_U8 **compNames)
    { return ::OMX_GetComponentsOfRole(role, pNumComps, compNames); };
  virtual OMX_ERRORTYPE OMX_GetRolesOfComponent(OMX_STRING compName, OMX_U32 *pNumRoles, OMX_U8 **roles)
    { return ::OMX_GetRolesOfComponent(compName, pNumRoles, roles); };
  virtual OMX_ERRORTYPE OMX_ComponentNameEnum(OMX_STRING cComponentName, OMX_U32 nNameLength, OMX_U32 nIndex)
    { return ::OMX_ComponentNameEnum(cComponentName, nNameLength, nIndex); };
  virtual OMX_ERRORTYPE OMX_SetupTunnel(OMX_HANDLETYPE hOutput, OMX_U32 nPortOutput, OMX_HANDLETYPE hInput, OMX_U32 nPortInput)
    { return ::OMX_SetupTunnel(hOutput, nPortOutput, hInput, nPortInput); };
  virtual bool ResolveExports()
    { return true; }
  virtual bool Load()
  {
    CLog::Log(LOGDEBUG, "DllOMX: Using omx system library");
    return true;
  }
  virtual void Unload() {}
  static DllOMX *GetDllOMX() { static DllOMX static_dll_omx; return &static_dll_omx; }
};
#else
class DllOMX : public DllDynamic, DllOMXInterface
{
  //DECLARE_DLL_WRAPPER(DllLibOpenMax, "/usr/lib/libnvomx.so")
  DECLARE_DLL_WRAPPER(DllOMX, "/opt/vc/lib/libopenmaxil.so")

  DEFINE_METHOD0(OMX_ERRORTYPE, OMX_Init)
  DEFINE_METHOD0(OMX_ERRORTYPE, OMX_Deinit)
  DEFINE_METHOD4(OMX_ERRORTYPE, OMX_GetHandle, (OMX_HANDLETYPE *p1, OMX_STRING p2, OMX_PTR p3, OMX_CALLBACKTYPE *p4))
  DEFINE_METHOD1(OMX_ERRORTYPE, OMX_FreeHandle, (OMX_HANDLETYPE p1))
  DEFINE_METHOD3(OMX_ERRORTYPE, OMX_GetComponentsOfRole, (OMX_STRING p1, OMX_U32 *p2, OMX_U8 **p3))
  DEFINE_METHOD3(OMX_ERRORTYPE, OMX_GetRolesOfComponent, (OMX_STRING p1, OMX_U32 *p2, OMX_U8 **p3))
  DEFINE_METHOD3(OMX_ERRORTYPE, OMX_ComponentNameEnum, (OMX_STRING p1, OMX_U32 p2, OMX_U32 p3))
  DEFINE_METHOD4(OMX_ERRORTYPE, OMX_SetupTunnel, (OMX_HANDLETYPE p1, OMX_U32 p2, OMX_HANDLETYPE p3, OMX_U32 p4));
  BEGIN_METHOD_RESOLVE()
    RESOLVE_METHOD(OMX_Init)
    RESOLVE_METHOD(OMX_Deinit)
    RESOLVE_METHOD(OMX_GetHandle)
    RESOLVE_METHOD(OMX_FreeHandle)
    RESOLVE_METHOD(OMX_GetComponentsOfRole)
    RESOLVE_METHOD(OMX_GetRolesOfComponent)
    RESOLVE_METHOD(OMX_ComponentNameEnum)
    RESOLVE_METHOD(OMX_SetupTunnel)
  END_METHOD_RESOLVE()

public:
  virtual bool Load()
  {
    return DllDynamic::Load();
  }
};
#endif

#endif


text:
<?php

namespace mako\tests\unit\validator\rules;

use mako\tests\TestCase;
use mako\validator\rules\Natural;

/**
 * @group unit
 */
class NaturalTest extends TestCase
{
	/**
	 *
	 */
	public function testValidatesWhenEmpty()
	{
		$rule = new Natural;

		$this->assertFalse($rule->validateWhenEmpty());
	}

	/**
	 *
	 */
	public function testWithValidValue()
	{
		$rule = new Natural;

		$this->assertTrue($rule->validate(0, []));
		$this->assertTrue($rule->validate(1, []));
		$this->assertTrue($rule->validate('1', []));
	}

	/**
	 *
	 */
	public function testWithInvalidValue()
	{
		$rule = new Natural;

		$this->assertFalse($rule->validate(1.1, []));
		$this->assertFalse($rule->validate('1.1', []));

		$this->assertSame('The foobar field must contain a natural number.', $rule->getErrorMessage('foobar'));
	}
}


text: export { default } from 'ember-trello/adapters/label';


text:
describe("Connected Mode", function() {
  it("can save a password profile on connected mode", function() {
    cy.visit("/");
    cy.get(".fa-sign-in").click();
    cy.get("#email").type("test@lesspass.com");
    cy.get("#passwordField").type("test@lesspass.com");
    cy.get("#encryptMasterPassword__btn").click();
    cy.get("#fingerprint .fa-university").should("be.visible");
    cy.get("#fingerprint .fa-btc").should("be.visible");
    cy.get("#fingerprint .fa-subway").should("be.visible");
    cy.get("#signInButton").click();
    cy.get("#siteField").type("lesspass.com").blur();
    cy.get("#login").type("test@lesspass.com");
    cy.get("#passwordField").type("test@lesspass.com");
    cy.get("#generatePassword__btn").click();
    cy.get("#generated-password").should("have.value", "hjV@\\5ULp3bIs,6B");
    cy.get(".fa-save").should("be.visible");
    cy.get(".fa-sign-out").click();
    cy.get(".fa-save").should("not.be.visible");
  });
  it("can log in and log out", function() {
    cy.visit("/");
    cy.get(".fa-sign-in").click();
    cy.get("#baseURL").should("have.value", "https://lesspass.com");
    cy.get("#email").type("test@lesspass.com");
    cy.get("#passwordField").type("test@lesspass.com");
    cy.get("#encryptMasterPassword__btn").click();
    cy.wait(500);
    cy.get("#signInButton").click();
    cy.get("#siteField").should("be.visible");
    cy.get(".fa-key").should("be.visible");
    cy.get(".fa-sign-out").click();
    cy.get(".fa-key").should("not.be.visible");
  });
  it("reset password page", function() {
    cy.visit("/");
    cy.get(".fa-sign-in").click();
    cy.get("#login__forgot-password-btn").click();
    cy.get("#password-reset__reset-password-btn").click();
  });
  it("use saved profile", function() {
    cy.visit("/");
    cy.get(".fa-sign-in").click();
    cy.get("#baseURL").should("have.value", "https://lesspass.com");
    cy.get("#email").type("test@lesspass.com");
    cy.get("#passwordField").type("test@lesspass.com");
    cy.get("#encryptMasterPassword__btn").click();
    cy.wait(500);
    cy.get("#signInButton").click();
    cy.get(".fa-key").click();
    cy.get(".passwordProfile__meta")
      .first()
      .click();
    cy.get("#siteField").should("have.value", "example.org");
    cy.get("#login").should("have.value", "contact@example.org");
    cy.get(".fa-sign-out").click();
  });
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Justicia appressa Forssk.

### Remarks
null


text:
require 'spec_helper'

RSpec.describe Brcobranca::Remessa::Cnab400::BancoBrasil do
  let(:pagamento) do
    Brcobranca::Remessa::Pagamento.new(valor: 199.9,
                                       data_vencimento: Date.current,
                                       nosso_numero: 123,
                                       documento_sacado: '12345678901',
                                       nome_sacado: 'PABLO DIEGO JOSÉ FRANCISCO DE PAULA JUAN NEPOMUCENO MARÍA DE LOS REMEDIOS CIPRIANO DE LA SANTÍSSIMA TRINIDAD RUIZ Y PICASSO',
                                       endereco_sacado: 'RUA RIO GRANDE DO SUL São paulo Minas caçapa da silva junior',
                                       bairro_sacado: 'São josé dos quatro apostolos magros',
                                       cep_sacado: '12345678',
                                       cidade_sacado: 'Santa rita de cássia maria da silva',
                                       uf_sacado: 'SP')
  end
  let(:params) do
    { carteira: '12',
      agencia: '1234',
      variacao_carteira: '123',
      convenio: '1234567',
      convenio_lider: '7654321',
      conta_corrente: '1234',
      empresa_mae: 'SOCIEDADE BRASILEIRA DE ZOOLOGIA LTDA',
      documento_cedente: '12345678910',
      sequencial_remessa: '1',
      pagamentos: [pagamento],
      tipo_cobranca: '04DSC' }
  end
  let(:banco_brasil) { subject.class.new(params) }

  context 'validacoes dos campos' do
    context '@agencia' do
      it 'deve ser invalido se nao possuir uma agencia' do
        object = subject.class.new(params.merge!(agencia: nil))
        expect(object.invalid?).to be true
        expect(object.errors.full_messages).to include('Agencia não pode estar em branco.')
      end

      it 'deve ser invalido se a agencia tiver mais de 4 digitos' do
        banco_brasil.agencia = '12345'
        expect(banco_brasil.invalid?).to be true
        expect(banco_brasil.errors.full_messages).to include('Agencia deve ser igual a 4 digítos.')
      end
    end

    context '@conta_corrente' do
      it 'deve ser invalido se nao possuir uma conta corrente' do
        object = subject.class.new(params.merge!(conta_corrente: nil))
        expect(object.invalid?).to be true
        expect(object.errors.full_messages).to include('Conta corrente não pode estar em branco.')
      end

      it 'deve ser invalido se a conta corrente tiver mais de 5 digitos' do
        banco_brasil.conta_corrente = '123456789'
        expect(banco_brasil.invalid?).to be true
        expect(banco_brasil.errors.full_messages).to include('Conta corrente deve ser menor ou igual a 8 dígitos.')
      end
    end

    context '@carteira' do
      it 'deve ser invalido se nao possuir uma carteira' do
        object = subject.class.new(params.merge!(carteira: nil))
        expect(object.invalid?).to be true
        expect(object.errors.full_messages).to include('Carteira não pode estar em branco.')
      end

      it 'deve ser invalido se a carteira nao tiver 2 digitos' do
        banco_brasil.carteira = '123'
        expect(banco_brasil.invalid?).to be true
        expect(banco_brasil.errors.full_messages).to include('Carteira deve ser igual a 2 digítos.')
      end
    end

    context '@convenio' do
      it 'deve ser invalido se nao possuir o convenio' do
        object = subject.class.new(params.merge!(convenio: nil))
        expect(object.invalid?).to be true
        expect(object.errors.full_messages).to include('Convenio não pode estar em branco.')
      end
    end

    context '@variacao_carteira' do
      it 'deve ser invalido se nao possuir a variacao da carteira' do
        object = subject.class.new(params.merge!(variacao_carteira: nil))
        expect(object.invalid?).to be true
        expect(object.errors.full_messages).to include('Variacao carteira não pode estar em branco.')
      end

      it 'deve ser invalido se a carteira nao tiver 3 digitos' do
        banco_brasil.variacao_carteira = '1234'
        expect(banco_brasil.invalid?).to be true
        expect(banco_brasil.errors.full_messages).to include('Variacao carteira deve ser igual a 3 digítos.')
      end
    end

    context '@documento_cedente' do
      it 'deve ser invalido se nao possuir o documento cedente' do
        object = subject.class.new(params.merge!(documento_cedente: nil))
        expect(object.invalid?).to be true
        expect(object.errors.full_messages).to include('Documento cedente não pode estar em branco.')
      end

      it 'deve ser invalido se o documento do cedente nao tiver entre 11 e 14 digitos' do
        banco_brasil.documento_cedente = '123'
        expect(banco_brasil.invalid?).to be true
        expect(banco_brasil.errors.full_messages).to include('Documento cedente deve ter entre 11 e 14 dígitos.')
      end
    end
  end

  context 'formatacoes dos valores' do
    it 'cod_banco deve ser 001' do
      expect(banco_brasil.cod_banco).to eq '001'
    end

    it 'nome_banco deve ser BANCODOBRASIL com 15 posicoes' do
      nome_banco = banco_brasil.nome_banco
      expect(nome_banco.size).to eq 15
      expect(nome_banco.strip).to eq 'BANCODOBRASIL'
    end

    it 'complemento deve retornar 294 posicoes com as suas informacoes' do
      complemento = banco_brasil.complemento
      expect(complemento.size).to eq 294
      expect(complemento[0..6]).to eq '0000001'    # sequencial de remessa
      expect(complemento[29..35]).to eq '7654321'  # numero do convenio lider
    end

    it 'info_conta deve retornar com 20 posicoes as informacoes da conta' do
      info_conta = banco_brasil.info_conta
      expect(info_conta.size).to eq 20
      expect(info_conta[0..3]).to eq '1234'                              # num. da agencia
      expect(info_conta[4]).to eq banco_brasil.agencia_dv.to_s           # digito da agencia
      expect(info_conta[5..12]).to eq '00001234'                         # num. da conta corrente
      expect(info_conta[13]).to eq banco_brasil.conta_corrente_dv.to_s   # digito da conta corrente
    end
  end

  context 'monta remessa' do
    it_behaves_like 'cnab400'

    context 'header' do
      it 'informacoes devem estar posicionadas corretamente no header' do
        header = banco_brasil.monta_header
        expect(header[1]).to eq '1'                                                 # tipo operacao (1 = remessa)
        expect(header[2..8]).to eq 'REMESSA'                                        # literal da operacao
        expect(header[26..45]).to eq banco_brasil.info_conta                        # informacoes da conta
        expect(header[46..75]).to eq 'SOCIEDADE BRASILEIRA DE ZOOLOGIA LTDA'[0..29] # nome da empresa cedente
        expect(header[76..78]).to eq '001'                                          # codigo do banco
        expect(header[79..93]).to eq 'BANCODOBRASIL'.ljust(15, ' ')                 # nome do banco
        expect(header[100..393]).to eq banco_brasil.complemento                     # complemento
      end
    end

    context 'detalhe' do
      it 'informacoes devem estar posicionadas corretamente no detalhe' do
        detalhe = banco_brasil.monta_detalhe pagamento, 1
        expect(detalhe[3..16]).to eq '00012345678910'                           # documento do cedente
        expect(detalhe[17..20]).to eq '1234'                                    # agencia
        expect(detalhe[21]).to eq banco_brasil.agencia_dv.to_s                  # digito da agencia
        expect(detalhe[22..29]).to eq '00001234'                                # num. da conta corrente
        expect(detalhe[30]).to eq banco_brasil.conta_corrente_dv.to_s           # digito da conta corrente
        expect(detalhe[31..37]).to eq '1234567'                                 # convenio da empresa
        expect(detalhe[70..79]).to eq '0000000123'                              # nosso numero
        expect(detalhe[91..93]).to eq '123'                                     # variacao da carteira
        expect(detalhe[101..105]).to eq '04DSC'                                 # tipo de cobranca
        expect(detalhe[106..107]).to eq '12'                                    # carteira
        expect(detalhe[120..125]).to eq Date.current.strftime('%d%m%y')         # data de vencimento
        expect(detalhe[126..138]).to eq '0000000019990'                         # valor do titulo
        expect(detalhe[156..157]).to eq '00'                                    # primeira instrucao
        expect(detalhe[158..159]).to eq '00'                                    # segunda instrucao
        expect(detalhe[220..233]).to eq '00012345678901'                        # documento do pagador
        expect(detalhe[234..270]).to eq 'PABLO DIEGO JOSE FRANCISCO DE PAULA J' # nome do pagador
      end
    end

    context 'arquivo' do
      before { Timecop.freeze(Time.local(2015, 7, 14, 16, 15, 15)) }
      after { Timecop.return }

      it { expect(banco_brasil.gera_arquivo).to eq(read_remessa('remessa-banco-brasil-cnab400.rem', banco_brasil.gera_arquivo)) }
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Module: PaymentProfileCim

    — Documentation by YARD 0.8.2.1

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" media="screen" charset="utf-8" />

    Index (P) »

    PaymentProfileCim

(no frames)

      Class List

      Method List

      File List

Module: PaymentProfileCim

Includes:

ActiveMerchant::Billing

Included in:

PaymentProfile

Defined in:

app/models/payment_profile_cim.rb

      Instance Method Summary
      (collapse)

      - (Object) create

      - (Object) destroy

      - (Object) update

Instance Method Details

    - (<tt>Object</tt>) create

5
6
7
8
9
10
11
12
13
14
15
16
17

# File 'app/models/payment_profile_cim.rb', line 5

def create
  if super and create_payment_profile
    # user.payment_profile_id = self.id  #  add this line if the user has a default payment_profile
    # user.save
    return true
  else
    if self.id
      #destroy the instance if it was created
      self.destroy
    end
    return false
  end
end

    - (<tt>Object</tt>) destroy

26
27
28
29
30
31

# File 'app/models/payment_profile_cim.rb', line 26

def destroy
  if delete_payment_profile and super
    return true
  end
  return false
end

    - (<tt>Object</tt>) update

19
20
21
22
23
24

# File 'app/models/payment_profile_cim.rb', line 19

def update
  if super and update_payment_profile
    return true
  end
  return false
end

  Generated on Sun Jul 15 15:24:22 2012 by
  yard
  0.8.2.1 (ruby-1.9.3).


text:
<?php
/**
 * User: execut
 * Date: 21.07.16
 * Time: 13:47
 */

namespace execut\actions\action\adapter\viewRenderer;

use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use kartik\alert\Alert;
use yii\helpers\Url;
use \execut\actions\widgets\DetailView as DetailViewWidget;

class DetailView extends Widget
{
    public $uniqueId = null;
    public $model = null;
    public $mode = null;
    public $heading = 'Редактирование';
    public $action = null;
    public $buttonsTemplate = \execut\actions\widgets\DetailView::DEFAULT_BUTTONS_TEMPLATE;
    public $saveButton = DetailViewWidget::BUTTON_SAVE;
    public $checkButton = DetailViewWidget::BUTTON_CHECK;
    public $applyButton = DetailViewWidget::BUTTON_APPLY;
    public $cancelButton = DetailViewWidget::BUTTON_CANCEL;
    public function getDefaultWidgetOptions()
    {
        return [
            'class' => DetailViewWidget::class,
            'uniqueId' => $this->uniqueId,
            'model' => $this->model,
            'mode' => $this->mode,
            'action' => $this->action,
            'buttonsTemplate' => $this->buttonsTemplate,
            'saveButton' => $this->saveButton,
            'checkButton' => $this->checkButton,
            'applyButton' => $this->applyButton,
            'cancelButton' => $this->cancelButton,
        ];
    }
}