text:
package nl.tno.idsa.framework.behavior.planners;

import nl.tno.idsa.Constants;
import nl.tno.idsa.framework.agents.Agent;
import nl.tno.idsa.framework.behavior.activities.concrete.Activity;
import nl.tno.idsa.framework.behavior.activities.concrete.BasicMovementActivity;
import nl.tno.idsa.framework.behavior.activities.possible.PossibleActivity;
import nl.tno.idsa.framework.behavior.likelihoods.ActivityLikelihoodMap;
import nl.tno.idsa.framework.behavior.likelihoods.DayOfWeek;
import nl.tno.idsa.framework.behavior.multipliers.IMultiplier;
import nl.tno.idsa.framework.messaging.ProgressNotifier;
import nl.tno.idsa.framework.semantics_base.SemanticLibrary;
import nl.tno.idsa.framework.semantics_impl.groups.Group;
import nl.tno.idsa.framework.semantics_impl.locations.LocationFunction;
import nl.tno.idsa.framework.utils.RandomNumber;
import nl.tno.idsa.framework.utils.TextUtils;
import nl.tno.idsa.framework.utils.Tuple;
import nl.tno.idsa.framework.world.Area;
import nl.tno.idsa.framework.world.Environment;
import nl.tno.idsa.framework.world.Time;
import nl.tno.idsa.framework.world.Vertex;
import nl.tno.idsa.tools.DebugPrinter;

import java.util.*;

/**
 * Create agendas for the entire population.
 */
public class AgendaPlanner {

    // Settings and data structures for debugging. *********************************************************************

    private final static int DEBUG_NUM_SAMPLE_AGENDAS = 0;
    private final static boolean DEBUG_QUIT_WHEN_DONE_MAKING_AGENDAS = false;
    private static TreeMap<PossibleActivity, Tuple<Integer, Integer>> successesAndFailures = new TreeMap<>();

    private static void addSuccess(PossibleActivity pa) {
        Tuple<Integer, Integer> sf = successesAndFailures.get(pa);
        if (sf == null) {
            sf = new Tuple<>(1, 0);
            successesAndFailures.put(pa, sf);
        } else {
            successesAndFailures.put(pa, new Tuple<Integer, Integer>(sf.getFirst() + 1, sf.getSecond()));
        }
    }

    private static void addFailure(PossibleActivity pa) {
        Tuple<Integer, Integer> sf = successesAndFailures.get(pa);
        if (sf == null) {
            sf = new Tuple<>(0, 1);
            successesAndFailures.put(pa, sf);
        } else {
            successesAndFailures.put(pa, new Tuple<Integer, Integer>(sf.getFirst(), sf.getSecond() + 1));
        }
    }

    // End settings and data structures for debugging. *****************************************************************

    private final DayOfWeek dayOfWeek;
    private final Environment environment;

    private final IMultiplier[] multipliers;

    private final Map<Agent, ActivityLikelihoodMap> activityProbabilities;

    public AgendaPlanner(Environment environment, DayOfWeek dayOfWeek, IMultiplier... multipliers) {
        this.environment = environment;
        this.dayOfWeek = dayOfWeek;
        this.multipliers = multipliers;
        this.activityProbabilities = new HashMap<>(30000);
    }

    public void createAgendas(Set<Group> households) {

        // Administer progress.
        int current = 0;
        double total = 19 * households.size(); // Magic numbers that make the progress look a bit more uniform.

        // Apply multipliers.
        ProgressNotifier.notifyProgressMessage("Applying multipliers...");
        for (Group household : households) {
            for (Agent agent : household) {
                applyMultipliers(agent);
            }
            int current1 = current++;
            ProgressNotifier.notifyProgress(current1 / total);
        }

        // Give an overview of the expected number of agents that will do each activity and the available capacity.
        // TODO Move to logger.
        Map<String, Double> overviewMultipliers = createOverviewMultipliers();
        TreeMap<String, Integer> overviewCapacities = createOverviewCapacities();
        System.out.println("\n\n" + TextUtils.addSpacesToString("Activity occurrences", 30) + TextUtils.addSpacesToString("Expected", 10) + TextUtils.addSpacesToString("Capacity", 10));
        for (String paS : overviewMultipliers.keySet()) {
            Integer cap = overviewCapacities.get(paS);
            String capS;
            if (cap < 0 || cap == Integer.MAX_VALUE) {
                capS = "Unlimited";
            } else {
                capS = cap.toString();
            }
            System.out.println(TextUtils.addSpacesToString(paS, 30) + TextUtils.addSpacesToString((int) Math.round(overviewMultipliers.get(paS)), 10) + TextUtils.addSpacesToString(capS, 10));
        }

        // Plan activities.
        ProgressNotifier.notifyProgressMessage("Planning activities...");
        int i = 0;
        int h = 0;
        for (Group household : households) {
            planActivities(household);
            int current1 = current = current + 16;
            ProgressNotifier.notifyProgress(current1 / total);
            ProgressNotifier.notifyProgressMessage("Planning activities... Household " + ++h + " of " + households.size());
            if (i++ > Constants.AGENDA_MAX_AGENTS_WITH_AGENDAS) {
                break;
            }
        }

        // Optimize activities.
        ProgressNotifier.notifyProgressMessage("Optimizing activities...");
        DebugPrinter.println("\n\n\n");
        i = 0;
        h = 0;
        for (Group household : households) {
            optimizeActivities(household);
            int current1 = current = current + 2;
            ProgressNotifier.notifyProgress(current1 / total);
            ProgressNotifier.notifyProgressMessage("Optimizing activities... Household " + ++h + " of " + households.size());
            if (i++ > Constants.AGENDA_MAX_AGENTS_WITH_AGENDAS) {
                break;
            }
        }

        // Show a sample of a number of agendas.
        // TODO Move to logger.
        int sampleSize = DEBUG_NUM_SAMPLE_AGENDAS;
        if (sampleSize != 0) {
            System.out.println("\n\nSome sample agendas follow.\n");
            for (Group household : households) {
                for (Agent agent : household) {
                    if (RandomNumber.nextDouble() < 0.1) {
                        if (agent.getAgenda() != null && agent.getAgenda().size() > 0) {
                            // find agendas with joint activities to test them
                            Set<Agent> agentsWithCommonActivities = agent.getAgentsWithCommonActivities();
                            if (agentsWithCommonActivities.size() > 1) {
                                System.out.println("\n\nAgent " + agent + " has joint activities, showing all agendas.\n");
                                for (Agent a : agentsWithCommonActivities) {
                                    System.out.println(a + "\n---");
                                    System.out.println(createOverviewAgenda(a));
                                }
                            } else {
                                System.out.println("\n\nAgent " + agent + " has no joint activities, showing only this agent's agenda.\n---");
                                System.out.println(createOverviewAgenda(agent));
                            }
                            if (--sampleSize == 0) {
                                break;
                            }
                        }
                    }
                }
            }
        }

        // Show a summary of possible activities that have been successfully transformed into planned activities. Or not.
        // TODO Move to a logger.
        System.out.println("\n\n" +
                TextUtils.addSpacesToString("Summary of successes and failures in planning", 50) +
                TextUtils.addSpacesToString("Success", 8) +
                TextUtils.addSpacesToString("Fail", 8) +
                TextUtils.addSpacesToString("Total", 8));
        for (PossibleActivity pa : successesAndFailures.keySet()) {
            Tuple<Integer, Integer> sf = successesAndFailures.get(pa);
            int s = sf.getFirst();
            int f = sf.getSecond();
            System.out.println(
                    TextUtils.addSpacesToString(pa, 50) +
                            TextUtils.addSpacesToString(s, 8) +
                            TextUtils.addSpacesToString(f, 8) +
                            TextUtils.addSpacesToString(s + f, 8));
        }

        // Show a summary of planned activities. This includes walking activities.
        // TODO Move to a log or output.
        HashMap<String, Integer> summary = new HashMap<>();
        for (Group household : households) {
            for (Agent agent : household) {
                for (Activity activity : agent.getAgenda()) {
                    if (summary.containsKey(activity.getName())) {
                        summary.put(activity.getName(), summary.get(activity.getName()) + 1);
                    } else {
                        summary.put(activity.getName(), 1);
                    }
                }
            }
        }
        System.out.println("\n\nOccurrences for each activity:");
        ArrayList<String> sortedActivities = new ArrayList<>(summary.keySet());
        Collections.sort(sortedActivities);
        for (String activity : sortedActivities) {
            System.out.format("%s: %d%n", TextUtils.addSpacesToString(activity, 30), summary.get(activity));
        }

        // Show status: number of agents that stay at home.
        // TODO Move to a logger.
        int numStayAtHomeAgents = 0, numAgents = 0;
        for (Group household : households)
            for (Agent agent : household) {
                Vertex house = agent.getHouse();
                boolean agendaOnlyAtHome = true;
                for (Activity activity : agent.getAgenda()) {
                    if (!(activity.getStartLocation().equals(house) && activity.getEndLocation().equals(house))) {
                        agendaOnlyAtHome = false;
                        break;
                    }
                }
                if (agendaOnlyAtHome) {
                    numStayAtHomeAgents++;
                }
                numAgents++;
            }
        System.out.println("\n\nStay-at-home agents: " + numStayAtHomeAgents + " of " + numAgents);

        if (DEBUG_QUIT_WHEN_DONE_MAKING_AGENDAS) {
            System.exit(0);
        }
    }

