text:
package com.wegas.reviewing.ejb;

import com.wegas.core.Helper;
import com.wegas.core.api.ReviewingFacadeI;
import com.wegas.core.ejb.PlayerFacade;
import com.wegas.core.ejb.VariableDescriptorFacade;
import com.wegas.core.ejb.VariableInstanceFacade;
import com.wegas.core.ejb.WegasAbstractFacade;
import com.wegas.core.exception.client.WegasErrorMessage;
import com.wegas.core.exception.internal.WegasNoResultException;
import com.wegas.core.persistence.game.DebugTeam;
import com.wegas.core.persistence.game.Game;
import com.wegas.core.persistence.game.GameModel;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.persistence.game.Populatable;
import com.wegas.core.persistence.game.Team;
import com.wegas.core.persistence.variable.VariableDescriptor;
import com.wegas.core.persistence.variable.VariableInstance;
import com.wegas.core.persistence.variable.primitive.EnumItem;
import com.wegas.core.persistence.variable.primitive.StringInstance;
import com.wegas.core.persistence.variable.primitive.TextInstance;
import com.wegas.core.persistence.variable.scope.AbstractScope;
import com.wegas.core.persistence.variable.scope.GameModelScope;
import com.wegas.core.persistence.variable.scope.PlayerScope;
import com.wegas.core.persistence.variable.scope.TeamScope;
import com.wegas.core.security.util.WegasEntityPermission;
import com.wegas.core.security.util.WegasPermission;
import com.wegas.reviewing.persistence.PeerReviewDescriptor;
import com.wegas.reviewing.persistence.PeerReviewInstance;
import com.wegas.reviewing.persistence.Review;
import com.wegas.reviewing.persistence.evaluation.CategorizedEvaluationDescriptor;
import com.wegas.reviewing.persistence.evaluation.EvaluationDescriptor;
import com.wegas.reviewing.persistence.evaluation.EvaluationDescriptorContainer;
import com.wegas.reviewing.persistence.evaluation.EvaluationInstance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * PeerReview Inject Facade
 * <p>
 * Contains PeerReviewing logic
 *
 * @author Maxence Laurent (maxence.laurent at gmail.com)
 */
@Stateless
@LocalBean
public class ReviewingFacade extends WegasAbstractFacade implements ReviewingFacadeI {

    static final private Logger logger = LoggerFactory.getLogger(ReviewingFacade.class);
    private static final long serialVersionUID = 5140216834760973410L;

    /**
     * Default Constructor
     */
    public ReviewingFacade() {
        // useless but ensure there is an empty constructor
    }
    /**
     * Player Facade
     */
    @Inject
    private PlayerFacade playerFacade;
    /**
     * Variable Instance Facade
     */
    @Inject
    private VariableInstanceFacade variableInstanceFacade;
    /**
     * Variable Descriptor Facade
     */
    @Inject
    private VariableDescriptorFacade variableDescriptorFacade;

    /**
     * Get a Review by id
     *
     * @param entityId the reviewID
     *
     * @return the corresponding review or null
     */
    public Review findReview(final Long entityId) {
        return this.getEntityManager().find(Review.class, entityId);
    }

    /**
     * Get an evaluationInstance by Id
     *
     * @param evId evaluation instance id
     *
     * @return the evaluation instance or null
     */
    public EvaluationInstance findEvaluationInstance(Long evId) {
        return this.getEntityManager().find(EvaluationInstance.class, evId);
    }

    /**
     * Get an evaluationDescriptor by Id
     *
     * @param evId evaluation descriptor id
     *
     * @return the evaluation descriptor or null
     */
    public EvaluationDescriptor findEvaluationDescriptor(Long evId) {
        return this.getEntityManager().find(EvaluationDescriptor.class, evId);
    }

    public Collection<WegasPermission> getReviewReadPermission(Review aReview) {
        Query query = getEntityManager().createNamedQuery("Review.findOwners");
        query.setParameter(1, aReview.getId());
        List results = query.getResultList();

        Collection<WegasPermission> perms = new ArrayList<>();
        for (Object item : results) {
            Object[] tuple = (Object[]) item;
            String entityType = (String) tuple[0];
            Long entityId = (Long) tuple[1];

            perms.add(new WegasEntityPermission(entityId, WegasEntityPermission.Level.READ, WegasEntityPermission.EntityType.valueOf(entityType)));
        }

        return perms;
    }

    /**
     *
     * @param prd
     *
     * @return
     */
    private List<PeerReviewInstance> getInstances(PeerReviewDescriptor prd) {
        return new ArrayList(variableDescriptorFacade.getInstances(prd).values());
    }

    /**
     * Let a player submit his variable. It means the variable become ready to be reviewed
     *
     * @param prd the PeerReview Descriptor
     * @param p   the player submitting
     */
    @Override
    public void submit(PeerReviewDescriptor prd, Player p) {
        PeerReviewInstance instance = prd.getInstance(p);
        if (instance.getReviewState() == PeerReviewDescriptor.ReviewingState.NOT_STARTED || instance.getReviewState() == PeerReviewDescriptor.ReviewingState.SUBMITTED) {
            instance.setReviewState(PeerReviewDescriptor.ReviewingState.SUBMITTED);
        } else {
            throw WegasErrorMessage.error("Error: already submitted");
        }
    }

    /**
     * Let a player submit his variable. It means the variable become ready to be reviewed
     *
     * @param peerReviewDescriptorId the PeerReview Descriptor id
     * @param playerId               the player submitting
     */
    public void submit(Long peerReviewDescriptorId, Long playerId) {
        VariableDescriptor vd = variableDescriptorFacade.find(peerReviewDescriptorId);
        if (vd instanceof PeerReviewDescriptor) {
            submit((PeerReviewDescriptor) vd, playerFacade.find(playerId));
        } else {
            throw WegasErrorMessage.error("Submit failed: Descriptor is not instance of PeerReviewDescriptor");
        }
    }

    /**
     * Private method that initialise review instance when dispatching
     *
     * @param prd      the peer review descriptor
     * @param author   peer review instance corresponding to the author
     * @param reviewer peer review instance corresponding to the reviewer
     *
     * @return a brand new review, ready to be edited by the reviewer
     */
    private Review createReview(PeerReviewDescriptor prd, PeerReviewInstance author, PeerReviewInstance reviewer) {
        Review r = new Review();
        r.setReviewState(Review.ReviewState.DISPATCHED);

        reviewer.addToToReview(r);
        author.addToReviewed(r);

        //r.setAuthor(author);
        for (EvaluationDescriptor ed : prd.getFeedback().getEvaluations()) {
            EvaluationInstance ei = ed.createInstance();
            ei.setFeedbackReview(r);
            r.getFeedback().add(ei);
        }
        for (EvaluationDescriptor ed : prd.getFbComments().getEvaluations()) {
            EvaluationInstance ei = ed.createInstance();
            ei.setCommentsReview(r);
            r.getComments().add(ei);
        }
        this.getEntityManager().persist(r);
        return r;
    }