    private Map<String, Double> createOverviewMultipliers() {
        Map<String, Double> overview = new TreeMap<>();
        for (Agent agent : activityProbabilities.keySet()) {
            ActivityLikelihoodMap activityLikelihoodMap = activityProbabilities.get(agent);
            Set<PossibleActivity> possibleActivities = activityLikelihoodMap.getPossibleActivities();
            for (PossibleActivity possibleActivity : possibleActivities) {
                double likelihood = activityLikelihoodMap.getLikelihood(possibleActivity);
                String paS = possibleActivity.toString();
                Double multiplier = overview.get(paS);
                if (multiplier == null) {
                    multiplier = likelihood;
                } else {
                    multiplier = multiplier + likelihood;
                }
                overview.put(paS, multiplier);
            }
        }
        return overview;
    }

    @SuppressWarnings("unchecked")
    private TreeMap<String, Integer> createOverviewCapacities() {
        HashMap<Class<? extends LocationFunction>, Integer> count = new HashMap<>();
        for (Area a : environment.getWorld().getAreas()) {
            List<LocationFunction> functions = a.getFunctions();
            for (LocationFunction function : functions) {
                int capacity = function.getCapacity();
                if (capacity > 0) {
                    Class<? extends LocationFunction> fClass = function.getClass();
                    createOverviewCapacities_update(count, capacity, fClass);
                    // Also count the capacity for all the superclasses.
                    Set<Class<? extends LocationFunction>> superclasses = SemanticLibrary.getInstance().listSemanticSuperclasses(fClass);
                    for (Class<? extends LocationFunction> superclass : superclasses) {
                        createOverviewCapacities_update(count, capacity, superclass);
                    }
                }
            }

        }
        TreeMap<String, Integer> overview = new TreeMap<>();
        Set<PossibleActivity> allActivities = dayOfWeek.keySet();
        for (PossibleActivity activity : allActivities) {
            Class<? extends LocationFunction>[] possibleLocationFunctions = activity.getPossibleLocationFunctions();
            int countFS = 0;
            for (Class<? extends LocationFunction> possibleLocationFunction : possibleLocationFunctions) {
                Integer countF = count.get(possibleLocationFunction);
                if (countF != null) {
                    if (countF == Integer.MAX_VALUE || countFS == Integer.MAX_VALUE) {
                        countFS = Integer.MAX_VALUE;
                    } else {
                        countFS += countF;
                    }
                }
            }
            overview.put(activity.toString(), countFS);
        }
        return overview;
    }

    private void createOverviewCapacities_update(HashMap<Class<? extends LocationFunction>, Integer> count, int capacity, Class<? extends LocationFunction> fClass) {
        Integer countF = count.get(fClass);
        if (countF == null) {
            countF = capacity;
        } else if (countF == Integer.MAX_VALUE || capacity == Integer.MAX_VALUE) {
            countF = Integer.MAX_VALUE;
        } else {
            countF += capacity;
        }
        count.put(fClass, countF);
    }

    private void applyMultipliers(Agent agent) {
        ActivityLikelihoodMap agentProbabilities = dayOfWeek.initializeLikelihoods(agent);
        for (IMultiplier multiplier : multipliers) {
            if (multiplier != null) { // It is possible if we chose e.g. defaults.
                multiplier.applyMultipliers(agent, agentProbabilities);
            }
        }
        activityProbabilities.put(agent, agentProbabilities);
    }

    private void planActivities(Group household) {

        // Create the priority maps.
        // priority -> #participants -> agent -> activity[]
        SortedMap<Integer, SortedMap<Integer, HashMap<Agent, List<PossibleActivity>>>> prioritizedActivities = new TreeMap<>();
        for (Agent agent : household) {
            ActivityLikelihoodMap activityLikelihoodMap = activityProbabilities.get(agent);

            DebugPrinter.println("Agent: " + agent);
            DebugPrinter.println("Possible activities: " + activityLikelihoodMap);

            for (PossibleActivity possibleActivity : activityLikelihoodMap.getPossibleActivities()) {

                // Look up priority.
                final double priority = possibleActivity.getPriority();
                int priorityInt = (int) (100 * (1 - priority)); // Round-off errors if we use doubles; reverse so standard sort works.
                SortedMap<Integer, HashMap<Agent, List<PossibleActivity>>> activitiesGivenPriority = prioritizedActivities.get(priorityInt);
                if (activitiesGivenPriority == null) {
                    activitiesGivenPriority = new TreeMap<>();
                    prioritizedActivities.put(priorityInt, activitiesGivenPriority);
                }

                // Look up number of participants.
                int numParticipants = possibleActivity.getNumberAgentsInvolved(agent);
                if (numParticipants != 0) {
                    numParticipants = Integer.MAX_VALUE - numParticipants; // Reverse so standard sort works.
                    HashMap<Agent, List<PossibleActivity>> activitiesGivenPriorityAndNumParticipants = activitiesGivenPriority.get(numParticipants);
                    if (activitiesGivenPriorityAndNumParticipants == null) {
                        activitiesGivenPriorityAndNumParticipants = new HashMap<>();
                        activitiesGivenPriority.put(numParticipants, activitiesGivenPriorityAndNumParticipants);
                    }

                    // Look up possible activities.
                    List<PossibleActivity> agentPossibleActivities = activitiesGivenPriorityAndNumParticipants.get(agent);
                    if (agentPossibleActivities == null) {
                        agentPossibleActivities = new ArrayList<>();
                        activitiesGivenPriorityAndNumParticipants.put(agent, agentPossibleActivities);
                    }
                    agentPossibleActivities.add(possibleActivity);
                }
            }

            DebugPrinter.println("Prioritized activities: " + prioritizedActivities);
        }

        // Iterate through priorities: the most important activities first.
        for (int priorityInt : prioritizedActivities.keySet()) {
            SortedMap<Integer, HashMap<Agent, List<PossibleActivity>>> activitiesGivenPriority = prioritizedActivities.get(priorityInt);

            // Iterate through number of participants: the activities with the most participants first.
            for (int numParticipants : activitiesGivenPriority.keySet()) {
                final HashMap<Agent, List<PossibleActivity>> possibleActivitiesWithPriority = activitiesGivenPriority.get(numParticipants);

                // Iterate through agents that will get an activity.
                for (Agent agent : possibleActivitiesWithPriority.keySet()) {
                    final List<PossibleActivity> possibleActivities = possibleActivitiesWithPriority.get(agent);
                    final ActivityLikelihoodMap likelihoods = activityProbabilities.get(agent);

                    DebugPrinter.println("Priority   : " + priorityInt);
                    DebugPrinter.println("#Particip  : " + (Integer.MAX_VALUE - numParticipants));
                    DebugPrinter.println("Agent      : " + agent);
                    DebugPrinter.println("Likelihoods: " + likelihoods);

                    // Iterate through possible activities.
                    for (int i = possibleActivities.size() - 1; !possibleActivities.isEmpty(); i--) {
                        int index = RandomNumber.nextInt(possibleActivities.size());
                        PossibleActivity possibleActivity = possibleActivities.remove(index);

                        DebugPrinter.println("* Planning activity: " + possibleActivity);

                        double threshold = RandomNumber.nextDouble();

                        DebugPrinter.println("  Threshold and likelihood: " + threshold + " < " + likelihoods.get(possibleActivity));

                        if (threshold < likelihoods.get(possibleActivity)) {
                            EnumMap<PossibleActivity.Index, Activity> activities = possibleActivity.createActivities(agent, environment);
                            if (activities != null && activities.get(PossibleActivity.Index.ACTIVITY) != null && activities.get(PossibleActivity.Index.ACTIVITY).getParticipants().size() != 0) {

                                DebugPrinter.println("  Created activity: " + activities);
                                addSuccess(possibleActivity);

                                for (Activity a : activities.values()) {
                                    writeInAgenda(a);
                                }

                                DebugPrinter.println("  Agenda is now: \n---\n" + createOverviewAgenda(agent) + "---");

                                // Make sure none of the agents involved do this activity again today.
                                // TODO It is currently not possible to do an activity twice per day. ...
                                // If we remove this restriction, we have a side effect: e.g. if we force a parent to be present for
                                // dinner with a child, the parent may very well decide to have dinner a second time on the same day.
                                Activity plannedActivity = activities.get(PossibleActivity.Index.ACTIVITY);
                                Group participants = plannedActivity.getParticipants();
                                for (Agent participant : participants) { // For anyone involved...
                                    ActivityLikelihoodMap activityLikelihoodMap = activityProbabilities.get(participant);
                                    activityLikelihoodMap.setLikelihoodsToZero(possibleActivity.getClass()); // ... the activity is no longer possible.
                                }
                            } else {
                                addFailure(possibleActivity); // We mean failure as in wanting to do it but not being able to.
                            }
                        }
                    }
                }
            }
        }
    }

    private void optimizeActivities(Group household) {
        for (Agent agent : household) {

            // First, optimize pairs of non-moving as well as pairs of moving activities.
            List<Activity> currentAgenda = agent.getAgenda();
            DebugPrinter.println("\n\nBEFORE TUPLE OPTIMIZING:\n" + createOverviewAgenda(agent) + "\n");
            for (int i = 0; i < currentAgenda.size() - 1; i++) {
                optimizeActivityPair(currentAgenda, i);
            }
            List<Activity> newAgenda = new ArrayList<>();
            for (Activity activity : currentAgenda) {
                if (activity != null) {
                    newAgenda.add(activity);
                }
            }
            agent.getAgenda().clear();
            agent.getAgenda().addAll(newAgenda);

            // Second, optimize triplets with a move in the middle to time the move such that the gap is smallest.
            currentAgenda = agent.getAgenda();
            DebugPrinter.println("\n\nBEFORE TRIPLE OPTIMIZING:\n" + createOverviewAgenda(agent) + "\n");
            for (int i = 1; i < currentAgenda.size() - 1; i++) {
                optimizeActivityTriple(currentAgenda.get(i - 1), currentAgenda.get(i), currentAgenda.get(i + 1));
            }
            DebugPrinter.println("\n\nOPTIMIZED AGENDA:\n" + createOverviewAgenda(agent) + "\n");
        }
    }

    private void optimizeActivityPair(List<Activity> agenda, int firstIndex) {

        Activity activity1 = agenda.get(firstIndex);
        Activity activity2 = agenda.get(firstIndex + 1);
        if (activity1 == null || activity2 == null) {
            return;
        }

        DebugPrinter.println("\nActivities before optimizing: - " + activity1);
        DebugPrinter.println("                              - " + activity2);

        // Only modify activities with one participant; otherwise,
        // we start snowballing across agenda's of different agents.
        boolean firstActivityCanBeModified = activity1.getParticipants().size() == 1;
        boolean secondActivityCanBeModified = activity2.getParticipants().size() == 1;

        // Don't modify anything that has more participants because of snowballing.
        if (!firstActivityCanBeModified && !secondActivityCanBeModified) {
            // Nothing needed here.
        }

        // Two non-moving activities can perhaps be planned closer together.
        else if (!activity1.isMoving() && !activity2.isMoving()) {
            if (activity1.getEndTime().compareTo(activity2.getStartTime()) < 0) {

                DebugPrinter.println("We can try to move two static activities closer together");

                optimizeActivityGap(activity1, activity2, 0, firstActivityCanBeModified, secondActivityCanBeModified);

                DebugPrinter.println("Activities after  optimizing: - " + activity1);
                DebugPrinter.println("                              - " + activity2);
            }
        }

        // Two moving activities can be combined into one.
        else if (activity1.isMoving() && activity2.isMoving()) {
            if (firstActivityCanBeModified && secondActivityCanBeModified) {

                DebugPrinter.println("We can merge two moving activities");

                // Rather cumbersome way of correctly estimating the new end time for the activity.
                double a1pathLengthInM = environment.getWorld().getPathLengthInM(activity1.getStartLocation().getPoint(), activity1.getEndLocation().getPoint());
                long a1durationInNs = activity1.getEndTime().getNanos() - activity1.getStartTime().getNanos();
                double newPathLengthInM = environment.getWorld().getPathLengthInM(activity1.getStartLocation().getPoint(), activity2.getEndLocation().getPoint());
                long newDurationInNs = (long) ((newPathLengthInM / a1pathLengthInM) * a1durationInNs);
                Time newEndTime = activity1.getStartTime().incrementByMinutes(0);
                newEndTime.increment(newDurationInNs);
                // Create a new movement activity, delete the two old ones.
                agenda.set(firstIndex, new BasicMovementActivity(activity1.getPossibleActivity(), environment, activity1.getStartLocation(), activity1.getStartTime(), activity2.getEndLocation(), newEndTime, activity1.getParticipants(), false));
                agenda.set(firstIndex + 1, null);

                DebugPrinter.println("Activity   after  optimizing: - " + activity1);
            }
        }
    }

    private void optimizeActivityTriple(Activity activity1, Activity activity2, Activity activity3) {

        DebugPrinter.println("\nActivities before optimizing: - " + activity1);
        DebugPrinter.println("                              - " + activity2);
        DebugPrinter.println("                              - " + activity3);

        // Only modify activities with one participant; otherwise,
        // we start snowballing across agenda's of different agents.
        boolean firstActivityCanBeModified = activity1.getParticipants().size() == 1;
        boolean secondActivityCanBeModified = activity2.getParticipants().size() == 1;
        boolean thirdActivityCanBeModified = activity3.getParticipants().size() == 1;

        // We now know that it is also the SAME participant.
        Agent agent = activity1.getParticipants().get(0);

        // Don't modify anything that has more participants because of snowballing.
        if (!firstActivityCanBeModified && !secondActivityCanBeModified && !thirdActivityCanBeModified) {
            // Nothing needed here.
        }

        // Only optimize activities when a move is between two stationary activities.
        else if (activity1.isMoving() || !activity2.isMoving() || activity3.isMoving()) {
            // Nothing needed here.
        }

        // There is something to optimize! Try to move the moving activity right in between the stationary ones.
        else if (secondActivityCanBeModified) {

            DebugPrinter.println("We can move a movement activity around.");

            // First, move the stationary activities closer together.
            long activity2DurationNs = activity2.getEndTime().getNanos() - activity2.getStartTime().getNanos();
            optimizeActivityGap(activity1, activity3, activity2DurationNs, firstActivityCanBeModified, thirdActivityCanBeModified);

            // Fit the movement activity in between.
            long newGapSizeNs = activity3.getStartTime().getNanos() - activity1.getEndTime().getNanos();

            // Stay at home as long as possible, if possible. (We don't want people standing on the street doing nothing.)
            boolean moveAfterPrevious = RandomNumber.nextDouble() > 0.5; // Move immediately after activity 1, or immediately before 2?
            if (activity2.startsAtHomeFor(agent)) {
                moveAfterPrevious = false;
                DebugPrinter.println("The agent starts moving at home. Stay at home as long as possible.");
            } else if (activity2.endsAtHomeFor(agent)) {
                moveAfterPrevious = true;
                DebugPrinter.println("The agent ends up moving at home. Go home as soon as possible.");
            } else {
                DebugPrinter.println("The agent moves from a location that is not at home to another such location.");
            }
            DebugPrinter.println("Planning the movement activity directly " + (moveAfterPrevious ? "after the first" : "before the third") + " activity.");
            long delayMovementNs = moveAfterPrevious ? 0 : newGapSizeNs - activity2DurationNs;
            activity2.setStartTime(new Time(activity1.getEndTime().getNanos() + delayMovementNs));
            activity2.setEndTime(new Time(activity1.getEndTime().getNanos() + delayMovementNs + activity2DurationNs));

            DebugPrinter.println("Activities after  optimizing: - " + activity1);
            DebugPrinter.println("                              - " + activity2);
            DebugPrinter.println("                              - " + activity3);
        }

        // There is something to optimize, but the moving activity must remain where it is.
        else {

            DebugPrinter.println("We can adjust gaps around a movement activity");

            optimizeActivityGap(activity1, activity2, 0, firstActivityCanBeModified, secondActivityCanBeModified);
            optimizeActivityGap(activity2, activity3, 0, secondActivityCanBeModified, thirdActivityCanBeModified);

            DebugPrinter.println("Activities after  optimizing: - " + activity1);
            DebugPrinter.println("                              - " + activity2);
            DebugPrinter.println("                              - " + activity3);
        }
    }

    private void optimizeActivityGap(Activity activity1, Activity activity2, long requiredGapSizeNs, boolean firstActivityCanBeModified, boolean secondActivityCanBeModified) {

        // Determine the smallest size of the gap.
        Time a1end = firstActivityCanBeModified ? activity1.getLatestPossibleEndTime() : activity1.getEndTime();
        Time a2start = secondActivityCanBeModified ? activity2.getEarliestPossibleStartTime() : activity2.getStartTime();
        long minGapSizeNs = a2start.getNanos() - a1end.getNanos();

        // Keep a gap bigger than the minimal gap required, if necessary.
        if (minGapSizeNs >= requiredGapSizeNs) {
            if (firstActivityCanBeModified && !a1end.equals(activity1.getEndTime())) {
                activity1.setEndTime(a1end);
            }
            if (secondActivityCanBeModified && !a2start.equals(activity2.getStartTime())) {
                activity2.setStartTime(a2start);
            }
        }

        // Increase the gap if the current gap is smaller than the minimal gap required.
        else if (minGapSizeNs < requiredGapSizeNs) {
            long addToGapNs = requiredGapSizeNs - minGapSizeNs;

            // Determine where to increase the gap.
            long gapSizeToAddToFirstActivityNs = 0;
            long gapSizeToAddToSecondActivityNs = 0;

            // Both activities can be modified.
            if (firstActivityCanBeModified && secondActivityCanBeModified) {
                // TODO At the moment a gap between activities is filled by randomly extending the activities on both sides. ...
                // This may be suboptimal given maximum durations.
                gapSizeToAddToFirstActivityNs = (long) (RandomNumber.nextDouble() * addToGapNs);
                gapSizeToAddToSecondActivityNs = addToGapNs - gapSizeToAddToFirstActivityNs;
            }

            // Only the first activity can be modified.
            else if (firstActivityCanBeModified) {
                gapSizeToAddToFirstActivityNs = addToGapNs;
            }

            // Only the second activity can be modified.
            else if (secondActivityCanBeModified) { // And not first.
                gapSizeToAddToSecondActivityNs = addToGapNs;
            }

            // Modify the activities if possible and needed.
            if (gapSizeToAddToFirstActivityNs != 0) {
                activity1.setEndTime(new Time(Math.min(a1end.getNanos() - gapSizeToAddToFirstActivityNs, activity1.getLatestPossibleEndTime().getNanos())));
            }
            if (gapSizeToAddToSecondActivityNs != 0) {
                activity2.setStartTime(new Time(Math.max(a2start.getNanos() + gapSizeToAddToSecondActivityNs, activity2.getEarliestPossibleStartTime().getNanos())));
            }
        }
    }