    /**
     * Called by the teacher, it will take each PeerReviewInstance matching the given peer review
     * descriptor and dispatch them (who review who?)
     *
     * @param prd peer review descriptor to dispatch
     *
     * @return all peerreviewinstance which have been modified
     */
    public List<PeerReviewInstance> dispatch(PeerReviewDescriptor prd) {
        AbstractScope scope = prd.getScope();
        //Collection<VariableInstance> values = scope.getVariableInstances().values(); // TODO
        List<PeerReviewInstance> pris = new ArrayList<>();
        List<PeerReviewInstance> touched = new ArrayList<>();
        List<PeerReviewInstance> evicted = new ArrayList<>();

        if (scope instanceof GameModelScope) {
            throw WegasErrorMessage.error("Invalid Scope for PeerReview descriptor. GameModelScope does not make any sense for this kind of data");
        }

        int numberOfReview;

        if (!prd.getGameModel().isPlay()) {
            // Not a real game
            // Edit Scenario Case -> there is only one game (debug) and one player (TestPlayer)
            // In this case, allow the player to review itself once
            numberOfReview = 2;
            Player testPlayer = prd.getGameModel().getGames().get(0).getTeams().get(0).getPlayers().get(0);
            pris.add(prd.getInstance(testPlayer));
        } else {
            /*
             * Real Game: evict test or "ghost" instance(s)
             *
             * In case peerreview variable is game/gameModel scoped, there will be only one instance
             * for the whole game and such an instance will be evicted.... For the time, it sounds
             * like OK since such a review seems useless
             */
            for (Game game : prd.getGameModel().getGames()) {
                for (Team team : game.getTeams()) {
                    if (team.getStatus() == Populatable.Status.LIVE) {
                        if (scope instanceof TeamScope) {
                            // 1 instance per team: evict empty team instances
                            TeamScope tScope = (TeamScope) scope;
                            PeerReviewInstance instance = (PeerReviewInstance) variableInstanceFacade.getTeamInstance(tScope, team);

                            if (team.getAnyLivePlayer() == null || team instanceof DebugTeam) {
                                // if team is a debug team or the team does not contain any LIVE
                                // player, discard this instance
                                instance.setReviewState(PeerReviewDescriptor.ReviewingState.DISCARDED);
                                variableInstanceFacade.merge(instance);
                                touched.add(instance);
                            } else {
                                pris.add(instance);
                            }
                        } else { // PlayerScoped
                            // 1 instance per player: evict test player instance
                            for (Player p : team.getPlayers()) {
                                if (p.getStatus() == Populatable.Status.LIVE) {
                                    PeerReviewInstance instance = (PeerReviewInstance) variableInstanceFacade.getPlayerInstance((PlayerScope) scope, p);
                                    if (team instanceof DebugTeam) {
                                        // Discared instance
                                        instance.setReviewState(PeerReviewDescriptor.ReviewingState.DISCARDED);
                                        variableInstanceFacade.merge(instance);
                                        touched.add(instance);
                                    } else {
                                        pris.add(instance);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            VariableDescriptor toReview = prd.getToReview();
            for (Iterator<PeerReviewInstance> it = pris.iterator(); it.hasNext();) {
                PeerReviewInstance pri = it.next();
                VariableInstance toReviewInstance = toReview.findInstance(pri, null);
                if (toReviewInstance != null) {

                    boolean reject = false;

                    if (pri.getReviewState() == PeerReviewDescriptor.ReviewingState.COMPLETED
                        || pri.getReviewState() == PeerReviewDescriptor.ReviewingState.DISPATCHED
                        || pri.getReviewState() == PeerReviewDescriptor.ReviewingState.NOTIFIED) {
                        // Only accept NOT_STARTED and SUBMITTING states
                        reject = true;
                    } else if (toReviewInstance instanceof TextInstance) {
                        TextInstance primitive = (TextInstance) toReviewInstance;
                        String primitiveValue = primitive.getValue(),
                            defaultValue = ((TextInstance) primitive.getDescriptor().getDefaultInstance()).getValue();
                        reject = Helper.isNullOrEmpty(primitiveValue) || primitiveValue.equals(defaultValue);
                    } else if (toReviewInstance instanceof StringInstance) {
                        StringInstance primitive = (StringInstance) toReviewInstance;
                        String primitiveValue = primitive.getValue(),
                            defaultValue = ((StringInstance) primitive.getDescriptor().getDefaultInstance()).getValue();
                        reject = Helper.isNullOrEmpty(primitiveValue) || primitiveValue.equals(defaultValue);
                    }

                    if (reject) {
                        pri.setReviewState(PeerReviewDescriptor.ReviewingState.EVICTED);
                        variableInstanceFacade.merge(pri);
                        touched.add(pri);
                        evicted.add(pri);
                        it.remove();
                    }
                }
            }
            numberOfReview = Math.min(prd.getMaxNumberOfReview(), pris.size() - 1);
            if (numberOfReview < 1) {
                throw WegasErrorMessage.error("Unable to dispatch reviews: there is not enough players");
            }
        }

        Collections.shuffle(pris);

        int i, j;
        for (i = 0; i < pris.size(); i++) {
            PeerReviewInstance author = pris.get(i);

            if (author.getReviewState() == PeerReviewDescriptor.ReviewingState.SUBMITTED
                || author.getReviewState() == PeerReviewDescriptor.ReviewingState.NOT_STARTED) {
                logger.warn("Dispatch Author");
                //List<Review> reviewed = author.getReviewed();
                for (j = 1; j <= numberOfReview; j++) {
                    PeerReviewInstance reviewer = pris.get((i + j) % pris.size());

                    createReview(prd, author, reviewer);
                    //reviewed.add(r);
                    //reviewer.getToReview().add(r);
                    variableInstanceFacade.merge(reviewer);
                }
                author.setReviewState(PeerReviewDescriptor.ReviewingState.DISPATCHED);
                variableInstanceFacade.merge(author);
                touched.add(author);
            }
        }

        if (prd.getIncludeEvicted()) {
            // Give some work even to users who didn't do their job
            for (PeerReviewInstance reviewer : evicted) {
                for (j = 0; j < numberOfReview; j++) {
                    // NOTE : such an author will have some extra feedback !
                    PeerReviewInstance author = pris.get(j % pris.size());
                    createReview(prd, author, reviewer);
                }
            }
        }

        /* for (PeerReviewInstance pri : pris) { variableInstanceFacade.merge(pri); em.flush();
        } */
        return touched;
    }

    /**
     * Called by the teacher, it will take each PeerReviewInstance matching the given peer review
     * descriptor and dispatch them (who review who?)
     *
     * @param peerReviewDescriptorId peer review descriptor id to dispatch
     */
    public List<PeerReviewInstance> dispatch(Long peerReviewDescriptorId) {
        VariableDescriptor vd = variableDescriptorFacade.find(peerReviewDescriptorId);
        if (vd instanceof PeerReviewDescriptor) {
            return dispatch((PeerReviewDescriptor) vd);
        } else {
            throw WegasErrorMessage.error("Submit failed: Descriptor is not instance of PeerReviewDescriptor");
        }
    }

    /**
     * @deprecated @param evalInstance
     * @param other
     */
    public void mergeEval(EvaluationInstance evalInstance, EvaluationInstance other) {
        evalInstance.merge(other);
    }

    /**
     * Save (update) evaluations in given list
     *
     * @param evs evaluations to update
     */
    public void mergeEvaluations(List<EvaluationInstance> evs) {
        for (EvaluationInstance other : evs) {
            EvaluationInstance ev = this.findEvaluationInstance(other.getId());
            ev.merge(other);
        }
    }

    /**
     * Retrieve the PeerReviewInstance containing given Review that belongs to the currentPlayer
     *
     * @param review
     *
     * @return peer review instance that belong to the current player
     */
    public PeerReviewInstance getPeerReviewInstanceFromReview(Review review, Player player) {
        PeerReviewInstance author = review.getAuthor();

        //PeerReviewDescriptor desc = (PeerReviewDescriptor) descriptorFacade.find(author.getDescriptor().getId());
        PeerReviewInstance instance = (PeerReviewInstance) author.getDescriptor().getInstance(player);
        return instance;
    }

    /**
     * Save a review posted by a player
     *
     * @param pri   peer review instance containing the review
     * @param other the review to merge within pri
     *
     * @return up to date review
     */
    public Review saveReview(PeerReviewInstance pri, Review other) {
        Review review = this.findReview(other.getId());
        PeerReviewInstance author = review.getAuthor();
        PeerReviewInstance reviewer = review.getReviewer();

        /*
         * if author is posting and only if review state is notified: update comments only
         */
        if (pri == author && review.getReviewState() == Review.ReviewState.NOTIFIED) {
            mergeEvaluations(other.getComments());
        }

        /*
         * if reviewer is posting and only if review state is dispatched: update evaluation
         */
        if (pri == reviewer && review.getReviewState() == Review.ReviewState.DISPATCHED) {
            mergeEvaluations(other.getFeedback());
        }

        this.getEntityManager().merge(review);
        return review;
    }

    /**
     * Submitting a review occurs twice in the whole process First time when the reviewer post his
     * review. In this case, the review switch from DISPATCHED to REVIEWED. The second time is when
     * the author post his comments, switch from NOTIFIED to COMPLETED
     *
     * @param review the review to submit
     * @param player
     *
     * @return review
     */
    public Review submitReview(Review review, Player player) {
        Review r = this.findReview(review.getId());
        PeerReviewInstance pri = this.getPeerReviewInstanceFromReview(r, player);
        r = this.saveReview(pri, review);
        if (r.getReviewState() == Review.ReviewState.DISPATCHED) {
            r.setReviewState(Review.ReviewState.REVIEWED);
            //em.merge(r);
        } else if (r.getReviewState() == Review.ReviewState.NOTIFIED) {
            r.setReviewState(Review.ReviewState.COMPLETED);
            //em.merge(r);
        }
        return r;
    }

    /**
     * {@link #submitReview(com.wegas.reviewing.persistence.Review) } a review by id
     *
     * @param reviewId
     *
     * @return the submitted review
     */
    public Review submitReview(Long reviewId, Player player) {
        return this.submitReview(this.getEntityManager().find(Review.class, reviewId), player);
    }

    /**
     * Reviewing phase is over -> authors will be able to see feedbacks
     *
     * @param prd the PeerReviewDescriptor
     *
     * @return
     */
    public List<PeerReviewInstance> notify(PeerReviewDescriptor prd) {
        List<PeerReviewInstance> pris = this.getInstances(prd);
        List<PeerReviewInstance> touched = new ArrayList<>();
        for (PeerReviewInstance pri : pris) {
            if (pri.getReviewState() != PeerReviewDescriptor.ReviewingState.DISCARDED && pri.getReviewState() != PeerReviewDescriptor.ReviewingState.EVICTED) {

                if (pri.getReviewState() == PeerReviewDescriptor.ReviewingState.DISPATCHED) {
                    for (Review review : pri.getReviewed()) {
                        if (review.getReviewState() == Review.ReviewState.DISPATCHED || review.getReviewState() == Review.ReviewState.REVIEWED) {
                            review.setReviewState(Review.ReviewState.NOTIFIED);
                        }
                    }
                    pri.setReviewState(PeerReviewDescriptor.ReviewingState.NOTIFIED);
                } else {
                    pri.setReviewState(PeerReviewDescriptor.ReviewingState.EVICTED);
                }
                touched.add(pri);
                variableInstanceFacade.merge(pri);
                //requestManager.addUpdatedInstance(pri);
            }
        }
        return touched;
    }

    /**
     * Reviewing phase is over -> authors will be able to see feedbacks
     *
     * @param peerReviewDescriptorId
     */
    public List<PeerReviewInstance> notify(Long peerReviewDescriptorId) {
        VariableDescriptor vd = variableDescriptorFacade.find(peerReviewDescriptorId);
        if (vd instanceof PeerReviewDescriptor) {
            return notify((PeerReviewDescriptor) vd);
        } else {
            throw WegasErrorMessage.error("Notify failed: Descriptor is not instance of PeerReviewDescriptor");
        }
    }

    /**
     * The Reviewing will be completely finished after closing
     *
     * @param prd
     *
     * @return all peerReviewInstance that have been closed
     */
    public List<PeerReviewInstance> close(PeerReviewDescriptor prd) {
        List<PeerReviewInstance> pris = this.getInstances(prd);
        List<PeerReviewInstance> touched = new ArrayList<>();
        for (PeerReviewInstance pri : pris) {
            if (pri.getReviewState() != PeerReviewDescriptor.ReviewingState.DISCARDED && pri.getReviewState() != PeerReviewDescriptor.ReviewingState.EVICTED) {
                if (pri.getReviewState() == PeerReviewDescriptor.ReviewingState.NOTIFIED) {
                    for (Review review : pri.getReviewed()) {
                        if (review.getReviewState() == Review.ReviewState.NOTIFIED
                            || review.getReviewState() == Review.ReviewState.COMPLETED) {
                            review.setReviewState(Review.ReviewState.CLOSED);
                        }
                    }
                    pri.setReviewState(PeerReviewDescriptor.ReviewingState.COMPLETED);
                } else {
                    pri.setReviewState(PeerReviewDescriptor.ReviewingState.EVICTED);
                }
                touched.add(pri);
                variableInstanceFacade.merge(pri);
            }
            //requestManager.addUpdatedInstance(pri);
        }
        return touched;
    }

    /**
     * Reviewing phase is over. Author will be able to see feedbacks
     *
     * @param peerReviewDescriptorId
     *
     * @return all PeerReviewInstance which have been closed
     */
    public List<PeerReviewInstance> close(Long peerReviewDescriptorId) {
        VariableDescriptor vd = variableDescriptorFacade.find(peerReviewDescriptorId);
        if (vd instanceof PeerReviewDescriptor) {
            return close((PeerReviewDescriptor) vd);
        } else {
            throw WegasErrorMessage.error("Close failed: Descriptor is not instance of PeerReviewDescriptor");
        }
    }

    /**
     * Since PeerReviewDescriptor toReview variable is only referenced by its own private name on
     * the JSON side, we have to resolve those name to effective VariableDescriptor
     * <p>
     * Moreover, as the variable may not yet exists (especially when posting a whole GameModel) when
     * the PeerReviewDescriptor is created, we'll have to wait to resolve such identifier.
     * <p>
     * This is done by listening to EntityRevivedEvent
     *
     * @param reviewD
     */
    public void revivePeerReviewDescriptor(PeerReviewDescriptor reviewD) {
        try {
            String toReviewName = reviewD.getImportedToReviewName();
            if (toReviewName != null) {
                GameModel gameModel = reviewD.getGameModel();
                VariableDescriptor toReview = variableDescriptorFacade.find(gameModel, toReviewName);
                reviewD.setToReview(toReview);
            }

            assertScopesAreValid(reviewD);

            this.reviveEvaluations(reviewD.getFeedback(), reviewD);
            this.reviveEvaluations(reviewD.getFbComments(), reviewD);
        } catch (WegasNoResultException ex) {
            logger.error("Failed te revive ReviewDescriptor", ex);
            reviewD.setToReview(null);
        }
    }

    private void reviveEvaluations(EvaluationDescriptorContainer container, PeerReviewDescriptor parent) {
        for (EvaluationDescriptor ed : container.getEvaluations()) {
            if (ed.getLabel() != null) {
                ed.getLabel().setParentDescriptor(parent);
            }
            if (ed.getDescription() != null) {
                ed.getDescription().setParentDescriptor(parent);
                if (ed instanceof CategorizedEvaluationDescriptor) {
                    CategorizedEvaluationDescriptor ced = (CategorizedEvaluationDescriptor) ed;
                    for (EnumItem category : ced.getCategories()) {
                        if (category.getLabel() != null) {
                            category.getLabel().setParentDescriptor(parent);
                        }
                    }
                }
            }
        }
    }

    public void revivePeerReviewInstance(PeerReviewInstance reviewI) {
        this.assertScopesAreValid((PeerReviewDescriptor) reviewI.findDescriptor());
    }

    private void assertScopesAreValid(PeerReviewDescriptor prd) {

        VariableDescriptor toReview = prd.getToReview();

        AbstractScope rScope = prd.getScope();
        AbstractScope vScope = toReview.getScope();
        if (rScope instanceof GameModelScope) {
            throw WegasErrorMessage.error("GameModel/Game Scope is forbidden for " + prd);
        }
        if (rScope instanceof TeamScope && vScope instanceof PlayerScope) {
            throw WegasErrorMessage.error("Reviewed variable " + toReview + " scope is too scpecific");
        }
    }
}


text:
if(!dojo._hasResource["dojox.dtl.contrib.objects"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.dtl.contrib.objects"] = true;
dojo.provide("dojox.dtl.contrib.objects");

dojo.mixin(dojox.dtl.contrib.objects, {
	key: function(value, arg){
		return value[arg];
	}
});

dojox.dtl.register.filters("dojox.dtl.contrib", {
	"objects": ["key"]
});

}

redpajama_set_name: RedPajamaGithub


text:
module Asposediagramjava
  module ExportToPdf
    def initialize()
        data_dir = File.dirname(File.dirname(File.dirname(File.dirname(__FILE__)))) + '/data/'

        # Call the diagram constructor to load diagram from a VSD file
        diagram = Rjb::import('com.aspose.diagram.Diagram').new(data_dir + "Drawing.vsd")

        # Save as PDF file format
        diagram.save(data_dir + "Diagram.pdf", Rjb::import('com.aspose.diagram.SaveFileFormat').PDF)

        puts "Exported visio diagram to pdf."
    end
  end
end


text: superstatic.html


text:
package org.protempa.backend.dsb.relationaldb;

import java.util.List;
import org.arp.javautil.string.StringUtil;
import org.protempa.backend.dsb.relationaldb.mappings.Mappings;

/**
 *
 * @author Andrew Post
 */
public final class IntColumnSpecWrapper implements IColumnSpec {
    private final ColumnSpec columnSpec;
    private ColumnSpec isSameAs;

    public IntColumnSpecWrapper(ColumnSpec columnSpec) {
        this.columnSpec = columnSpec;
    }

    @Override
    public String getColumn() {
        return this.columnSpec.getColumn();
    }

    @Override
    public ColumnOp getColumnOp() {
        return this.columnSpec.getColumnOp();
    }

    @Override
    public Operator getConstraint() {
        return this.columnSpec.getConstraint();
    }

    @Override
    public JoinSpec getJoin() {
        return this.columnSpec.getJoin();
    }

    @Override
    public Mappings getMappings() {
        return this.columnSpec.getMappings();
    }

    @Override
    public String getSchema() {
        return this.columnSpec.getSchema();
    }

    @Override
    public String getTable() {
        return this.columnSpec.getTable();
    }

    @Override
    public boolean isPropositionIdsComplete() {
        return this.columnSpec.isPropositionIdsComplete();
    }

    public void setIsSameAs(ColumnSpec columnSpec) {
        this.isSameAs = columnSpec;
    }

    public ColumnSpec getIsSameAs() {
        return this.isSameAs;
    }

    ColumnSpec getColumnSpec() {
        return this.columnSpec;
    }

    /**
     * Returns whether the given column specification has the same schema and
     * table as this one.
     *
     * @param columnSpec
     *            a {@link ColumnSpec}.
     * @return true if the given column specification has the same
     *         schema and table as this one, false if not.
     */
    boolean isSameSchemaAndTable(IntColumnSpecWrapper columnSpec) {
        return StringUtil.equals(columnSpec.getSchema(), getSchema())
                && StringUtil.equals(columnSpec.getTable(), getTable());
    }

    /**
     * Returns whether the given column specification has the same schema and
     * table as this one.
     *
     * @param tableSpec
     *            a {@link TableSpec}.
     * @return true if the given table specification has the same
     *         schema and table as this one, false if not.
     */
    boolean isSameSchemaAndTable(TableSpec tableSpec) {
        return StringUtil.equals(tableSpec.getSchema(), getSchema())
                && StringUtil.equals(tableSpec.getTable(), getTable());
    }

    List<ColumnSpec> asList() {
        return this.columnSpec.asList();
    }

}


text:
[![Latest Version](https://img.shields.io/github/release/boekkooi/tactician-amqp.svg?style=flat-square)](https://github.com/boekkooi/tactician-amqp/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Build Status](https://img.shields.io/travis/boekkooi/tactician-amqp/master.svg?style=flat-square)](https://travis-ci.org/boekkooi/tactician-amqp)
[![Total Downloads](https://img.shields.io/packagist/dt/boekkooi/tactician-amqp.svg?style=flat-square)](https://packagist.org/packages/boekkooi/tactician-amqp)
[![Reference Status](https://www.versioneye.com/php/boekkooi:tactician-amqp/reference_badge.svg?style=flat)](https://www.versioneye.com/php/boekkooi:tactician-amqp/references)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/437a6de0-d13a-4426-8f3c-284e472946d7/mini.png)](https://insight.sensiolabs.com/projects/437a6de0-d13a-4426-8f3c-284e472946d7)

**AMQP command bus plugin for [Tactician](http://tactician.thephpleague.com) using [php-amqp](https://github.com/pdezwart/php-amqp).**

## Install

Via Composer

``` bash
$ composer require boekkooi/tactician-amqp
```

## License

The MIT License (MIT). Please see [License File](LICENSE) for more information.


text:
#ifndef GrDrawableOp_DEFINED
#define GrDrawableOp_DEFINED

#include "src/gpu/ops/GrOp.h"

#include "include/core/SkDrawable.h"
#include "include/core/SkMatrix.h"
#include "src/gpu/GrSemaphore.h"

class GrRecordingContext;

class GrDrawableOp final : public GrOp {
public:
    DEFINE_OP_CLASS_ID

    static std::unique_ptr<GrDrawableOp> Make(GrRecordingContext*,
                                              std::unique_ptr<SkDrawable::GpuDrawHandler> drawable,
                                              const SkRect& bounds);

    const char* name() const override { return "Drawable"; }

#ifdef SK_DEBUG
    SkString dumpInfo() const override {
        return INHERITED::dumpInfo();
    }
#endif

private:
    friend class GrOpMemoryPool; // for ctor

    GrDrawableOp(std::unique_ptr<SkDrawable::GpuDrawHandler>, const SkRect& bounds);

    CombineResult onCombineIfPossible(GrOp* that, GrRecordingContext::Arenas*,
                                      const GrCaps& caps) override {
        return CombineResult::kCannotCombine;
    }
    void onPrepare(GrOpFlushState*) override {}

    void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;

    std::unique_ptr<SkDrawable::GpuDrawHandler> fDrawable;

    typedef GrOp INHERITED;
};

#endif


text:
package gappsockets.server.requesthandler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface RequestHandler {

	void handle(final HttpServletRequest request, final HttpServletResponse response)
			throws ServletException, IOException;

}


text:
import os
import sys

from automation.utilities.display import display, output
from automation.utilities.path import get_repo_root, get_test_results_dir
from automation.tests.nose_helper import get_nose_runner

def run_tests(modules, parallel, run_live, tests):

    if not modules and not tests:
        display('No tests set to run.')
        sys.exit(0)

    display("""
=============
  Run Tests
=============
""")
    if modules:
        display('Modules: {}'.format(', '.join(name for name, _, _ in modules)))

    # set environment variable
    if run_live:
        os.environ['AZURE_TEST_RUN_LIVE'] = 'True'

    test_paths = tests or [p for _, _, p in modules]

    display('Drive test by nosetests')
    runner = get_nose_runner(parallel=parallel, process_timeout=3600 if run_live else 600)
    results = runner([path for path in test_paths])
    return results, []

def collect_test():
    from importlib import import_module

    paths = import_module('azure.cli').__path__
    result = []
    collect_tests(paths, result, 'azure.cli')
    return result

def collect_tests(path, return_collection, prefix=''):
    from unittest import TestLoader
    from importlib import import_module
    from pkgutil import iter_modules

    loader = TestLoader()
    for _, name, is_pkg in iter_modules(path):
        full_name = '{}.{}'.format(prefix, name)
        module_path = os.path.join(path[0], name)

        if is_pkg:
            collect_tests([module_path], return_collection, full_name)

        if not is_pkg and name.startswith('test'):
            test_module = import_module(full_name)
            for suite in loader.loadTestsFromModule(test_module):
                for test in suite._tests:  # pylint: disable=protected-access
                    return_collection.append(
                        '{}.{}.{}'.format(full_name, test.__class__.__name__, test._testMethodName))  # pylint: disable=protected-access

def summarize_tests(test_output):
    display(test_output)
    failed_tests = []
    for line in test_output.splitlines():
        if '... ERROR' in line or '... FAIL' in line:
            line = line.replace('(', '')
            line = line.replace(')', '')
            try:
                test_name, _, _, _ = line.split(' ')
                line = test_name
            except:
                pass
            failed_tests.append(line)

    if failed_tests:
        display("""
==========
  FAILED
==========
""")
        for failed_test in failed_tests:
            display(failed_test)
    return failed_tests


text:
/*
 * The Plaid API
 *
 * The Plaid REST API. Please see https://plaid.com/docs/api for more details.
 *
 * API version: 2020-09-14_1.205.3
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package plaid

import (
	"encoding/json"
)

// Employee Data about the employee.
type Employee struct {
	Address PaystubAddress `json:"address"`
	// The name of the employee.
	Name NullableString `json:"name"`
	// Marital status of the employee - either `single` or `married`.
	MaritalStatus NullableString `json:"marital_status,omitempty"`
	TaxpayerId *TaxpayerID `json:"taxpayer_id,omitempty"`
	AdditionalProperties map[string]interface{}
}

type _Employee Employee

// NewEmployee instantiates a new Employee object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewEmployee(address PaystubAddress, name NullableString) *Employee {
	this := Employee{}
	this.Address = address
	this.Name = name
	return &this
}

// NewEmployeeWithDefaults instantiates a new Employee object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewEmployeeWithDefaults() *Employee {
	this := Employee{}
	return &this
}

// GetAddress returns the Address field value
func (o *Employee) GetAddress() PaystubAddress {
	if o == nil {
		var ret PaystubAddress
		return ret
	}

	return o.Address
}

// GetAddressOk returns a tuple with the Address field value
// and a boolean to check if the value has been set.
func (o *Employee) GetAddressOk() (*PaystubAddress, bool) {
	if o == nil  {
		return nil, false
	}
	return &o.Address, true
}

// SetAddress sets field value
func (o *Employee) SetAddress(v PaystubAddress) {
	o.Address = v
}

// GetName returns the Name field value
// If the value is explicit nil, the zero value for string will be returned
func (o *Employee) GetName() string {
	if o == nil || o.Name.Get() == nil {
		var ret string
		return ret
	}

	return *o.Name.Get()
}

// GetNameOk returns a tuple with the Name field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *Employee) GetNameOk() (*string, bool) {
	if o == nil  {
		return nil, false
	}
	return o.Name.Get(), o.Name.IsSet()
}

// SetName sets field value
func (o *Employee) SetName(v string) {
	o.Name.Set(&v)
}

// GetMaritalStatus returns the MaritalStatus field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *Employee) GetMaritalStatus() string {
	if o == nil || o.MaritalStatus.Get() == nil {
		var ret string
		return ret
	}
	return *o.MaritalStatus.Get()
}

// GetMaritalStatusOk returns a tuple with the MaritalStatus field value if set, nil otherwise
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *Employee) GetMaritalStatusOk() (*string, bool) {
	if o == nil  {
		return nil, false
	}
	return o.MaritalStatus.Get(), o.MaritalStatus.IsSet()
}

// HasMaritalStatus returns a boolean if a field has been set.
func (o *Employee) HasMaritalStatus() bool {
	if o != nil && o.MaritalStatus.IsSet() {
		return true
	}

	return false
}

// SetMaritalStatus gets a reference to the given NullableString and assigns it to the MaritalStatus field.
func (o *Employee) SetMaritalStatus(v string) {
	o.MaritalStatus.Set(&v)
}
// SetMaritalStatusNil sets the value for MaritalStatus to be an explicit nil
func (o *Employee) SetMaritalStatusNil() {
	o.MaritalStatus.Set(nil)
}

// UnsetMaritalStatus ensures that no value is present for MaritalStatus, not even an explicit nil
func (o *Employee) UnsetMaritalStatus() {
	o.MaritalStatus.Unset()
}

// GetTaxpayerId returns the TaxpayerId field value if set, zero value otherwise.
func (o *Employee) GetTaxpayerId() TaxpayerID {
	if o == nil || o.TaxpayerId == nil {
		var ret TaxpayerID
		return ret
	}
	return *o.TaxpayerId
}

// GetTaxpayerIdOk returns a tuple with the TaxpayerId field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *Employee) GetTaxpayerIdOk() (*TaxpayerID, bool) {
	if o == nil || o.TaxpayerId == nil {
		return nil, false
	}
	return o.TaxpayerId, true
}

// HasTaxpayerId returns a boolean if a field has been set.
func (o *Employee) HasTaxpayerId() bool {
	if o != nil && o.TaxpayerId != nil {
		return true
	}

	return false
}

// SetTaxpayerId gets a reference to the given TaxpayerID and assigns it to the TaxpayerId field.
func (o *Employee) SetTaxpayerId(v TaxpayerID) {
	o.TaxpayerId = &v
}

func (o Employee) MarshalJSON() ([]byte, error) {
	toSerialize := map[string]interface{}{}
	if true {
		toSerialize["address"] = o.Address
	}
	if true {
		toSerialize["name"] = o.Name.Get()
	}
	if o.MaritalStatus.IsSet() {
		toSerialize["marital_status"] = o.MaritalStatus.Get()
	}
	if o.TaxpayerId != nil {
		toSerialize["taxpayer_id"] = o.TaxpayerId
	}

	for key, value := range o.AdditionalProperties {
		toSerialize[key] = value
	}

	return json.Marshal(toSerialize)
}

func (o *Employee) UnmarshalJSON(bytes []byte) (err error) {
	varEmployee := _Employee{}

	if err = json.Unmarshal(bytes, &varEmployee); err == nil {
		*o = Employee(varEmployee)
	} else {
		return err
	}

	additionalProperties := make(map[string]interface{})

	if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
		delete(additionalProperties, "address")
		delete(additionalProperties, "name")
		delete(additionalProperties, "marital_status")
		delete(additionalProperties, "taxpayer_id")
		o.AdditionalProperties = additionalProperties
	}

	return err
}

type NullableEmployee struct {
	value *Employee
	isSet bool
}

func (v NullableEmployee) Get() *Employee {
	return v.value
}

func (v *NullableEmployee) Set(val *Employee) {
	v.value = val
	v.isSet = true
}

func (v NullableEmployee) IsSet() bool {
	return v.isSet
}

func (v *NullableEmployee) Unset() {
	v.value = nil
	v.isSet = false
}

func NewNullableEmployee(val *Employee) *NullableEmployee {
	return &NullableEmployee{value: val, isSet: true}
}

func (v NullableEmployee) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.value)
}

func (v *NullableEmployee) UnmarshalJSON(src []byte) error {
	v.isSet = true
	return json.Unmarshal(src, &v.value)
}


text:
import Bacon from 'baconjs';
import counter from './counter/count';

export default function stateProvider(initial){
    const countProperty = counter.counterToProperty(initial);
    return Bacon.combineTemplate({count:countProperty});
}


text:
/**
* Authentication
* @namespace brew_journal.authentication.services
*/
// NOTE: 66% certain the anonymous function call is to setup the 'use strict'
(function () {
  'use strict';

  angular
    .module('brew_journal.authentication.services')
    .factory('Authentication', Authentication);

  Authentication.$inject = ['$rootScope', '$cookies', '$http', '$location'];

  /**
  * @namespace Authentication
  * @returns {Factory}
  */
  function Authentication($rootScope, $cookies, $http, $location) {
    /**
    * @name Authentication
    * @desc The Factor to be returned
    */
    var Authentication = {
      login:                   login,
      logout:                  logout,
      register:                register,
      getAuthenticatedAccount: getAuthenticatedAccount,
      isAuthenticated:         isAuthenticated,
      setAuthenticatedAccount: setAuthenticatedAccount,
      unauthenticate:          unauthenticate,
      getRegistrationResult:   getRegistrationResult,
      checkAuthentication:     checkAuthentication
    };

    return Authentication;

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

    function broadcastAuthenticationUpdate() {
      $rootScope.$broadcast('authentication:change', isAuthenticated());
    }

    var registrationResult = {};

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

    /**
    * @name register
    * @desc Try to register a new user
    * @param {string} username The username entered by the user
    * @param {string} password The password entered by the user
    * @param {string} confirm_password Password confirmation. There is backend validation so needed
    * @param {string} email The email entered by the user
    * @param {string} first_name Registering user's first name
    * @param {string} last_name Registering user's last name
    * @returns {Promise}
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function register(username, password, confirm_password, email, first_name, last_name) {
      return $http.post('/api/v1/account/', {
        username:         username,
        password:         password,
        confirm_password: confirm_password,
        email:            email,
        first_name:       first_name,
        last_name:        last_name
      }).then(registerSuccessFn,registerFailureFn);
    }

    /**
    * @name registerSuccessFn
    * @desc Upon a successful registration, login a user.
    */
    function registerSuccessFn(data, status, headers, config) {
      setRegistrationResult(data);

      // Check to see if a user is already loggedin. If so, then an admin is adding users so don't try to log the
      // new user in.
      if(!isAuthenticated()) {
        Authentication.login(data.data.username, data.data.password);
      }
    }

    /**
    * @name registerFailureFn
    * @desc Warn a user as to why a registration failed
    */
    function registerFailureFn(data, status, headers, config) {
      setRegistrationResult(data);
    }

    /**
    * @name setRegistarationResult
    * @desc set the value of the Registration result
    */
    function setRegistrationResult(data) {
      registrationResult = data;
    }

    /**
     * @name getRegistrationResult
     * @desc Return the results of a registration action
     * @returns {Object}
     * @memberOf brew_journal.authentication.services.Authentication
    */
    function getRegistrationResult() {
      return registrationResult;
    }

    /**
    * @name login
    * @desc Try to log in with username `username` and password `password`
    * @param {string} username The username entered by the user
    * @param {string} password The password entered by the user
    * @returns {Promise}
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function login(username, password) {
      return $http.post('/api/v1/auth/login/', {
        username: username, password: password
      }).then(loginSuccessFn, loginErrorFn);
    }

    /**
    * @name loginSuccessFn
    * @desc Set the authenticated account and redirect to index
    */
    function loginSuccessFn(data, status, headers, config) {
      Authentication.setAuthenticatedAccount(data.data);

      // Adding a check that all spoofed HTTP requests will return. This is to avoid accidentially
      // redirecting during a unit test, which throws everything off and could end up in a nasty
      // redirect loop.
      if(!data.data.isUnitTest)
      {
        $location.url('/view/login');
      }
    }

    /**
    * @name loginErrorFn
    * @desc Log "Epic failure!" to the console
    * @todo Evaluate the necessity of this function
    */
    function loginErrorFn(data, status, headers, config) {
      console.log(data);
    }

    /**
    * @name logout
    * @desc Log the user out
    * @returns {Promise}
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function logout() {
      return $http.post('/api/v1/auth/logout/')
        .then(logoutSuccessFn, logoutErrorFn);
    }

    /**
    * @name logoutSuccessFn
    * @desc Unathentication the user and redirect to login
    */
    function logoutSuccessFn(data, status, headers, config) {
      Authentication.unauthenticate();

      // Adding a check that all spoofed HTTP requests will return. This is to avoid accidentially
      // redirecting during a unit test, which throws everything off and could end up in a nasty
      // redirect loop.
      if(!data.data.isUnitTest)
      {
        $location.url('/view/login');
      }
    }

    /**
    * @name logoutErrorFn
    * @desc Log why the user could not logout
    */
    function logoutErrorFn(data, status, headers, config) {
      console.error(data);
    }

    /**
    * @name getAuthenticatedAccount
    * @desc Return the currently authenticated account
    * @returns {object|undefined} Account if authenticated, else `undefined`
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function getAuthenticatedAccount() {
      if (!$cookies.authenticatedAccount) {
        return;
      }

      return JSON.parse($cookies.authenticatedAccount);
    }

    /**
    * @name isAuthenticated
    * @desc Check if the current user is authenticated
    * @returns {boolean} True is user is authenticated, else false.
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function isAuthenticated() {
      return !!$cookies.authenticatedAccount;
    }

    /**
    * @name checkAuthentication
    * @desc Authentication check specialized for the router. Will throw an exception when the user is not authenticated.
    * @returns {None}
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function checkAuthentication() {
      if(!this.isAuthenticated()) {
        throw new Error("Unathorized access attempted. Please login.");
      } else {
        return true;
      }
    }

    /**
    * @name setAuthenticatedAccount
    * @desc Stringify the account object and store it in a cookie
    * @param {Object} user The account object to be stored
    * @returns {undefined}
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function setAuthenticatedAccount(account) {
      $cookies.authenticatedAccount = JSON.stringify(account);
      broadcastAuthenticationUpdate();
    }

    /**
    * @name unauthenticate
    * @desc Delete the cookie where the user object is stored
    * @returns {undefined}
    * @memberOf brew_journal.authentication.services.Authentication
    */
    function unauthenticate() {
      delete $cookies.authenticatedAccount;
      broadcastAuthenticationUpdate();
    }
  }
})();


text:
<?php
	error_reporting(-1);
	ini_set( 'display_errors', 1 );

	// Creación de la BD
	include("./src/php/bd.php");	// Comentar una vez creada

	// Inicio de sesión
	session_start();

	// Cuando se pulsa el botón salir la sesión se destruye y se va al index.
	if(isset($_GET['salir'])){
		session_destroy();
		header("location:index.php");
	}
?>

<!doctype html>

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<meta name="author" content="Alberto y Miguel" />
		<meta name="keywords" lang="es" content="congreso, granada, sistemas, web, CEIIE" />
		<meta name="description" lang="es" content="Página del primer congreso de Estudiantes de Ingeniería Informática en España" />
		<title>1º Congreso de CEIIE</title>
		<link href="./css/style.css" rel="stylesheet" type="text/css" />
		<link rel="icon" type="image/png" href="./image/fav.png" />

	<?php

		$presentacion="";		// Varables que se usarán como rutas, por defecto en blanco
		$actividades="";		// para no asignar la clase "current" a ningún botón en particular.
		$granada="";
		$comollegar="";
		$info="";

		if(isset($_GET["contenido"]))		// Si se establecido la variable "contenido" por $_GET.
			$contenido=$_GET["contenido"];
		else
			$contenido="";

		switch($contenido)	// Según su valor se marcará un botón u otro
		{					// añadiendo "class=current" a la variable elegida.
			case "index":
			case "programa":
			case "ponentes": $presentacion="class=\"current\"";  break;
			case "sierra_nevada":
			case "alhambra": $actividades="class=\"current\"";  break;
			case "granada":
			case "monumentos":
			case "tapas":
			case "barrios":
			case "etsiit": $granada="class=\"current\"";  break;
			case "bus":
			case "tren":
			case "coche":
			case "avion": $comollegar="class=\"current\"";  break;
			case "contacto":
			case "patrocinio":
			case "inscripcion": $info="class=\"current\"";  break;
			case "login": ;  break;
			case "registro": ;  break;
			case "restablecer": ;  break;
			case "pass": ;  break;
			case "admin": ;  break;
			case "hoteles": ; break;
			case "edit": ; break;
			case "hotelseleccion": break;

			default:
				$contenido="index";
				$presentacion="class=\"current\"";
		}
	?>

		<?php
				include("./src/php/header.php");
				include("./src/php/menubar.php");
		?>

		<?php
				include("./src/php/content.php");
		?>

	<?php
				include("./src/php/footer.php");
	?>


text:
#include <signal.h>

#include <iostream>
#include <thread>

#include <glog/logging.h>

#include <folly/Format.h>
#include <folly/Singleton.h>
#include <folly/logging/Init.h>

#include "mcrouter/lib/network/AsyncMcServer.h"
#include "mcrouter/lib/network/AsyncMcServerWorker.h"
#include "mcrouter/lib/network/CarbonMessageDispatcher.h"
#include "mcrouter/lib/network/McServerRequestContext.h"
#include "mcrouter/lib/network/gen/MemcacheMessages.h"
#include "mcrouter/lib/network/gen/MemcacheServer.h"
#include "mcrouter/lib/network/test/MockMc.h"
#include "mcrouter/lib/network/test/MockMcOnRequest.h"

/**
 * Mock Memcached implementation.
 *
 * The purpose of this program is to:
 *
 * 1) Provide a reference AsyncMcServer use case;
 * 2) Serve as an AsyncMcServer implementation for AsyncMcServer
 *    integration tests;
 * 3) Serve as a Memcached mock for other project's integration tests;
 * 4) Provide an easy to follow Memcached logic reference.
 *
 * The intention is to have the same semantics as our Memcached fork.
 *
 * Certain keys with __mockmc__. prefix provide extra functionality
 * useful for testing.
 */

using namespace facebook::memcache;

void serverLoop(
    size_t /* threadId */,
    folly::EventBase& evb,
    AsyncMcServerWorker& worker) {
  worker.setOnRequest(MemcacheRequestHandler<MockMcOnRequest>());
  evb.loop();
}

[[noreturn]] void usage(char** argv) {
  std::cerr << "Arguments:\n"
               "  -P <port>      TCP port on which to listen\n"
               "  -t <fd>        TCP listen sock fd\n"
               "  -s             Use ssl\n"
               "  -z             Zero Copy Threshold (Default disabled)\n"
               "Usage:\n"
               "  $ "
            << argv[0] << " -p 15213\n";
  exit(1);
}

// Configure folly to enable INFO+ messages, and everything else to
// enable WARNING+.
// Set the default log handler to log asynchronously by default.
FOLLY_INIT_LOGGING_CONFIG(".=WARNING,folly=INFO; default:async=true");

int main(int argc, char** argv) {
  folly::SingletonVault::singleton()->registrationComplete();

  AsyncMcServer::Options opts;
  opts.worker.versionString = "MockMcServer-1.0";

  bool ssl = false;
  uint16_t port = 0;

  int c;
  while ((c = getopt(argc, argv, "P:t:z:sh")) >= 0) {
    switch (c) {
      case 's':
        ssl = true;
        break;
      case 'P':
        port = folly::to<uint16_t>(optarg);
        break;
      case 't':
        opts.existingSocketFds = {folly::to<int>(optarg)};
        break;
      case 'z':
        opts.worker.tcpZeroCopyThresholdBytes = folly::to<int>(optarg);
        break;
      default:
        usage(argv);
    }
  }

  if (ssl) {
    if (port) {
      opts.sslPorts.push_back(port);
    }
    opts.pemCertPath = "mcrouter/lib/network/test/test_cert.pem";
    opts.pemKeyPath = "mcrouter/lib/network/test/test_key.pem";
    opts.pemCaPath = "mcrouter/lib/network/test/ca_cert.pem";
  } else {
    if (port) {
      opts.ports.push_back(port);
    }
  }

  try {
    LOG(INFO) << "Starting server";
    AsyncMcServer server(opts);
    server.installShutdownHandler({SIGINT, SIGTERM});
    server.spawn(&serverLoop);
    server.join();
    LOG(INFO) << "Shutting down";
  } catch (const std::exception& e) {
    LOG(ERROR) << e.what();
  }
}


text:
package com.appsrox.my_notes.note;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.appsrox.my_notes.R;
import com.appsrox.my_notes.my_notes;
import com.appsrox.my_notes.model.Attachment;

/**
 * @author appsrox.com
 *
 */
public class PhotoActivity extends Activity {

	//private static final String TAG = "PhotoActivity";

	private ImageView iv;
	private ImageButton backBtn;
	private ImageButton deleteBtn;

	private SQLiteDatabase db;
	private Attachment attachment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo);
        findViews();

        db = my_notes.db;

        long id = getIntent().getLongExtra(Attachment.COL_ID, 0);
        if (id > 0) {
        	attachment = new Attachment(id);
        	attachment.load(db);
        	iv.setImageURI(Uri.parse(attachment.getUri()));
        }
    }

	private void findViews() {
		iv = (ImageView) findViewById(R.id.image);
		backBtn = (ImageButton) findViewById(R.id.back_btn);
		deleteBtn = (ImageButton) findViewById(R.id.delete_btn);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;

		case R.id.delete_btn:
			attachment.delete(db);
			finish();
			break;
		}
	}

}


text:
ALTER TABLE project_version_download_warnings
  ALTER COLUMN download_id DROP NOT NULL,
  ALTER COLUMN download_id DROP DEFAULT;

UPDATE project_version_download_warnings SET download_id = NULL WHERE download_id = -1;

# --- !Downs
UPDATE project_version_download_warnings SET download_id = -1 WHERE download_id IS NULL;

ALTER TABLE project_version_download_warnings
  ALTER COLUMN download_id SET DEFAULT -1,
  ALTER COLUMN download_id SET NOT NULL;


text:
<?php namespace Anomaly\Streams\Platform\Addon\Theme;

use Anomaly\Streams\Platform\Addon\Addon;

/**
 * Class Theme
 *
 * @link    http://pyrocms.com/
 * @author  PyroCMS, Inc. <support@pyrocms.com>
 * @author  Ryan Thompson <ryan@pyrocms.com>
 */
class Theme extends Addon
{

    /**
     * Determines whether this is
     * an admin theme or not.
     *
     * @var bool
     */
    protected $admin = false;

    /**
     * Determines whether this is
     * the active theme or not.
     *
     * @var bool
     */
    protected $active = false;

    /**
     * Determines whether this is
     * the currently rendering theme
     * or not.
     *
     * @var bool
     */
    protected $current = false;

    /**
     * Get the admin flag.
     *
     * @return bool
     */
    public function isAdmin()
    {
        return $this->admin;
    }

    /**
     * Set the active flag.
     *
     * @param  $active
     * @return $this
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get the active flag.
     *
     * @return bool
     */
    public function isActive()
    {
        return $this->active;
    }

    /**
     * Return the current flag.
     *
     * @return bool
     */
    public function isCurrent()
    {
        return $this->current;
    }

    /**
     * Set the current flag.
     *
     * @param $current
     * @return $this
     */
    public function setCurrent($current)
    {
        $this->current = $current;

        return $this;
    }

    /**
     * Get the module's presenter.
     *
     * @return ThemePresenter
     */
    public function getPresenter()
    {
        return app()->make('Anomaly\Streams\Platform\Addon\Theme\ThemePresenter', ['object' => $this]);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;
using Hapikit.Templates;

namespace Hapikit
{
    public static class UriExtensions
    {

        public static UriTemplate MakeTemplate(this Uri uri)
        {
            var parameters = uri.GetQueryStringParameters();
            return MakeTemplate(uri, parameters);

        }

        public static UriTemplate MakeTemplate(this Uri uri, IDictionary<string, object> parameters)
        {
            var target = uri.GetComponents(UriComponents.AbsoluteUri
                                           & ~UriComponents.Query
                                           & ~UriComponents.Fragment, UriFormat.Unescaped);
            var template = new UriTemplate(target + "{?" + string.Join(",", parameters.Keys.ToArray()) + "}");
            template.AddParameters(parameters);

            return template;
        }
        public static Dictionary<string, object> ObjectToDictionary<T>(T dto)
        {
            Type t = typeof (T);
            var properties = t.GetRuntimeProperties();
            var dictionary = properties.ToDictionary(info => info.Name,
                info => info.GetValue(dto, null));
            return dictionary;
        }

        public static Uri AddToQuery(this Uri requestUri, Dictionary<string,string> values)
        {

            var formContent = new FormUrlEncodedContent(values);

            var uriBuilder = new UriBuilder(requestUri) { Query = formContent.ReadAsStringAsync().Result };

            return uriBuilder.Uri;
        }

        public static Dictionary<string, object> GetQueryStringParameters(this Uri target )
        {
            Uri uri = target;
            var parameters = new Dictionary<string, object>();

            var reg = new Regex(@"([-A-Za-z0-9._~]*)=([^&]*)&?");		// Unreserved characters: http://tools.ietf.org/html/rfc3986#section-2.3
            foreach (Match m in reg.Matches(uri.Query))
            {
                string key = m.Groups[1].Value.ToLowerInvariant();
                string value = m.Groups[2].Value;
                parameters.Add(key, value);
            }
            return parameters;
        }

        public static Uri AddParametersToQueryString(this Uri target, bool? replaceQueryString, string[] linkParameters)
        {
            var queryTokens = String.Join(",", linkParameters.
                Where(k => !target.OriginalString.Contains("{" + k + "}"))
                .Select(p => p).ToArray());

            // If query string already contains a parameter, then assume replace.
            replaceQueryString = replaceQueryString ?? linkParameters.Any(k => target.Query.Contains(k + "="));

            string queryStringTemplate = null;
            if (replaceQueryString == true || String.IsNullOrEmpty(target.Query))
            {
                queryStringTemplate = "{?" + queryTokens + "}";
            }
            else
            {
                queryStringTemplate = "{&" + queryTokens + "}";
            }

            var targetUri = target.OriginalString;

            if (replaceQueryString == true)
            {
                var queryStart = targetUri.IndexOf("?");
                if (queryStart >= 0)
                {
                    targetUri = targetUri.Substring(0, queryStart);
                }
            }

            return new Uri(targetUri + queryStringTemplate);
        }

        public static Uri GetResolvedTarget(this Uri resolvedTarget, Dictionary<string, object> linkParameters, bool addNonTemplatedParametersToQueryString)
        {
            if (resolvedTarget == null) return null;

            var uriTemplate = new UriTemplate(resolvedTarget.OriginalString);

            if (addNonTemplatedParametersToQueryString)
            {
                var templateParameters = uriTemplate.GetParameterNames();
                if (linkParameters.Any(p => !templateParameters.Contains(p.Key)))
                {
                    resolvedTarget = resolvedTarget.AddParametersToQueryString(null, linkParameters.Keys.ToArray());
                    uriTemplate = new UriTemplate(resolvedTarget.OriginalString);
                }
            }

            if (resolvedTarget.OriginalString.Contains("{"))
            {
                ApplyParametersToTemplate(uriTemplate, linkParameters);
                resolvedTarget = new Uri(uriTemplate.Resolve(), UriKind.RelativeOrAbsolute);
                return resolvedTarget;
            }

            return resolvedTarget;
        }

        // This should be moved into URI Template library
        public static void ApplyParametersToTemplate(this UriTemplate uriTemplate, Dictionary<string, object> linkParameters)
        {
            foreach (var parameter in linkParameters)
            {
                if (parameter.Value is IEnumerable<string>)
                {
                    uriTemplate.SetParameter(parameter.Key, (IEnumerable<string>)parameter.Value);
                }
                else if (parameter.Value is IDictionary<string, string>)
                {
                    uriTemplate.SetParameter(parameter.Key, (IDictionary<string, string>)parameter.Value);
                }
                else
                {
                    uriTemplate.SetParameter(parameter.Key, parameter.Value.ToString());
                }
            }
        }

    }
}


text:
---
layout: post
title: Google Calendar to Google Sheets Bidirectional Sync
date: '2014-12-12T07:47:00.001-05:00'
author: Phillip Green II
tags:
- sheets
- javascript
- sync
- google calendar
- calendar
- google sheets
- google
modified_time: '2015-03-29T00:48:00.001-05:00'
blogger_id: tag:blogger.com,1999:blog-3096944600800047027.post-8062514110157538820
blogger_orig_url: http://coder-in-training.blogspot.com/2014/12/google-calendar-to-google-sheets.html
calendarUtilsLibProjectKey: MT9e6TqW6VlvXr43nv8kZqWRtpc-QmtJv
---

Personally, I love both spreadsheets and google calendar and some times it makes sense to keep them in sync.
The use case that started me on this was a calendar to keep track of important work dates.
Having things show up on my google calendar is great for keeping track of everything, but I have not found any simple way of doing bulk upload
My solution is to dump into a spreadsheet all of the events (holidays, major releases, ...).
There is one place to look.
I then added a menu to either push events from the spreadsheet to my calendar or vice versa.
The process is manual, but I haven't had any problems.
Generally, I view and update events through the calendar.
When necessary, I drop into the spreadsheet,
pull from the calendar, make my changes, then push back to the calendar.
Below is the code I use to make it happen.

##CalendarUtilsLib
###Creation
In order to re-use my sync code across multiple spreadsheets, I created a stand alone project that was reused as a library.
Go to https://drive.google.com/ and click
`New->More->Google Apps Script`

```javascript
//TODO: support day light savings time

function createEventsLookup(events){
  var lookup = {};
  events.forEach(function(event){
    lookup[event.getId()] = event;
  });

  return lookup;
}

function createEventInfosLookup(events){
  var lookup = {};
  events.forEach(function(event){
    lookup[event.getId()] = event;
  });

  return lookup;
}

function loadAllEventsFromCalendar(calendar) {
  return calendar.getEvents(new Date(2000,0,1), new Date(3000,0,1));
}
/*
* This throws in a pause (sleep) after so many steps.
* This exists because google will fail if you attempt too many updates at once.
*/
function throttleSpeed(limit,count) {
  if(count % limit === (limit - 1)) {
    Utilities.sleep(1000);
  }
}

function publish2calendar(calendar, eventInfos) {
  var existingEvents = loadAllEventsFromCalendar(calendar)
  var existingEventsById = createEventsLookup(existingEvents);

  var updatedEvents = {},
  updateCounts = 0,
  createdCounts = 0,
  errorsCount = 0;
  eventInfos.forEach(function(info,index){
    throttleSpeed(15,index);
    if(info && info.isValid()){
      var existingEvent = existingEventsById[info.getId()];
      if(existingEvent) {
        updatedEvents[existingEvent.getId()] = true;
        if(info.updateEvent(existingEvent)) {
          Logger.log('Updated Event: %s (%s %s-%s)', existingEvent.getId(),existingEvent.getTitle(),existingEvent.getStartTime(),existingEvent.getEndTime());
          updateCounts = updateCounts + 1;
        }
        } else {
          Logger.log('Creating Event: %s %s-%s',info.getTitle(), info.getStartTime(), info.getEndTime());
          var event = info.createEventOnCalendar(calendar);
          info.setId(event.getId());
          // Make sure the cell is updated right away in case the script is interrupted
          SpreadsheetApp.flush();
          createdCounts = createdCounts + 1;
        }
        } else {
          Logger.log('Invalid row[%s]: %s', index, info && info.toString());
        }
        })

        var deletedCounts = 0;
        existingEvents.forEach(function(event,index){
          if(!updatedEvents[event.getId()]) {
            throttleSpeed(15,index);
            Logger.log('Deleting Event: %s (%s %s-%s)', event.getId(),event.getTitle(),event.getStartTime(),event.getEndTime());
            event.deleteEvent();
            deletedCounts = deletedCounts + 1;
          }
          });

          var msgLines = [],
          timeout = 5;
          if(updateCounts > 0) {
            msgLines.push("Updates:\t" + updateCounts);
            timeout = -1
          }
          if(createdCounts > 0) {
            msgLines.push("New Events:\t "+ createdCounts);
            timeout = -1
          }
          if(deletedCounts > 0) {
            msgLines.push("Deleted Events:\t "+ deletedCounts);
            timeout = -1
          }
          if(errorsCount > 0) {
            msgLines.push("Errors:\t" + errorsCount);
            timeout = -1
          }

          if(msgLines.length === 0) {
            msgLines.push("No changes");
          }
          msgLines.forEach(function(line) {Logger.log(line)});
          SpreadsheetApp.getActiveSpreadsheet().toast(msgLines.join("\n"),"Publish Complete",timeout);
        }

        function refreshFromCalendar(calendar, eventInfos, addEvent) {
          var existingEvents = loadAllEventsFromCalendar(calendar);
          var infosById = createEventInfosLookup(eventInfos);

          var updateCount = 0,
          newEntriesCount = 0,
          errorsCount = 0;
          existingEvents.forEach(function(event){
            var info = infosById[event.getId()];
            if(info) {
              try{
                if(info.updateSelf(event)) {
                  Logger.log('Updated Info: %s (%s %s-%s)', info.getId(),info.getTitle(),info.getStartTime(),info.getEndTime());
                  updateCount = updateCount + 1;
                }
              }
              catch(e) {
                Logger.log(e.message);
                errorsCount = errorsCount + 1;
              }
              } else {
                info = addEvent(event);
                Logger.log('Created Info: %s (%s %s-%s)', info.getId(),info.getTitle(),info.getStartTime(),info.getEndTime());
                newEntriesCount = newEntriesCount + 1;
              }
              SpreadsheetApp.flush();
              });

              var msgLines = [],
              timeout = 5;

              if(updateCount > 0) {
                msgLines.push("Updates:\t" + updateCount);
                timeout = -1;
              }
              if(newEntriesCount > 0) {
                msgLines.push("New Entries:\t" + newEntriesCount);
                timeout = -1;
              }
              if(errorsCount > 0) {
                msgLines.push("Errors:\t" + errorsCount);
                timeout = -1;
              }

              if(msgLines.length === 0) {
                msgLines.push("No changes");
              }
              msgLines.forEach(function(line) {Logger.log(line)});
              SpreadsheetApp.getActiveSpreadsheet().toast(msgLines.join("\n"),"Refresh Complete",timeout);
            }
```

Save the above script as "CalendarUtilsLib".
Then click `File->Manage Versions...`.
Create the initial version (the comment doesn't matter).
Lastly, go to `File->Project Properties`.
On the page lists the "Project key".
It will look something like this: `{{ page.calendarUtilsLibProjectKey }}`.
The project key is what is necessary to import this script as a library.

###Explanation
CalendarUtilsLib exposes two functions: `refreshFromCalendar(calendar, eventInfos, addEvent)` and `publish2calendar(calendar, eventInfos)`.
The first is the pull function that takes events from the calendar and will add them to your spread sheet, the second is the push.
The first parameter in each function is the calendar object from the Google Calendar API, the second parameter is a list of EventInfos which is sourced from the spreadsheet.
The next paragraph goes into more detail.
Lastly, `refreshFromCalendar()` has a third parameter: `addEvent`.
This is actually a function that accepts a calendar event and will create a new `EventInfo` and add it to your spread sheet.
This function is called when an event exists on the calendar, but not in the spreadsheet.
An example implementation will be showed below.
CalendarUtilsLib works through an abstraction called `EventInfo`.
Essentially, `EventInfo`s allow you to customize how the calendar events map to your spread sheet.
`EventInfo`s must have three methods:
`updateSelf(calendarEvent)`, `updateEvent(calendarEvent)`, and `isValid()`.
The first updates the spreadsheet with the calendar event, the second updates the calendar event.
Each return a boolean of whether or not anything changes occurred.
The last method is used to keep garbage data from messing things up.
If the info says it isn't valid, then it won't be pushed to the calendar.
Below is sample implementations, so I won't go into detail here.

##WorkSchedule Script
Below is the spreadsheet code for the spreadsheet that I want to sync with a calendar.
I start by creating my script files and then import CalendarUtilsLib.

###Creation
Open the spreadsheet you want to sync with a calendar.
Click `Tools->Script Editor`.
Add the following code segments.
I split them into two scripts, but that is my personal preference.

####main.gs
```javascript
function retrieveDatesCalendar() {
  return CalendarApp.getCalendarsByName('Work')[0];
}

function loadAllInfos() {
  return loadWorkScheduleEventInfos();
}

function publish2calendar() {
  CalendarUtilsLib.publish2calendar(retrieveDatesCalendar(),loadAllInfos());
}

function refreshFromCalendar() {
  CalendarUtilsLib.refreshFromCalendar(retrieveDatesCalendar(),loadAllInfos(), addEventToWorkSheet);
}
/*This function adds the Menu options*/
function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [
{name: "Refresh (calendar -> sheet)", functionName: "refreshFromCalendar"} ,
{name: "Publish (sheet -> calendar)", functionName: "publish2calendar"}
];
ss.addMenu("Calendar", menuEntries);
}
```

####WorkScheduleEventInfo.gs
```javascript
function loadWorkScheduleEventInfos() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Work')
  var startRow = 2;  // First row of data to process
  var numRows = sheet.getLastRow();  // Number of rows to process
  var dataRange = sheet.getRange(startRow, 1, numRows, 8);
  return dataRange.getValues().map(function(row,index){
    return new WorkScheduleEventInfo(sheet,startRow+index,row);
  });
}

function addEventToWorkSheet(event) {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Work');
  var rowNumber = sheet.getLastRow()+1;
  var info = new WorkScheduleEventInfo(sheet,rowNumber,[]);
  info.updateSelf(event);
  //This is a little tweak I added so I can recognize when new events are added to the sheet.
  var newRowAsRange = sheet.getRange(rowNumber + ":" + rowNumber);
  newRowAsRange.setBackground("red");
  return info;
}

function WorkScheduleEventInfo(sheet, rowNumber, rowData) {
  var COLUMN_TITLE_INDEX = 0;
  var COLUMN_DESCRIPTION_INDEX = 1;
  var COLUMN_LOCATION_INDEX = 2;
  var COLUMN_START_TIMESTAMP_INDEX = 3;
  var COLUMN_END_TIMESTAMP_INDEX = 4;
  var COLUMN_EVENT_ID_INDEX = 5;

  this.isValid = function() {
    return rowData[COLUMN_TITLE_INDEX] && rowData[COLUMN_START_TIMESTAMP_INDEX] && rowData[COLUMN_END_TIMESTAMP_INDEX];
  }

  function updateField(index,value) {
    sheet.getRange(rowNumber, index+1).setValue(value);
    rowData[index] = value;
  }

  this.getTitle = function() {
    return rowData[COLUMN_TITLE_INDEX];
  };

  this.setTitle = function(title) {
    updateField(COLUMN_TITLE_INDEX,title);
  }

  this.getDescription = function() {
    return rowData[COLUMN_DESCRIPTION_INDEX];
  };

  this.setDescription = function(description) {
    updateField(COLUMN_DESCRIPTION_INDEX,description);
  }

  this.getLocation = function() {
    return rowData[COLUMN_LOCATION_INDEX];
  };

  this.setLocation = function(location) {
    updateField(COLUMN_LOCATION_INDEX,location);
  }

  this.getStartTime = function() {
    return rowData[COLUMN_START_TIMESTAMP_INDEX];
  }

  this.setStartTime = function(startTime) {
    updateField(COLUMN_START_TIMESTAMP_INDEX,startTime);
  }

  this.getEndTime = function() {
    return rowData[COLUMN_END_TIMESTAMP_INDEX];
  }

  this.setEndTime = function(endTime) {
    updateField(COLUMN_END_TIMESTAMP_INDEX,endTime);
  }

  this.getId = function() {
    return rowData[COLUMN_EVENT_ID_INDEX];
  }

  this.setId = function(id) {
    updateField(COLUMN_EVENT_ID_INDEX,id);
  }

  this.createEventOnCalendar = function(calendar) {
    return calendar.createEvent(this.getTitle(), this.getStartTime(), this.getEndTime(), {description:this.getDescription(),location:this.getLocation()});
  }

  this.updateSelf = function(event) {
    var updateOccurred = false;
    if(this.getId() != event.getId()) {
      if(this.getId()) {
        throw Error('Cannot update self with event with different id');
        } else {
          this.setId(event.getId());
          updateOccurred = true;
        }
      }
      if(this.getTitle() != event.getTitle()) {
        this.setTitle(event.getTitle());
        updateOccurred = true;
      }
      if(!this.getStartTime() || this.getStartTime().getTime() != event.getStartTime().getTime()) {
        this.setStartTime(event.getStartTime());
        updateOccurred = true;
      }
      if(!this.getEndTime() || this.getEndTime().getTime() != event.getEndTime().getTime()) {
        this.setEndTime(event.getEndTime());
        updateOccurred = true;
      }
      if(this.getLocation() != event.getLocation()) {
        this.setLocation(event.getLocation());
        updateOccurred = true;
      }
      if(this.getDescription() != event.getDescription()) {
        this.setDescription(event.getDescription());
        updateOccurred = true;
      }

      return updateOccurred;
    }

    this.updateEvent = function(event) {
      if(this.getId() !== event.getId()) {
        throw Error('Cannot update event with different id');
      }
      changeOccurred = false;
      if(event.getTitle() != this.getTitle()) {
        event.setTitle(this.getTitle());
        changeOccurred = true;
      }
      if(event.getStartTime().getTime() != this.getStartTime().getTime() || event.getEndTime().getTime() != this.getEndTime().getTime()) {
        event.setTime(this.getStartTime(),this.getEndTime());
        changeOccurred = true;
      }
      if(event.getLocation() != this.getLocation()) {
        event.setLocation(this.getLocation());
        changeOccurred = true;
      }
      if(event.getDescription() != this.getDescription()) {
        event.setDescription(this.getDescription());
        changeOccurred = true;
      }
      return changeOccurred;
    }

    this.toString = function() {
      return this.rowData;
    }
  }
```

After adding the code, you import CalendarUtilsLib by clicking `Resources->Libraries`.
Paste the Project Key from earlier (`{{ page.calendarUtilsLibProjectKey }}`).
Be sure to select a version.
The development mode allows you to edit the library and test it at the same time, but it is slower and google suggests not doing it.
If you aren't making changes to CalendarUtilsLib, then disable development mode.
At this point, you are ready to tinker and customize for your code.
Read below for more details.

###Explanation

The code above assumes a worksheet in your spreadsheet called "Work" with the following columns:

  Title
  Description
  Location
  Start Timestamp
  End Timestamp
  Event Id (don't touch)

  Christmas Vacation

  Home
  12/24/2012 0:00:00
  12/28/2012 0:00:00

The event id column is very important.
This is what matches `EventInfo`s against Calendar events.
Because of that, it must exist and you should never manually change this column.

####main.gs
This script is where we setup the menu.
It needs to be able to retrieve the calendar (`retrieveDatesCalendar()`) and the infos (`loadAllInfos()`).
If your calendar is named differently, then update `retrieveDatesCalendar()`.
 I have two different spreadsheets that use CalenderUtilsLib and this portion of the script looks nearly the same in each.
 Pretty much the only difference is calendar name.
 The real customization occurs within the EventInfo.

####WorkScheduleEventInfo.gs
This is where you will be spending most of your tweaking.
I like to break my code into smaller chunks, which is why you see all of the setters and getters.
For me it makes the implementation of `updateEvent()`
and `updateSelf()` easier.
While the methods look big, each section is simply doing a comparison between event info and the calendar event to see if an update should occur.
 If so, it makes the change and marks that a change has occurred.
 The last bit of customization is in `addEventToWorkSheet()`.
 It works by creating a new `EventInfo` on the next blank line and doing an update.
 I have found this pattern works very well.
 For the sake of my own sanity, I color any new rows red.

##Conclusion
While there is a bit of setup work, I have used this pattern a couple times and it has really worked well for me.
 For my own spreadsheets, I have created varies `EventInfo` implementations where I some times dynamically generate fields.
 It has allowed a lot of flexibility.


text:
import React, { Component } from 'react';
import { connect } from 'react-redux'
import SidebarHeader from './SidebarHeader';
import SlackChannels from './SlackChannels';

import './Sidebar.less';

const Sidebar = ({ isSidebarActive }) => (
  <div className={`sidebar ${isSidebarActive ? "active" : ""}`}>
    <SidebarHeader />
    <SlackChannels />
  </div>
);

const mapStateToProps = state => {
  return {
    isSidebarActive: state.isSidebarActive,
  };
};

export default connect(mapStateToProps)(Sidebar);


text:
package org.mindinformatics.gwt.domeo.plugins.annotation.persistence.ui;

import org.mindinformatics.gwt.domeo.client.Domeo;
import org.mindinformatics.gwt.domeo.client.IDomeo;
import org.mindinformatics.gwt.domeo.model.persistence.ontologies.IDomeoOntology;
import org.mindinformatics.gwt.domeo.plugins.persistence.json.marshalling.JsoAnnotationSetSummary;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Paolo Ciccarese <paolo.ciccarese@gmail.com>
 */
public class JsAnnotationSetSummaryLens extends Composite {

	interface Binder extends UiBinder<Widget, JsAnnotationSetSummaryLens> { }
	private static final Binder binder = GWT.create(Binder.class);

	private IDomeo _domeo;
	private JsoAnnotationSetSummary _set;
	private JsAnnotationSetSummaryLens _this;
	private ExistingAnnotationSetsListPanel _parent;

	@UiField VerticalPanel body;
	@UiField FocusPanel wrapper;
	@UiField SimplePanel nameEditableField;
	@UiField SimplePanel itemsNumberLabel;
	//@UiField SimplePanel descriptionField;
	@UiField HorizontalPanel provenanceLabel;
	@UiField CheckBox selectionButton;
	@UiField SimplePanel typeField;
	@UiField SimplePanel arrow;

	public JsAnnotationSetSummaryLens(IDomeo domeo, final ExistingAnnotationSetsListPanel parent, JsoAnnotationSetSummary set) {
		_domeo = domeo;
		_this = this;
		_set = set;
		_parent = parent;

		initWidget(binder.createAndBindUi(this));

		if(set.getType().equals(IDomeoOntology.discussionSet)) {
			typeField.add(new Image(Domeo.resources.littleCommentsIcon()));
		} else {
			typeField.setVisible(false);
		}

		wrapper.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				parent.displayAannotationSetInfo(_set);
			}
		});

		selectionButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				//parent.setSelectedAnnotaitonSet(_set);
				parent.refresh();
				event.stopPropagation();
			}
		});

		refreshLens();
	}

	public JsAnnotationSetSummaryLens(IDomeo domeo, final ExistingAnnotationSetsListPanel parent, JsoAnnotationSetSummary set, boolean alreadyLoaded) {
		_domeo = domeo;
		_this = this;
		_set = set;
		_parent = parent;

		if(alreadyLoaded) selectionButton.setEnabled(false);

		initWidget(binder.createAndBindUi(this));

		if(set.getType().equals(IDomeoOntology.discussionSet)) {
			typeField.add(new Image(Domeo.resources.littleCommentsIcon()));
		} else {
			typeField.setVisible(false);
		}

		wrapper.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				parent.displayAannotationSetInfo(_set);
			}
		});

		selectionButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				//parent.setSelectedAnnotaitonSet(_set);
				parent.refresh();
				event.stopPropagation();
			}
		});

		refreshLens();
	}

	public void setSelected(boolean selection) {
		selectionButton.setValue(selection);
	}

	public boolean isSelected() {
		return selectionButton.getValue().booleanValue();
	}

	public void refresh() {
		_parent.refresh();
	}

	public void refreshLens() {
		try {
			/*
			if(_parent.isAnnotationSetSelected(_set)) {
				selectionButton.setValue(true);
			}
			*/

			nameEditableField.add(new HTML(_set.getLabel()));
			//descriptionField.add(new HTML(_set.getDescription()));

			itemsNumberLabel.clear();
			if(_set.getNumberOfAnnotationItems()>0) {
				Label itemsNumberText = new Label(_set.getNumberOfAnnotationItems() +(_set.getNumberOfAnnotationItems()==1?" item":" items"));
				itemsNumberText.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						//_domeo.displayAnnotationOfSet(_set);
					}
				});
				itemsNumberLabel.add(itemsNumberText);
			} else {
				itemsNumberLabel.add(new HTML("No items"));
			}

			// Emphasize
			// --------------

			final CheckBox checkHighlight = new CheckBox();
			//checkHighlight.setValue(_set.isEmphasized());
			checkHighlight.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					_domeo.getLogger().command(_this, "Emphasis on " + checkHighlight.getValue());
					//_domeo.getContentPanel().getAnnotationFrameWrapper()
					//	.manageSetEmphasis(_set, checkHighlight.getValue());
					_domeo.getComponentsManager().updateObjectLenses(_set);
					_parent.refresh();
				}
			});
			//emphasizeCheckBox.clear();
			//emphasizeCheckBox.add(checkHighlight);