    private String createOverviewAgenda(Agent agent) {
        String s = "";
        final List<Activity> agenda = agent.getAgenda();
        for (Activity activity : agenda) {
            s = s + (TextUtils.addSpacesToString(activity.getName(), 30)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getParticipants(), 40)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getStartTime(), 10)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getStartLocation().getPoint(), 20)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getStartLocation().getArea().getFunctions(), 30)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getEndTime(), 10)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getEndLocation().getPoint(), 20)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getEndLocation().getArea().getFunctions(), 30)) + "| ";
            s = s + (TextUtils.addSpacesToString(activity.getParticipants(), 30));
            s = s + "\n";
        }
        return s;
    }

    private void writeInAgenda(Activity activity) {

        // Put it in everyone's agenda.
        for (Agent agent : activity.getParticipants()) {
            List<Activity> agenda = agent.getAgenda();

            // Insert at right place in the agenda if the agenda is empty or it is the latest activity.
            if (agenda.isEmpty() || activity.compareTo(agenda.get(agenda.size() - 1)) > 0) {
                agenda.add(activity);
            }

            // Insert at right place in the agenda if not empty or somewhere in between.
            else {
                for (int i = 0; i < agenda.size(); ++i) {
                    if (activity.compareTo(agenda.get(i)) < 0) {
                        agenda.add(i, activity);
                        break;
                    }
                }
            }
        }
    }
}


text:
Proteinlab - UTEM y Claudio Paredes

Ganadores en la categoría WEAREABLES con la colección "M2M or Imitation of Nature"

Felicitaciones a todo el equipo de ProteinLab - UTEM y a Claudio Paredes

ProteinLab presents M2M collection at AltaRoma 2019

Desde el 24 al 27 de Enero de 2019, en la ciudad de Roma, Italia se desarrollará el evento "Digital Fashion Week" en el contexto de la Semana de la Alta Moda de Roma. En este contexto, el proyecto de Diseño de Vestuario y Tecnologías Digitales
            denominado "M2M or Imitation of Nature", realizado en conjunto entre ProteinLab UTEM y el diseñador de vestuario Claudio Paredes ha sido seleccionado para presentar sus 12 looks que incluyen impresión 3D, corte Láser y Electrónica.

Este proyecto fue seleccionado en el concurso "Digital Made", de la fundación del mismo nombre en conjunto con AltaRoma (www.altaroma.it), las dos son organizaciones italianas enfocadas al diseño y la tecnología.

AltaRoma

Collection M2M

M2M or Imitation of Nature, es un proyecto colaborativo en Diseño, Moda y Tecnología que se desarrolló durante nueve meses entre ProteinLab UTEM y el diseñador de vestuario Claudio Paredes. La colección integra el uso de las herramientas de
            fabricación digital tales como impresión 3D, corte láser, y electrónica embebida que aporta ProteinLab en armonía con las técnicas tradicionales de confección y diseño de vestuario aportadas por Claudio Paredes.

        <button class="btn btn-outline-dark">Conoce más sobre este proyecto.</button>

La colección M2M se presentó por primera vez en un desfile desarrollado en el Hall Central de la sede UTEM de Dieciocho 390, Santiago en el mes de Mayo del 2017. Además, se exhibió en Agosto del mismo año en el evento de clausura de la Feria Internacional
            de FabLabs FAB13, desarrollado en el Centro Cultural Gabriela Mistral GAM.

El objetivo de este proyecto es explorar las potencialidades de la unión de moda y tecnología a través del uso de técnicas de diseño y desarrollo de alta costura tradicional, en combinación de las tecnologías de fabricación digital y electrónica
            interactiva. Tecnologías como el corte láser, permiten la aplicación de diseños, texturas y patrones dinámicos y complejos directamente sobre la tela, así como la impresión 3D facilita la creación de elementos biomiméticos los cuales se integran
            a las prendas.

Para el lograr el éxito de este proyecto ha sido clave el trabajo interdisciplinario y colaborativo con los Departamentos de Diseño, Electricidad e Informática y el apoyo de la Vicerrectoría de Transferencia Tecnología y Extensión.

Siguenos en Instagram.

Haz click sobre las imagenes y ve nuestro perfil.

Equipo desarrollador de la colección M2M

redpajama_set_name: RedPajamaGithub


text:
namespace Ab {

/// Push an element onto the back of the vector.
/// @returns a reference to the new element.
///
template <typename T, typename A, typename... Args>
T& push(std::vector<T, A>& vector, Args&&... args) {
	vector.emplace_back(std::forward<Args>(args)...);
	return vector.back();
}

/// Pop a value from the back of a vector, and return it.
///
template <typename T, typename A>
T pop(std::vector<T, A>& vector) {
	T value(std::move(vector.back()));
	vector.pop_back();
	return value;
}

} // namespace Ab

#endif // AB_VECTORUTILITIES_HPP_


text:
@class BugsnagConfiguration;

NS_ASSUME_NONNULL_BEGIN

static NSString * const BSGNotificationBreadcrumbsMessageAppWillTerminate = @"App Will Terminate";

BSG_OBJC_DIRECT_MEMBERS
@interface BSGNotificationBreadcrumbs : NSObject

#pragma mark Initializers

- (instancetype)initWithConfiguration:(BugsnagConfiguration *)configuration
                       breadcrumbSink:(id<BSGBreadcrumbSink>)breadcrumbSink NS_DESIGNATED_INITIALIZER;

- (instancetype)init UNAVAILABLE_ATTRIBUTE;

#pragma mark Properties

@property (nonatomic) BugsnagConfiguration *configuration;

@property (weak, nonatomic) id<BSGBreadcrumbSink> breadcrumbSink;

@property (nonatomic) NSNotificationCenter *notificationCenter;

@property (nonatomic) NSNotificationCenter *workspaceNotificationCenter;

#pragma mark Methods

/// Starts observing the default notifications.
- (void)start;

/// Starts observing notifications with the given name and adds a "state" breadcrumbs when received.
- (void)startListeningForStateChangeNotification:(NSNotificationName)notificationName;