			// Provenence
			// ----------
			provenanceLabel.clear();
			provenanceLabel.add(new HTML("By " + _set.getCreatedBy().getScreenName() +" on " + _set.getFormattedCreatedOn()));

			// Access control
			// --------------
			/*
			final Image accessIcon = new Image();
			ClickHandler accessHandler = new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					AnnotationAccessPopup popup = new AnnotationAccessPopup(_domeo, _this, _set);
					popup.show(accessIcon.getAbsoluteLeft(), accessIcon.getAbsoluteTop());
					event.stopPropagation();
				}
			};
			if(_domeo.getAnnotationAccessManager().isAnnotationSetPublic(_set)) {
				accessIcon.setResource(Domeo.resources.publicLittleIcon());
				addSimpleButton(accessPolicy, accessIcon, accessHandler);
			} else if(_domeo.getAnnotationAccessManager().isAnnotationSetGroups(_set)) {
				accessIcon.setResource(Domeo.resources.friendsLittleIcon());
				addSimpleButton(accessPolicy, accessIcon, accessHandler);
			} else if(_domeo.getAnnotationAccessManager().getAnnotationSetAccess(_set).equals(_domeo.getAgentManager().getUserPerson().getUrl())) {
				accessIcon.setResource(Domeo.resources.privateLittleIcon());
				addSimpleButton(accessPolicy, accessIcon, accessHandler);
			}
			*/