- (NSString *)messageForNotificationName:(NSNotificationName)name;

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/CPTNumericData.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/CPTNumericData</TokenIdentifier>
			<Abstract type="html">	@category CPTNumericData(TypeConversion)
	@brief Type conversion methods for CPTNumericData.</Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<NodeRef refid="33"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setData:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (copy, readonly) NSData *data</Declaration>

			<Anchor>//api/name/data</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/data</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (copy, readonly) NSData *data</Declaration>

			<Anchor>//api/name/data</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setBytes:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) const void *bytes</Declaration>

			<Anchor>//api/name/bytes</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/bytes</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) const void *bytes</Declaration>

			<Anchor>//api/name/bytes</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setLength:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) NSUInteger length</Declaration>

			<Anchor>//api/name/length</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/length</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) NSUInteger length</Declaration>

			<Anchor>//api/name/length</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setDataType:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (assign, readonly) CPTNumericDataType dataType</Declaration>

			<Anchor>//api/name/dataType</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/dataType</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (assign, readonly) CPTNumericDataType dataType</Declaration>

			<Anchor>//api/name/dataType</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setDataTypeFormat:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) CPTDataTypeFormat dataTypeFormat</Declaration>

			<Anchor>//api/name/dataTypeFormat</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/dataTypeFormat</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) CPTDataTypeFormat dataTypeFormat</Declaration>

			<Anchor>//api/name/dataTypeFormat</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setSampleBytes:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) size_t sampleBytes</Declaration>

			<Anchor>//api/name/sampleBytes</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/sampleBytes</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) size_t sampleBytes</Declaration>

			<Anchor>//api/name/sampleBytes</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setByteOrder:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) CFByteOrder byteOrder</Declaration>

			<Anchor>//api/name/byteOrder</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/byteOrder</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) CFByteOrder byteOrder</Declaration>

			<Anchor>//api/name/byteOrder</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setShape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (copy, readonly) NSArray *shape</Declaration>

			<Anchor>//api/name/shape</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/shape</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (copy, readonly) NSArray *shape</Declaration>

			<Anchor>//api/name/shape</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setNumberOfDimensions:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) NSUInteger numberOfDimensions</Declaration>

			<Anchor>//api/name/numberOfDimensions</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/numberOfDimensions</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) NSUInteger numberOfDimensions</Declaration>

			<Anchor>//api/name/numberOfDimensions</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/setNumberOfSamples:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) NSUInteger numberOfSamples</Declaration>

			<Anchor>//api/name/numberOfSamples</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/CPTNumericData/numberOfSamples</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>@property (readonly) NSUInteger numberOfSamples</Declaration>

			<Anchor>//api/name/numberOfSamples</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/CPTNumericData/numericDataWithData:dataType:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>+ (CPTNumericData *)numericDataWithData:(NSData *)newData dataType:(CPTNumericDataType)newDataType shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/numericDataWithData:dataType:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/CPTNumericData/numericDataWithData:dataTypeString:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>+ (CPTNumericData *)numericDataWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/numericDataWithData:dataTypeString:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/CPTNumericData/numericDataWithArray:dataType:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>+ (CPTNumericData *)numericDataWithArray:(NSArray *)newData dataType:(CPTNumericDataType)newDataType shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/numericDataWithArray:dataType:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/CPTNumericData/numericDataWithArray:dataTypeString:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>+ (CPTNumericData *)numericDataWithArray:(NSArray *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/numericDataWithArray:dataTypeString:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/initWithData:dataType:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (id)initWithData:(NSData *)newData dataType:(CPTNumericDataType)newDataType shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/initWithData:dataType:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/initWithData:dataTypeString:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (id)initWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/initWithData:dataTypeString:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/initWithArray:dataType:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (id)initWithArray:(NSArray *)newData dataType:(CPTNumericDataType)newDataType shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/initWithArray:dataType:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/initWithArray:dataTypeString:shape:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (id)initWithArray:(NSArray *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray</Declaration>

			<Anchor>//api/name/initWithArray:dataTypeString:shape:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/samplePointer:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (void *)samplePointer:(NSUInteger)sample</Declaration>

			<Anchor>//api/name/samplePointer:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/sampleValue:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (NSNumber *)sampleValue:(NSUInteger)sample</Declaration>

			<Anchor>//api/name/sampleValue:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/sampleArray</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData.h</DeclaredIn>

			<Declaration>- (NSArray *)sampleArray</Declaration>

			<Anchor>//api/name/sampleArray</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/dataByConvertingToDataType:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData+TypeConversion.h</DeclaredIn>

			<Declaration>- (CPTNumericData *)dataByConvertingToDataType:(CPTNumericDataType)newDataType</Declaration>

			<Anchor>//api/name/dataByConvertingToDataType:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/dataByConvertingToType:sampleBytes:byteOrder:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData+TypeConversion.h</DeclaredIn>

			<Declaration>- (CPTNumericData *)dataByConvertingToType:(CPTDataTypeFormat)newDataType sampleBytes:(size_t)newSampleBytes byteOrder:(CFByteOrder)newByteOrder</Declaration>

			<Anchor>//api/name/dataByConvertingToType:sampleBytes:byteOrder:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/convertData:dataType:toData:dataType:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData+TypeConversion.h</DeclaredIn>

			<Declaration>- (void)convertData:(NSData *)sourceData dataType:(CPTNumericDataType *)sourceDataType toData:(NSMutableData *)destData dataType:(CPTNumericDataType *)destDataType</Declaration>

			<Anchor>//api/name/convertData:dataType:toData:dataType:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/CPTNumericData/swapByteOrderForData:sampleSize:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CPTNumericData+TypeConversion.h</DeclaredIn>

			<Declaration>- (void)swapByteOrderForData:(NSMutableData *)sourceData sampleSize:(size_t)sampleSize</Declaration>

			<Anchor>//api/name/swapByteOrderForData:sampleSize:</Anchor>
		</Token>

	</File>
</Tokens>


text:
import {NgModule, ModuleWithProviders} from '@angular/core';
import {NGB_COLLAPSE_DIRECTIVES} from './collapse';

@NgModule({declarations: NGB_COLLAPSE_DIRECTIVES, exports: NGB_COLLAPSE_DIRECTIVES})
export class NgbCollapseModule {
  static forRoot(): ModuleWithProviders { return {ngModule: NgbCollapseModule, providers: []}; }
}


text:
(function (app) {
    app.value('globalVariables',
        {
            APPNAME: 'mockngApp',
            serviceName: 'mockng',
            scopeStr: '$scope',
            rootScopeStr: '$rootScope'
        });
})(angular.module('mockngApp'));


text:
package org.vaadin.teemusa.beangrid.client;

import com.vaadin.client.extensions.AbstractExtensionConnector;
import com.vaadin.client.widgets.Grid;

import elemental.json.JsonObject;

public abstract class BeanGridExtensionConnector extends AbstractExtensionConnector {

	@Override
	public BeanGridConnector getParent() {
		return (BeanGridConnector) super.getParent();
	}

	public Grid<JsonObject> getGrid() {
		return getParent().getWidget();
	}
}


text:
/*
 * mylist.h
 *
 *  Created on: 28/09/2013
 *      Author: Luis Alonso Murillo Rojas
 */

#ifndef MYLIST_H_
#define MYLIST_H_

#define EMPTY_LIST      -1

typedef struct list_group_s list_group;
typedef struct list_m listMutex;

/**
 *This is an implementation of a disjoint list of integers.
 *After creating the list_group one can create disjoint lists of
 *these integers. The integers range from zero to the parameter @size
 *pecified in the init_list_group();
 *
 *There are two ways to add remove elements from the lists. In the first
 *an element can only be added to a list with @create_new_element()
 *and then moved between the different lists with remove and add functions,
 *or the move_element function, and when finished, use delete_from_list.
 *This method keeps a heap for all the free indices, so when you create new
 *element, its index is the least unused index.
 *
 *Otherwise, one may use only the remove and add function, without touching
 *the create_new_element, and delete_from_list, to add and remove indices
 *without the heap. After using this method, do not call
 *create_new_element or delete_from_list.
 *
 *When finished with the list of group use close_list_group to free
 *the memory.
 *
 *NOTICE: none of he function check if the parameters are valid.
 *When calling a function, it is up to the user to check if the index
 *is in bounds, the pointers are not NULL, etc.
 */

/**
 *Creates the new list_group of size @size and return it in the first
 *parameter
 *
 *In case of memory allocation problem, return -1
 *Otherwise returns 0
 */
int init_list_group(list_group** l, int size);

/**
 *Close the list group l that was opened using init_list_group
 */
void close_list_group(list_group* l);

/**
 *Creates a new list for the specified list_group
 *
 *In case of memory allocation problem return -1
 *On success returns 0
 */
int create_new_list(list_group* group, listMutex** l);

/**
 *Closes the list in parameter, and move all its indices to the heap
 *of free indices
 */
void close_list(listMutex* l);

/**
 *Creates a new element (take it out from the free heap)
 *with the least unused index and return it
 *
 *if there are no more free elements to create, return -1
 */
int create_new_element(list_group* group);

/**
 *Remove the element of specified index from the list.
 *this function DOES NOT add it back to free indices heap. use it if you want
 *for example to add it afterwards to another list
 *
 *Return -1 in case the specified index doesn't belong to that group
 *on success return 0
 */
int remove_from_list(listMutex* l, int index);

/**
 *Same as remove_from_list, but after removed, the index is added
 *to the heap, so one cannot use add_* functions afterwards
 *
 *Return -1 in case the specified index doesn't belong to that group
 *on success return 0
 */
int delete_from_list(listMutex* l, int index);

/**
 *Add the specified index to the end of this list
 */
void add_tail(listMutex* l, int index);

/**
 *Add the specified index to the start of this list
 *
 *This function automatically advances the head of the list to the new item
 */
void add_head(listMutex* l, int index);

/**
 *Add the specified index to the list in order. This function
 *assume that the list in parameter is ordered, otherwise bad things
 *can happen (...)
 */
void add_ordered(listMutex* l, int index);

/**
 *Move an element from one list to the end the other
 */
void move_element(listMutex* from, listMutex* to, int index);

/**
 *Return the first element in this list
 *
 *If the list is empty, returns EMPTY_LIST
 */
int get_element(listMutex* l);

/**
 *Advances the head of the list, and return the next element
 *
 *If the list is empty, returns EMPTY_LIST
 */
int next_element(listMutex* l);

/**
 *Go back one element with the head of the list, and return it
 *
 *If the list is empty, returns EMPTY_LIST
 */
int previous_element(listMutex* l);

/**
 *Prints the indices in this list
 */
void print_list(listMutex* l);

/**
 *returns the list size
 */
int get_list_size(listMutex* l);

/**
 *return the number of free indices left
 */
int get_list_free_size(list_group* l);

/**
 *Return the list which the index in parameter belongs to, or null
 *if it is unused
 */
listMutex* get_list(list_group* group, int index);