			// Locking
			// -------
			/*
			final Image rightsIcon = new Image();
			ClickHandler lockHandler = new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					AnnotationRightsPopup popup = new AnnotationRightsPopup(_domeo, _this, _set);
					popup.show(rightsIcon.getAbsoluteLeft(), rightsIcon.getAbsoluteTop());
					event.stopPropagation();
				}
			};
			if(_set.getIsLocked()) {
				rightsIcon.setResource(Domeo.resources.readOnlyLittleIcon());
				addSimpleButton(lockingPolicy, rightsIcon, lockHandler);
			} else {
				rightsIcon.setResource(Domeo.resources.readWriteLittleIcon());
				addSimpleButton(lockingPolicy, rightsIcon, lockHandler);
			}
			*/

			// Visibility
			// ----------
			/*
			final Image visibilityIcon = new Image();
			ClickHandler visibilityHandler = new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					AnnotationVisibilityPopup popup = new AnnotationVisibilityPopup(_domeo, _this, _set);
					popup.show(visibilityIcon.getAbsoluteLeft(), visibilityIcon.getAbsoluteTop());
					event.stopPropagation();
				}
			};
			if(_set.getIsVisible()) {
				visibilityIcon.setResource(Domeo.resources.visibleLittleIcon());
				addSimpleButton(visibilityPolicy, visibilityIcon, visibilityHandler);
			} else {
				visibilityIcon.setResource(Domeo.resources.invisibleLittleIcon());
				addSimpleButton(visibilityPolicy, visibilityIcon, visibilityHandler);
			}
			*/
		} catch(Exception e) {
			_domeo.getLogger().exception(this, "Visualization of the set " + _set.getLabel() + " failed");
		}
	}

	public JsoAnnotationSetSummary getSet() {
		return _set;
	}

	private void addSimpleButton(SimplePanel panel, Image img, ClickHandler clickHandler) {
		panel.clear();
		img.addClickHandler(clickHandler);
		panel.add(img);
	}
}