#endif /* MYLIST_H_ */


text:
import { combineReducers } from 'redux';
import tweet from './tweet';

export default combineReducers({
  tweet,
});


text:
package org.apache.cassandra.db;

import java.util.Arrays;
import java.util.Random;

import com.google.common.collect.ImmutableSet;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.dht.ByteOrderedPartitioner;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.dht.OrderPreservingPartitioner;
import org.apache.cassandra.dht.RandomPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.assertj.core.api.Assertions;
import org.mockito.Mockito;
import org.quicktheories.core.Gen;
import org.quicktheories.impl.Constraint;

import static org.assertj.core.api.Assertions.assertThat;
import static org.quicktheories.QuickTheory.qt;

public class ColumnFamilyStoreMBeanTest
{
    @BeforeClass
    public static void setup()
    {
        // can't use client due to the fact thread pools startup and fail due to config issues
        DatabaseDescriptor.daemonInitialization();
    }

    @Test
    public void testToTokenRangesMurmur3Partitioner()
    {
        testToTokenRanges(Murmur3Partitioner.instance);
    }

    @Test
    public void testToTokenRangesRandomPartitioner()
    {
        testToTokenRanges(RandomPartitioner.instance);
    }

    @Test
    public void testToTokenRangesOrderPreservingPartitioner()
    {
        testToTokenRanges(OrderPreservingPartitioner.instance);
    }

    @Test
    public void testToTokenRangesByteOrderedPartitioner()
    {
        testToTokenRanges(ByteOrderedPartitioner.instance);
    }

    @Test
    public void testInvalidateTokenRangesFormat()
    {
        ColumnFamilyStore store = Mockito.mock(ColumnFamilyStore.class);
        Mockito.doCallRealMethod().when(store).forceCompactionForTokenRanges(Mockito.any());
        IPartitioner previous = DatabaseDescriptor.getPartitioner();
        try
        {
            DatabaseDescriptor.setPartitionerUnsafe(ByteOrderedPartitioner.instance);

            for (String s : Arrays.asList("testing", "t1:", ":t2", "spaces should not have an impact"))
                Assertions.assertThatThrownBy(() -> store.forceCompactionForTokenRanges(s))
                          .hasMessageStartingWith(String.format("Unable to parse token range %s;", s));
        }
        finally
        {
            DatabaseDescriptor.setPartitionerUnsafe(previous);
        }

    }

    private static void testToTokenRanges(IPartitioner partitioner)
    {
        Token.TokenFactory tokenFactory = partitioner.getTokenFactory();
        Gen<Token> tokenGen = tokenGen(partitioner);
        qt().forAll(tokenGen, tokenGen)
            .checkAssert((left, right) ->
                         assertThat(ColumnFamilyStore.toTokenRanges(partitioner, toString(tokenFactory, left, right)))
                         .isEqualTo(ImmutableSet.of(new Range<>(left, right))));
    }

    private static String toString(Token.TokenFactory tokenFactory, Token left, Token right)
    {
        return tokenFactory.toString(left) + ColumnFamilyStore.TOKEN_DELIMITER + tokenFactory.toString(right);
    }

    private static Gen<Token> tokenGen(IPartitioner partitioner)
    {
        // Random and RandomSource can not share the same seed, but there is a workaround...
        // use RandomSource to generate a seed!
        return rs -> partitioner.getRandomToken(new Random(rs.next(Constraint.none())));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable LoopCanBeConvertedToQuery

namespace NetFusion.Common.Extensions.Tasks
{
    /// <summary>
    /// Extension methods for executing a collection of invokers that call an asynchronous method that will complete
    /// in the future.  When awaiting a collection of Tasks and there is an exception, only the exception  that first
    /// occurred will be thrown.  However, all of the exceptions can be accessed since they are associated with their
    /// task.  These methods generalize the calling a collection of tasks and returning a collection of all exceptions.
    /// </summary>
    public static class TaskExtensions
    {
        /// <summary>
        /// Executes a list of invokers that call an asynchronous method and returns a collection of objects
        /// storing the invoker and its associated task.
        /// </summary>
        /// <typeparam name="TInvoker">The type of object making the asynchronous call.</typeparam>
        /// <typeparam name="TInput">The type of value passed to all invokers.</typeparam>
        /// <param name="invokers">List of objects that will invoke an asynchronous method.</param>
        /// <param name="input">Reference to object passed to all invokers.</param>
        /// <param name="invoke">The delegate invoked that will call the asynchronous method on passed invoker.</param>
        /// <returns>Collection of invokers and associated task.</returns>
        public static TaskListItem<TInvoker>[] Invoke<TInvoker, TInput>(this IEnumerable<TInvoker> invokers,
            TInput input,
            Func<TInvoker, TInput, Task> invoke)
            where TInvoker : class
        {
            if (invokers == null) throw new ArgumentNullException(nameof(invokers));
            if (input == null) throw new ArgumentNullException(nameof(input));
            if (invoke == null) throw new ArgumentNullException(nameof(invoke));

            var taskList = new List<TaskListItem<TInvoker>>();
            foreach(TInvoker invoker in invokers)
            {
                Task task = invoke(invoker, input);
                taskList.Add(new TaskListItem<TInvoker>(task, invoker));
            }
            return taskList.ToArray();
        }

        /// <summary>
        /// Executes a list of invokers that call an asynchronous method and returns a collection of objects
        /// storing  the invoker and its associated task.
        /// </summary>
        /// <typeparam name="TInvoker">The type of object making the asynchronous call.</typeparam>
        /// <typeparam name="TInput">The type of value passed to all invokers.</typeparam>
        /// <param name="invokers">List of objects that will invoke an asynchronous method.</param>
        /// <param name="input">Reference to object passed to all invokers.</param>
        /// <param name="invoke">The delegate invoked that will call the asynchronous method on passed invoker.</param>
        /// <param name="cancellationToken">Cancellation token used to signal if the asynchronous task should be canceled.</param>
        /// <returns>Collection of invokers and associated task.</returns>
        public static TaskListItem<TInvoker>[] Invoke<TInvoker, TInput>(this IEnumerable<TInvoker> invokers,
            TInput input,
            Func<TInvoker, TInput, CancellationToken, Task> invoke,
            CancellationToken cancellationToken)
            where TInvoker : class
        {
            if (invokers == null) throw new ArgumentNullException(nameof(invokers));
            if (input == null) throw new ArgumentNullException(nameof(input));
            if (invoke == null) throw new ArgumentNullException(nameof(invoke));

            var taskList = new List<TaskListItem<TInvoker>>();
            foreach (TInvoker invoker in invokers)
            {
                Task task = invoke(invoker, input, cancellationToken);
                taskList.Add(new TaskListItem<TInvoker>(task, invoker));
            }
            return taskList.ToArray();
        }

        /// <summary>
        /// Given a task list, returns a task that will be completed when all task list items have completed.
        /// </summary>
        /// <typeparam name="TInvoker">The type of object making the asynchronous call.</typeparam>
        /// <param name="taskList">Collection of task item results.</param>
        /// <returns>Task that will completed when all task list items complete.</returns>
        public static Task WhenAll<TInvoker>(this TaskListItem<TInvoker>[] taskList)
            where TInvoker : class
        {
            if (taskList == null) throw new ArgumentNullException(nameof(taskList));
            return Task.WhenAll(taskList.Select(i => i.Task));
        }

        /// <summary>
        /// Given a task list, returns a collection of exceptions for each task item that resulted
        /// in an exception.  The caller is  responsible for creating the exception that should be
        /// returned.
        /// </summary>
        /// <typeparam name="TInvoker">The type of object making the asynchronous call.</typeparam>
        /// <typeparam name="TEx">The type of exception returned for each failed task.</typeparam>
        /// <param name="taskList">The task list to check for failed tasks.</param>
        /// <param name="exFactory">Delegate used to create exception for failed task.</param>
        /// <returns>Collection of custom exceptions for each failed task.</returns>
        public static TEx[] GetExceptions<TInvoker, TEx>(this TaskListItem<TInvoker>[] taskList,
            Func<TaskListItem<TInvoker>, TEx> exFactory)
            where TInvoker : class
            where TEx : Exception
        {
            if (taskList == null) throw new ArgumentNullException(nameof(taskList));
            if (exFactory == null) throw new ArgumentNullException(nameof(exFactory));

            var exceptions = new List<TEx>(taskList.Length);

            foreach (var task in taskList.Where(pt => pt.Task.Exception != null))
            {
                exceptions.Add(exFactory(task));
            }
            return exceptions.ToArray();
        }
    }
}


text:
namespace blink { class WebGraphicsContext3D; }

namespace webkit {
namespace gpu {

class ContextProviderWebContext : public cc::ContextProvider {
 public:
  virtual blink::WebGraphicsContext3D* WebContext3D() = 0;

 protected:
  ~ContextProviderWebContext() override {}
};

}  // namespace gpu
}  // namespace webkit

#endif  // WEBKIT_COMMON_GPU_CONTEXT_PROVIDER_WEB_CONTEXT_H_


text:
package io.fabric8.openshift;

import io.fabric8.commons.DeleteEntity;
import io.fabric8.commons.ReadyEntity;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.BuildConfigBuilder;
import io.fabric8.openshift.api.model.BuildConfigList;
import io.fabric8.openshift.client.OpenShiftClient;
import org.arquillian.cube.kubernetes.api.Session;
import org.arquillian.cube.openshift.impl.requirement.RequiresOpenshift;
import org.arquillian.cube.requirement.ArquillianConditionalRunner;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.concurrent.TimeUnit;

import static junit.framework.TestCase.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@RunWith(ArquillianConditionalRunner.class)
@RequiresOpenshift
public class BuildConfigIT {
  @ArquillianResource
  OpenShiftClient client;

  @ArquillianResource
  Session session;

  private BuildConfig buildConfig1, buildConfig2;

  private String currentNamespace;

  @Before
  public void init() {
    currentNamespace = session.getNamespace();
    buildConfig1 = new BuildConfigBuilder()
      .withNewMetadata().withName("bc1").endMetadata()
      .withNewSpec()
      .addNewTrigger()
      .withType("GitHub")
      .withNewGithub()
      .withSecret("secret101")
      .endGithub()
      .endTrigger()
      .addNewTrigger()
      .withType("Generic")
      .withNewGeneric()
      .withSecret("secret101")
      .endGeneric()
      .endTrigger()
      .addNewTrigger()
      .withType("ImageChange")
      .endTrigger()
      .withNewSource()
      .withType("Git")
      .withNewGit()
      .withUri("https://github.com/openshift/ruby-hello-world")
      .endGit()
      .withDockerfile("FROM openshift/ruby-22-centos7\\nUSER example")
      .endSource()
      .withNewStrategy()
      .withType("Source")
      .withNewSourceStrategy()
      .withNewFrom()
      .withKind("ImageStreamTag")
      .withName("origin-ruby-sample:latest")
      .endFrom()
      .endSourceStrategy()
      .endStrategy()
      .withNewOutput()
      .withNewTo()
      .withKind("ImageStreamTag")
      .withName("origin-ruby-sample:latest")
      .endTo()
      .endOutput()
      .withNewPostCommit()
      .withScript("bundle exec rake test")
      .endPostCommit()
      .endSpec()
      .build();

    client.buildConfigs().inNamespace(currentNamespace).createOrReplace(buildConfig1);
  }

  @Test
  public void load() {
    BuildConfig aBuildConfig = client.buildConfigs().inNamespace(currentNamespace)
      .load(getClass().getResourceAsStream("/test-buildconfig.yml")).get();
    assertThat(aBuildConfig).isNotNull();
    assertEquals("ruby-sample-build", aBuildConfig.getMetadata().getName());
  }

  @Test
  public void get() {
    assertNotNull(client.buildConfigs().inNamespace(currentNamespace).withName("bc1").get());
  }

  @Test
  public void list() {
    BuildConfigList bcList = client.buildConfigs().inNamespace(currentNamespace).list();
    assertThat(bcList).isNotNull();
    assertEquals(1, bcList.getItems().size());
  }

  @Test
  public void update() {
    ReadyEntity<BuildConfig> buildConfigReady = new ReadyEntity<>(BuildConfig.class, client, "bc1", currentNamespace);
    buildConfig1 = client.buildConfigs().inNamespace(currentNamespace).withName("bc1").edit()
      .editSpec().withFailedBuildsHistoryLimit(5).endSpec().done();
    await().atMost(30, TimeUnit.SECONDS).until(buildConfigReady);
    assertEquals(5, buildConfig1.getSpec().getFailedBuildsHistoryLimit().intValue());
  }

  @Test
  public void delete() {
    ReadyEntity<BuildConfig> buildConfigReady = new ReadyEntity<>(BuildConfig.class, client, "bc1", currentNamespace);
    await().atMost(30, TimeUnit.SECONDS).until(buildConfigReady);
    boolean bDeleted = client.buildConfigs().inNamespace(currentNamespace).withName("bc1").delete();
    assertTrue(bDeleted);
  }

  @After
  public void cleanup() throws InterruptedException {
    if (client.buildConfigs().list().getItems().size() != 0) {
      client.buildConfigs().inNamespace(currentNamespace).delete();
    }

    DeleteEntity<BuildConfig> buildConfigDelete = new DeleteEntity<>(BuildConfig.class, client, "bc1", currentNamespace);
    await().atMost(30, TimeUnit.SECONDS).until(buildConfigDelete);
  }
}


text:
using System;
using System.IO;
using ObjUnity3D;
using UnityEngine;

namespace ModTools.Utils
{
    public static class MeshUtil
    {
        public static void DumpMeshToOBJ(Mesh mesh, string fileName)
        {
            fileName = Path.Combine(Path.Combine(Application.dataPath, "Import"), fileName);
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            Mesh meshToDump = mesh;

            if (!mesh.isReadable)
            {
                Log.Warning($"Mesh \"{mesh.name}\" is marked as non-readable, running workaround..");

                try
                {
                    // copy the relevant data to the temporary mesh
                    meshToDump = new Mesh
                    {
                        vertices = mesh.vertices,
                        colors = mesh.colors,
                        triangles = mesh.triangles,
                        normals = mesh.normals,
                        tangents = mesh.tangents
                    };
                    meshToDump.RecalculateBounds();
                    meshToDump.Optimize();
                }
                catch (Exception ex)
                {
                    Log.Error($"Workaround failed with error - {ex.Message}");
                    return;
                }
            }

            try
            {
                using (var stream = new FileStream(fileName, FileMode.Create))
                {
                    OBJLoader.ExportOBJ(meshToDump.EncodeOBJ(), stream);
                    stream.Close();
                    Log.Warning($"Dumped mesh \"{((Mesh) mesh).name}\" to \"{fileName}\"");
                }
            }
            catch (Exception ex)
            {
                Log.Error($"There was an error while trying to dump mesh \"{mesh.name}\" - {ex.Message}");
            }
        }
    }
}


text:
/** @file gem_set_tiling_vs_blt.c
 *
 * Testcase: Check for proper synchronization of tiling changes vs. tiled gpu
 * access
 *
 * The blitter on gen3 and earlier needs properly set up fences. Which also
 * means that for untiled blits we may not set up a fence before that blt has
 * finished.
 *
 * Current kernels have a bug there, but it's pretty hard to hit because you
 * need:
 * - a blt on an untiled object which is aligned correctly for tiling.
 * - a set_tiling to switch that object to tiling
 * - another blt without any intervening cpu access that uses this object.
 *
 * Testcase has been extended to also check tiled->untiled and tiled->tiled
 * transitions (i.e. changing stride).
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <inttypes.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdbool.h>
#include "drm.h"
#include "ioctl_wrappers.h"
#include "drmtest.h"
#include "intel_bufmgr.h"
#include "intel_batchbuffer.h"
#include "intel_chipset.h"
#include "intel_io.h"

IGT_TEST_DESCRIPTION("Check for proper synchronization of tiling changes vs."
		     " tiled gpu access.");

static drm_intel_bufmgr *bufmgr;
struct intel_batchbuffer *batch;
uint32_t devid;

#define TEST_SIZE (1024*1024)
#define TEST_STRIDE (4*1024)
#define TEST_HEIGHT(stride)	(TEST_SIZE/(stride))
#define TEST_WIDTH(stride)	((stride)/4)

uint32_t data[TEST_SIZE/4];

static void do_test(uint32_t tiling, unsigned stride,
		    uint32_t tiling_after, unsigned stride_after)
{
	drm_intel_bo *busy_bo, *test_bo, *target_bo;
	int i, ret;
	uint32_t *ptr;
	uint32_t test_bo_handle;
	uint32_t blt_stride, blt_bits;
	bool tiling_changed = false;

	igt_info("filling ring .. ");
	busy_bo = drm_intel_bo_alloc(bufmgr, "busy bo bo", 16*1024*1024, 4096);

	for (i = 0; i < 250; i++) {
		BLIT_COPY_BATCH_START(0);
		OUT_BATCH((3 << 24) | /* 32 bits */
			  (0xcc << 16) | /* copy ROP */
			  2*1024*4);
		OUT_BATCH(0 << 16 | 1024);
		OUT_BATCH((2048) << 16 | (2048));
		OUT_RELOC_FENCED(busy_bo, I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER, 0);
		OUT_BATCH(0 << 16 | 0);
		OUT_BATCH(2*1024*4);
		OUT_RELOC_FENCED(busy_bo, I915_GEM_DOMAIN_RENDER, 0, 0);
		ADVANCE_BATCH();