text:
<!doctype html>

  <meta http-equiv="Content-Type" content="text/html;
    charset=ISO-8859-1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <title>SPA Chapter 8</title>

  <link rel="stylesheet" href="css/spa.css"       type="text/css"/>
  <link rel="stylesheet" href="css/spa.shell.css" type="text/css"/>
  <link rel="stylesheet" href="css/spa.chat.css"  type="text/css"/>
  <link rel="stylesheet" href="css/spa.avtr.css"  type="text/css"/>


text: console.log('this is plugin');


text:
namespace SchoolClasses
{
    using System;
    using System.Collections.Generic;

    public class Discipline : IComment
    {
        private string disciplineName;
        private int numberOfLectures;
        private int numberOfExcercises;
        private List<string> comment = new List<string>();

        public Discipline(string disciplineName, int numberOfLectures, int numberOfExcercises)
        {
            this.DisciplineName = disciplineName;
            this.NumberOfLectures = numberOfLectures;
            this.NumberOfExcercises = numberOfExcercises;
        }

        public string DisciplineName
        {
            get { return disciplineName; }
            private set
            {
                if (value == string.Empty)
                {
                    throw new ArgumentException("Invalid Discipline Name!");
                }
                else
                {
                    disciplineName = value;
                }
            }
        }

        public int NumberOfLectures
        {
            get { return numberOfLectures; }
            private set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Invalid Number of Lectures!");
                }
                else
                {
                    numberOfLectures = value;
                }
            }
        }

        public int NumberOfExcercises
        {
            get { return numberOfExcercises; }
            private set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Invalid Number of Excercises!");
                }
                else
                {
                    numberOfExcercises = value;
                }
            }
        }

        public List<string> Comment
        {
            get
            {
                return this.comment;
            }
        }

        public void AddComment(string comment)
        {
            this.Comment.Add(comment);
        }

        public override string ToString()
        {
            return string.Format("Discipline: {0} | Number of lectures: {1} | Number of excercises: {2}", this.DisciplineName, this.NumberOfLectures, this.NumberOfExcercises);
        }
    }
}