		if (batch->gen >= 6) {
			BEGIN_BATCH(3, 0);
			OUT_BATCH(XY_SETUP_CLIP_BLT_CMD);
			OUT_BATCH(0);
			OUT_BATCH(0);
			ADVANCE_BATCH();
		}
	}
	intel_batchbuffer_flush(batch);

	igt_info("playing tricks .. ");
	/* first allocate the target so it gets out of the way of playing funky
	 * tricks */
	target_bo = drm_intel_bo_alloc(bufmgr, "target bo", TEST_SIZE, 4096);

	/* allocate buffer with parameters _after_ transition we want to check
	 * and touch it, so that it's properly aligned in the gtt. */
	test_bo = drm_intel_bo_alloc(bufmgr, "tiled busy bo", TEST_SIZE, 4096);
	test_bo_handle = test_bo->handle;
	ret = drm_intel_bo_set_tiling(test_bo, &tiling_after, stride_after);
	igt_assert(ret == 0);
	drm_intel_gem_bo_map_gtt(test_bo);
	ptr = test_bo->virtual;
	*ptr = 0;
	ptr = NULL;
	drm_intel_gem_bo_unmap_gtt(test_bo);

	drm_intel_bo_unreference(test_bo);

	test_bo = NULL;

	/* note we need a bo bigger than batches, otherwise the buffer reuse
	 * trick will fail. */
	test_bo = drm_intel_bo_alloc(bufmgr, "busy bo", TEST_SIZE, 4096);
	/* double check that the reuse trick worked */
	igt_assert(test_bo_handle == test_bo->handle);

	test_bo_handle = test_bo->handle;
	/* ensure we have the right tiling before we start. */
	ret = drm_intel_bo_set_tiling(test_bo, &tiling, stride);
	igt_assert(ret == 0);

	if (tiling == I915_TILING_NONE) {
		drm_intel_bo_subdata(test_bo, 0, TEST_SIZE, data);
	} else {
		drm_intel_gem_bo_map_gtt(test_bo);
		ptr = test_bo->virtual;
		memcpy(ptr, data, TEST_SIZE);
		ptr = NULL;
		drm_intel_gem_bo_unmap_gtt(test_bo);
	}

	blt_stride = stride;
	blt_bits = 0;
	if (intel_gen(devid) >= 4 && tiling != I915_TILING_NONE) {
		blt_stride /= 4;
		blt_bits = XY_SRC_COPY_BLT_SRC_TILED;
	}

	BLIT_COPY_BATCH_START(blt_bits);
	OUT_BATCH((3 << 24) | /* 32 bits */
		  (0xcc << 16) | /* copy ROP */
		  stride);
	OUT_BATCH(0 << 16 | 0);
	OUT_BATCH((TEST_HEIGHT(stride)) << 16 | (TEST_WIDTH(stride)));
	OUT_RELOC_FENCED(target_bo, I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER, 0);
	OUT_BATCH(0 << 16 | 0);
	OUT_BATCH(blt_stride);
	OUT_RELOC_FENCED(test_bo, I915_GEM_DOMAIN_RENDER, 0, 0);
	ADVANCE_BATCH();
	intel_batchbuffer_flush(batch);

	drm_intel_bo_unreference(test_bo);

	test_bo = drm_intel_bo_alloc_for_render(bufmgr, "tiled busy bo", TEST_SIZE, 4096);
	/* double check that the reuse trick worked */
	igt_assert(test_bo_handle == test_bo->handle);
	ret = drm_intel_bo_set_tiling(test_bo, &tiling_after, stride_after);
	igt_assert(ret == 0);

	/* Note: We don't care about gen4+ here because the blitter doesn't use
	 * fences there. So not setting tiling flags on the tiled buffer is ok.
	 */
	BLIT_COPY_BATCH_START(0);
	OUT_BATCH((3 << 24) | /* 32 bits */
		  (0xcc << 16) | /* copy ROP */
		  stride_after);
	OUT_BATCH(0 << 16 | 0);
	OUT_BATCH((1) << 16 | (1));
	OUT_RELOC_FENCED(test_bo, I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER, 0);
	OUT_BATCH(0 << 16 | 0);
	OUT_BATCH(stride_after);
	OUT_RELOC_FENCED(test_bo, I915_GEM_DOMAIN_RENDER, 0, 0);
	ADVANCE_BATCH();
	intel_batchbuffer_flush(batch);

	/* Now try to trick the kernel the kernel into changing up the fencing
	 * too early. */

	igt_info("checking .. ");
	memset(data, 0, TEST_SIZE);
	drm_intel_bo_get_subdata(target_bo, 0, TEST_SIZE, data);
	for (i = 0; i < TEST_SIZE/4; i++)
		igt_assert(data[i] == i);

	/* check whether tiling on the test_bo actually changed. */
	drm_intel_gem_bo_map_gtt(test_bo);
	ptr = test_bo->virtual;
	for (i = 0; i < TEST_SIZE/4; i++)
		if (ptr[i] != data[i])
			tiling_changed = true;
	ptr = NULL;
	drm_intel_gem_bo_unmap_gtt(test_bo);
	igt_assert(tiling_changed);

	drm_intel_bo_unreference(test_bo);
	drm_intel_bo_unreference(target_bo);
	drm_intel_bo_unreference(busy_bo);
	igt_info("done\n");
}

int fd;

igt_main
{
	int i;
	uint32_t tiling, tiling_after;

	igt_skip_on_simulation();

	igt_fixture {
		for (i = 0; i < 1024*256; i++)
			data[i] = i;

		fd = drm_open_any();

		bufmgr = drm_intel_bufmgr_gem_init(fd, 4096);
		drm_intel_bufmgr_gem_enable_reuse(bufmgr);
		devid = intel_get_drm_devid(fd);
		batch = intel_batchbuffer_alloc(bufmgr, devid);
	}

	igt_subtest("untiled-to-tiled") {
		tiling = I915_TILING_NONE;
		tiling_after = I915_TILING_X;
		do_test(tiling, TEST_STRIDE, tiling_after, TEST_STRIDE);
		igt_assert(tiling == I915_TILING_NONE);
		igt_assert(tiling_after == I915_TILING_X);
	}

	igt_subtest("tiled-to-untiled") {
		tiling = I915_TILING_X;
		tiling_after = I915_TILING_NONE;
		do_test(tiling, TEST_STRIDE, tiling_after, TEST_STRIDE);
		igt_assert(tiling == I915_TILING_X);
		igt_assert(tiling_after == I915_TILING_NONE);
	}

	igt_subtest("tiled-to-tiled") {
		tiling = I915_TILING_X;
		tiling_after = I915_TILING_X;
		do_test(tiling, TEST_STRIDE/2, tiling_after, TEST_STRIDE);
		igt_assert(tiling == I915_TILING_X);
		igt_assert(tiling_after == I915_TILING_X);
	}
}


text:
$.editable.addInputType('geoAPILocalitiesEditable', {
	element: function(settings, original) {
		var input = $('<input />');
		if (settings.width  != 'none') { input.width(settings.width);  }
		if (settings.height != 'none') { input.height(settings.height); }
		input.attr('autocomplete','off');
		$(this).append(input);
		return(input);
	},
	plugin: function(settings, original) {
		$('input', this).css('min-width', '13em');
		$('input', this).autoComplete(settings.autoComplete);
	}
});


text:
if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    # We're in smart spawning mode.
    if forked
      # Re-establish redis connection
      require 'redis'
      config = YAML.safe_load(ERB.new(IO.read(Rails.root.join('config', 'redis.yml'))).result)[Rails.env].with_indifferent_access

      # The important two lines
      Redis.current.disconnect!
      Redis.current = begin
                        Redis.new(config.merge(thread_safe: true))
                      rescue StandardError
                        nil
                      end
      Resque.redis = Redis.current
      Resque.redis.namespace = "#{Hyrax.config.redis_namespace}:#{Rails.env}"
      Resque.redis&.client&.reconnect
    end
  end
else
  config = YAML.safe_load(ERB.new(IO.read(Rails.root.join('config', 'redis.yml'))).result)[Rails.env].with_indifferent_access
  require 'redis'
  Redis.current = begin
                    Redis.new(config.merge(thread_safe: true))
                  rescue StandardError
                    nil
                  end
end


text:
package com.funtl.framework.tencent.wechat.pay.protocol.closeorder;

import javax.xml.bind.annotation.XmlRootElement;

import com.funtl.framework.tencent.wechat.common.Config;

/**
 * 关闭订单请求对象
 *
参考开发文档

 *

 * Created by xuwen on 2015-12-13.
 */
@XmlRootElement(name = "xml")
public class CloseorderRequest {

	private String appid = Config.instance().getAppid();
	private String mch_id = Config.instance().getMchId();
	private String out_trade_no;
	private String nonce_str;
	private String sign;

	public String getAppid() {
		return appid;
	}

	public void setAppid(String appid) {
		this.appid = appid;
	}

	public String getMch_id() {
		return mch_id;
	}

	public void setMch_id(String mch_id) {
		this.mch_id = mch_id;
	}

	public String getOut_trade_no() {
		return out_trade_no;
	}

	public void setOut_trade_no(String out_trade_no) {
		this.out_trade_no = out_trade_no;
	}

	public String getNonce_str() {
		return nonce_str;
	}

	public void setNonce_str(String nonce_str) {
		this.nonce_str = nonce_str;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	@Override
	public String toString() {
		return "CloseorderRequest{" + "appid='" + appid + '\'' + ", mch_id='" + mch_id + '\'' + ", out_trade_no='" + out_trade_no + '\'' + ", nonce_str='" + nonce_str + '\'' + ", sign='" + sign + '\'' + '}';
	}
}