text:
@interface UIView (Extend)

- (void)resizeToFitSubviews;

- (CGFloat)getSubviewsHeight;

- (void)showLoading;

- (void)hideLoading;

- (CGFloat)getWidth;

- (CGFloat)getHeight;

- (CGFloat)getX;

- (CGFloat)getY;

- (void)setTopBorder:(UIColor *)color;

- (void)setTopBorder:(UIColor *)color height:(CGFloat)height;

- (void)setBorderWidth:(CGFloat)width;

- (void)setBorderColor:(UIColor *)color;

- (void)setBorderRadius:(CGFloat)radius;

- (void)setBorder:(CGFloat)radius color:(UIColor *)color;

- (void)makeRound;

- (void)click:(id)target action:(SEL)action;

- (BOOL)isTap:(UITapGestureRecognizer *)gestureRecognizer;

- (void)empty;

- (void)setCorner:(UIRectCorner)corners size:(CGFloat)size;

- (void)showQuickHUD:(NSString *)title;

- (void)showQuickHUD:(NSString *)title callback:(MBProgressHUDCompletionBlock)callback;

- (void)showProgressHUD;

- (void)showProgressHUD:(NSString *)title;

- (void)showProgressHUD:(NSString *)title callback:(MBProgressHUDCompletionBlock)callback;

- (void)hideProgressHUD;

- (UIViewController *)viewController;

- (CGFloat)frameX;

- (CGFloat)frameY;

- (CGFloat)frameWidth;

- (CGFloat)frameHeight;

- (void)setFrameY:(CGFloat)y;

- (void)setFrameX:(CGFloat)x;

- (void)setFrameWidth:(CGFloat)width;

- (void)setFrameHeight:(CGFloat)height;

- (void)disableEdit;

- (void)toFront;

- (void)toBack;
@end


text:
stage: Create
group: Source Code
info: "To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#designated-technical-writers"
type: reference
---
# Jupyter Notebook Files

> [Introduced](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/2508/) in GitLab 9.1.

[Jupyter](https://jupyter.org/) Notebook (previously IPython Notebook) files are used for
interactive computing in many fields and contain a complete record of the
user's sessions and include code, narrative text, equations, and rich output.

When added to a repository, Jupyter Notebooks with a `.ipynb` extension will be
rendered to HTML when viewed.

![Jupyter Notebook Rich Output](img/jupyter_notebook.png)

Interactive features, including JavaScript plots, will not work when viewed in
GitLab.

## Jupyter Hub as a GitLab Managed App

You can deploy [Jupyter Hub as a GitLab managed app](./../../../clusters/applications.md#jupyterhub).

## Jupyter Git integration

Find out how to [leverage JupyterLab's Git extension on your Kubernetes cluster](./../../../clusters/applications.md#jupyter-git-integration).


text:
<?php
/**
 * WsSoap\Client
 *
 * Extends the PHP SoapClient class to add WSSE security headers.
 * Based on: http://www.php.net/manual/en/soapclient.soapclient.php#97273
 */

namespace WsSoap;

class Client extends \SoapClient {
    protected $wsUsername;
    protected $wsPassword;
    protected $wsse;
    protected $wsHeader;

    public function __construct($wsdl, array $options) {
        if (empty($options['wsUsername']) || empty($options['wsPassword']))
            throw new \InvalidArgumentException('wsUsername and wsPassword must be supplied in the options array.');

        $this->wsUsername = $options['wsUsername'];
        $this->wsPassword = $options['wsPassword'];
        $this->wsse = empty($options['wsse']) ? 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' : $options['wsse'];

        parent::__construct($wsdl, $options);

        $this->generateWsHeader();
        $this->__setSoapHeaders();
    }

    public function __setSoapHeaders($soapheaders=null) {
        parent::__setSoapHeaders();
        return parent::__setSoapHeaders($this->addWsHeader($soapheaders));
    }

    public function __soapCall($function_name, $arguments, $options=null, $input_headers=null, &$output_headers=null) {
        return parent::__soapCall($function_name, $arguments, $options, $this->addWsHeader($input_headers), $output_headers);
    }

    protected function generateWsHeader() {
        $soapVarUser = new \SoapVar($this->wsUsername, XSD_STRING, null, $this->wsse, null, $this->wsse);
        $soapVarPass = new \SoapVar($this->wsPassword, XSD_STRING, null, $this->wsse, null, $this->wsse);

        $wsseAuth = new WSSEAuth($soapVarUser, $soapVarPass);
        $soapVarWsseAuth = new \SoapVar($wsseAuth, SOAP_ENC_OBJECT, null, $this->wsse, 'UsernameToken', $this->wsse);
        $wsseToken = new WSSEToken($soapVarWsseAuth);
        $soapVarWsseToken = new \SoapVar($wsseToken, SOAP_ENC_OBJECT, null, $this->wsse, 'UsernameToken', $this->wsse);
        $soapVarHeaderVal = new \SoapVar($soapVarWsseToken, SOAP_ENC_OBJECT, null, $this->wsse, 'Security', $this->wsse);

        $this->wsHeader = new \SoapHeader($this->wsse, 'Security', $soapVarHeaderVal, true);
    }

    protected function addWsHeader($headers=null) {
        if (empty($headers)) {
            $headers = array();
        } elseif (!is_array($headers)) {
            $headers = array($headers);
        }

        $headers[] = $this->wsHeader;
        return $headers;
    }
}

class WSSEAuth {
    private $Username;
    private $Password;

    function __construct($username, $password) {
        $this->Username = $username;
        $this->Password = $password;
    }
}

class WSSEToken {
    private $UsernameToken;

    function __construct ($innerVal) {
        $this->UsernameToken = $innerVal;
    }
}