text:
package psymbolic.runtime.scheduler;

import lombok.Getter;
import lombok.Setter;
import psymbolic.runtime.machine.Machine;
import psymbolic.valuesummary.*;
import psymbolic.runtime.Concretizer;
import psymbolic.runtime.Message;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

public class Schedule implements Serializable {

    private final boolean useSleepSets;

    private Guard filter = Guard.constTrue();

    @Setter
    private int schedulerDepth = 0;
    @Setter
    private int schedulerChoiceDepth = 0;
    private int numBacktracks = 0;
    private int numDataBacktracks = 0;

    public void restrictFilter(Guard c) { filter = filter.and(c); }
    public void setFilter(Guard c) { filter = c; }
    public Guard getFilter() { return filter; }
    public void resetFilter() { filter = Guard.constTrue(); }

    public Choice newChoice() {
        return new Choice();
    }

    SetVS<VectorClockVS> sleepSet = new SetVS<>(Guard.constTrue());

    private static List<VectorClockVS> fullUniverseClocks (VectorClockVS vc) {
        List<GuardedValue<List<Object>>> concreteVals = Concretizer.getConcreteValues(vc.getUniverse(), x -> false, Concretizer::concretize, vc);
        List<VectorClockVS> res = new ArrayList<>();
        for (GuardedValue<List<Object>> gv : concreteVals) {
            if (gv.getValue().isEmpty()) continue;
            List<Object> list = gv.getValue();
            ListVS newList = new ListVS<>(Guard.constTrue());
            for (Object i : list) {
                newList = newList.add(new PrimitiveVS<>((Integer) i));
            }
            res.add(new VectorClockVS(newList));
        }
        return res;
    }

    private static VectorClockVS getVectorClockSent (PrimitiveVS<Machine> sender) {
        Message m = new Message().restrict(Guard.constFalse());
        for (GuardedValue<Machine> gv : sender.getGuardedValues()) {
            m = m.merge(gv.getValue().sendBuffer.peek(gv.getGuard()));
        }
        return m.getVectorClock();
    }

    public List<PrimitiveVS> filterSleep (List<PrimitiveVS> candidates) {
        if (!useSleepSets) return candidates;
        List<PrimitiveVS> filtered = candidates.stream().map(x -> x.restrict(sleepSet.contains(getVectorClockSent(x)).getGuardFor(true).not())).collect(Collectors.toList());
        return filtered;
    }

    public void unblock(VectorClockVS vc) {
        VectorClockVS toRemove = vc.restrict(sleepSet.getUniverse());
        sleepSet.remove(toRemove.restrict(sleepSet.contains(toRemove).getGuardFor(true)));
    }

    public class ChoiceState implements Serializable {
        @Getter
        private Map<Machine, List<ValueSummary>> machineStates;
        @Getter
        private Map<Class<? extends Machine>, PrimitiveVS<Integer>> machineCounters;

        public ChoiceState() {
            this(new HashMap<>(), new HashMap<>());
        }
        public ChoiceState(Map<Machine, List<ValueSummary>> ms, Map<Class<? extends Machine>, PrimitiveVS<Integer>> mc) {
            this.machineStates = new HashMap<>(ms);
            this.machineCounters = new HashMap<>(mc);
        }
        public void copy(Map<Machine, List<ValueSummary>> ms, Map<Class<? extends Machine>, PrimitiveVS<Integer>> mc) {
            this.machineStates = new HashMap<>(ms);
            this.machineCounters = new HashMap<>(mc);
        }
    }
    private ChoiceState schedulerState = new ChoiceState();

    public void setSchedulerState(Map<Machine, List<ValueSummary>> ms, Map<Class<? extends Machine>, PrimitiveVS<Integer>> mc) {
        schedulerState.copy(ms, mc);
    }

    public class Choice implements Serializable {
        @Getter
        PrimitiveVS<Machine> repeatSender = new PrimitiveVS<>();
        @Getter
        PrimitiveVS<Boolean> repeatBool = new PrimitiveVS<>();
        @Getter
        PrimitiveVS<Integer> repeatInt = new PrimitiveVS<>();
        @Getter
        PrimitiveVS<ValueSummary> repeatElement = new PrimitiveVS<>();
        @Getter
        List<PrimitiveVS<Machine>>  backtrackSender = new ArrayList<>();
        @Getter
        List<PrimitiveVS<Boolean>> backtrackBool = new ArrayList();
        @Getter
        List<PrimitiveVS<Integer>> backtrackInt = new ArrayList<>();
        @Getter
        List<ValueSummary> backtrackElement = new ArrayList<>();
        @Getter
        Guard handledUniverse = Guard.constFalse();
        @Getter
        int schedulerDepth = 0;
        @Getter
        int schedulerChoiceDepth = 0;
        @Getter
        ChoiceState choiceState = null;
        @Getter
        Guard filter = null;

        public Choice() {
        }

        /** Copy-constructor for Choice
         * @param old The Choice to copy
         */
        public Choice(Choice old) {
            repeatSender = new PrimitiveVS<>(old.repeatSender);
            repeatBool = new PrimitiveVS<>(old.repeatBool);
            repeatInt = new PrimitiveVS<>(old.repeatInt);
            repeatElement = new PrimitiveVS<>(old.repeatElement);
            backtrackSender = new ArrayList<>(old.backtrackSender);
            backtrackBool = new ArrayList<>(old.backtrackBool);
            backtrackInt = new ArrayList<>(old.backtrackInt);
            backtrackElement = new ArrayList<>(old.backtrackElement);
            handledUniverse = old.handledUniverse;
            schedulerDepth = old.schedulerDepth;
            schedulerChoiceDepth = old.schedulerChoiceDepth;
            choiceState = old.choiceState;
            filter = old.filter;
        }

        /**
         * Copy the Choice
         *
         * @return A new cloned copy of the Choice
         */
        public Choice getCopy() {
            return new Choice(this);
        }

        public ChoiceState copyState(ChoiceState state) {
            if (state == null)
                return null;
            return new ChoiceState(state.getMachineStates(), state.getMachineCounters());
        }

        public void storeState(int depth, int cdepth, ChoiceState state, Guard f) {
            schedulerDepth = depth;
            schedulerChoiceDepth = cdepth;
            choiceState = copyState(state);
            filter = f;
        }

        public int getNumChoicesExplored() {
            return repeatSender.getValues().size() +
                    repeatBool.getValues().size() +
                    repeatInt.getValues().size() +
                    repeatElement.getValues().size();
        }

        public Guard getRepeatUniverse() {
            return repeatSender.getUniverse().or(repeatBool.getUniverse().or(repeatInt.getUniverse().or(repeatElement.getUniverse())));
        }

        public Guard getBacktrackUniverse() {
            Guard senderUniverse = Guard.constFalse();
            for (PrimitiveVS<Machine> machine : backtrackSender) {
                senderUniverse = senderUniverse.or(machine.getUniverse());
            }
            for (PrimitiveVS<Boolean> bool : backtrackBool) {
                senderUniverse = senderUniverse.or(bool.getUniverse());
            }
            for (PrimitiveVS<Integer> integer : backtrackInt) {
                senderUniverse = senderUniverse.or(integer.getUniverse());
            }
            for (ValueSummary element : backtrackElement) {
                senderUniverse = senderUniverse.or(element.getUniverse());
            }
            return senderUniverse;
        }

        public boolean isRepeatEmpty() {
            return getRepeatUniverse().isFalse();
        }

        public boolean isBacktrackEmpty() {
            return isScheduleBacktrackEmpty() && isDataBacktrackEmpty();
        }

        public boolean isScheduleBacktrackEmpty() {
            return getBacktrackSender().isEmpty();
        }

        public boolean isDataBacktrackEmpty() {
            return getBacktrackBool().isEmpty() && getBacktrackInt().isEmpty() && getBacktrackElement().isEmpty();
        }

        public Choice restrict(Guard pc) {
            Choice c = newChoice();
            c.repeatSender = repeatSender.restrict(pc);
            c.repeatBool = repeatBool.restrict(pc);
            c.repeatInt = repeatInt.restrict(pc);
            c.repeatElement = repeatElement.restrict(pc);
            c.backtrackSender = backtrackSender.stream().map(x -> x.restrict(pc)).filter(x -> !x.isEmptyVS()).collect(Collectors.toList());
            c.backtrackBool = backtrackBool.stream().map(x -> x.restrict(pc)).filter(x -> !x.isEmptyVS()).collect(Collectors.toList());
            c.backtrackInt = backtrackInt.stream().map(x -> x.restrict(pc)).filter(x -> !x.isEmptyVS()).collect(Collectors.toList());
            c.backtrackElement = backtrackElement.stream().map(x -> x.restrict(pc)).filter(x -> !x.isEmptyVS()).collect(Collectors.toList());
            c.storeState(this.schedulerDepth, this.schedulerChoiceDepth, this.choiceState, this.filter);
            return c;
        }

        public void updateHandledUniverse(Guard update) {
            handledUniverse = handledUniverse.or(update);
        }

        public void addRepeatSender(PrimitiveVS<Machine> choice) {
            repeatSender = choice;
            if (!useSleepSets) return;
            Guard seen = Guard.constFalse();
            Guard choiceUniverse = choice.getUniverse();
            for (GuardedValue<Machine> gv : choice.getGuardedValues()) {
                Guard initCond = gv.getValue().sendBuffer.hasCreateMachineUnderGuard().getGuardFor(true);
                List<VectorClockVS> clks = fullUniverseClocks(gv.getValue().sendBuffer.peek(gv.getGuard().and(initCond.not())).getVectorClock());
                seen = seen.or(gv.getGuard());
                for (VectorClockVS clk : clks) {
                    // remove from sleep set:
                    Guard toRemoveGuard = sleepSet.contains(clk.restrict(sleepSet.getUniverse())).getGuardFor(true);
                    sleepSet = sleepSet.remove(clk.restrict(toRemoveGuard));
                    // add to sleep set:
                    sleepSet = sleepSet.add(clk.restrict(seen.not().and(choiceUniverse)));
                }
            }
        }

        public void addRepeatBool(PrimitiveVS<Boolean> choice) {
            repeatBool = choice;
        }

        public void addRepeatInt(PrimitiveVS<Integer> choice) {
            repeatInt = choice;
        }

        public void addRepeatElement(PrimitiveVS<ValueSummary> choice) {
            repeatElement = choice;
        }

        public void clearRepeatSender() {
            repeatSender = new PrimitiveVS<>();
        }

        public void clearRepeat() {
            repeatSender = new PrimitiveVS<>();
            repeatBool = new PrimitiveVS<>();
            repeatInt = new PrimitiveVS<>();
            repeatElement = new PrimitiveVS<>();
        }

        public void addBacktrackSender(PrimitiveVS<Machine> choice) { if (!choice.isEmptyVS()) backtrackSender.add(choice); }

        public void addBacktrackBool(PrimitiveVS<Boolean> choice) { if (!choice.isEmptyVS())  backtrackBool.add(choice); }

        public void addBacktrackInt(PrimitiveVS<Integer> choice) { if (!choice.isEmptyVS()) backtrackInt.add(choice); }

        public void addBacktrackElement(ValueSummary choice) { if (!choice.isEmptyVS()) backtrackElement.add(choice); }

        public void clearBacktrack() {
            backtrackSender = new ArrayList<>();
            backtrackBool = new ArrayList<>();
            backtrackInt = new ArrayList<>();
            backtrackElement = new ArrayList<>();
        }

        public void clear() {
            clearRepeat();
            clearBacktrack();
            handledUniverse = Guard.constFalse();
        }

    }

    private List<Choice> choices = new ArrayList<>();

    public List<Choice> getChoices() { return choices; }

    public void setChoices(List<Choice> c) { choices = c; }

    public Choice getChoice(int d) {
        return choices.get(d);
    }

    public void setChoice(int d, Choice choice) {
        choices.set(d, choice);
    }

    public void clearChoice(int d) {
        choices.get(d).clear();
    }

    public void setNumBacktracksInSchedule() {
        numBacktracks = 0;
        numDataBacktracks = 0;
        for (Choice backtrack : choices) {
            if (!backtrack.isBacktrackEmpty()) {
                numBacktracks++;
                if(!backtrack.isDataBacktrackEmpty()) {
                    numDataBacktracks++;
                }
            }
        }
    }

    public int getNumBacktracksInSchedule() {
        return numBacktracks;
    }

    public int getNumDataBacktracksInSchedule() {
        return numDataBacktracks;
    }

    public void addRepeatSender(PrimitiveVS<Machine> choice, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        choices.get(depth).addRepeatSender(choice);
    }

    public void addRepeatBool(PrimitiveVS<Boolean> choice, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        choices.get(depth).addRepeatBool(choice);
    }

    public void addRepeatInt(PrimitiveVS<Integer> choice, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        choices.get(depth).addRepeatInt(choice);
    }

    public void addRepeatElement(PrimitiveVS<ValueSummary> choice, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        choices.get(depth).addRepeatElement(choice);
    }

    public void addBacktrackSender(List<PrimitiveVS<Machine>> machines, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        if (machines.isEmpty()) {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, null, filter);
        } else {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, schedulerState, filter);
            numBacktracks++;
        }
        for (PrimitiveVS<Machine> choice : machines) {
            choices.get(depth).addBacktrackSender(choice);
        }
    }

    public void addBacktrackBool(List<PrimitiveVS<Boolean>> bools, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        if (bools.isEmpty()) {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, null, filter);
        } else {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, schedulerState, filter);
            numBacktracks++;
            numDataBacktracks++;
        }
        for (PrimitiveVS<Boolean> choice : bools) {
            choices.get(depth).addBacktrackBool(choice);
        }
    }

    public void addBacktrackInt(List<PrimitiveVS<Integer>> ints, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        if (ints.isEmpty()) {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, null, filter);
        } else {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, schedulerState, filter);
            numBacktracks++;
            numDataBacktracks++;
        }
        for (PrimitiveVS<Integer> choice : ints) {
            choices.get(depth).addBacktrackInt(choice);
        }
    }

    public void addBacktrackElement(List<ValueSummary> elements, int depth) {
        if (depth >= choices.size()) {
            choices.add(newChoice());
        }
        if (elements.isEmpty()) {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, null, filter);
        } else {
            choices.get(depth).storeState(schedulerDepth, schedulerChoiceDepth, schedulerState, filter);
            numBacktracks++;
            numDataBacktracks++;
        }
        for (ValueSummary choice : elements) {
            choices.get(depth).addBacktrackElement(choice);
        }
    }

    public PrimitiveVS<Machine> getRepeatSender(int depth) {
        return choices.get(depth).getRepeatSender();
    }

    public PrimitiveVS<Boolean> getRepeatBool(int depth) {
        return choices.get(depth).getRepeatBool();
    }

    public PrimitiveVS<Integer> getRepeatInt(int depth) {
        return choices.get(depth).getRepeatInt();
    }

    public PrimitiveVS<ValueSummary> getRepeatElement(int depth) {
        return choices.get(depth).getRepeatElement();
    }

    public List<PrimitiveVS<Machine>> getBacktrackSender(int depth) {
        return choices.get(depth).getBacktrackSender();
    }

    public List<PrimitiveVS<Boolean>> getBacktrackBool(int depth) {
        return choices.get(depth).getBacktrackBool();
    }

    public List<PrimitiveVS<Integer>> getBacktrackInt(int depth) {
        return choices.get(depth).getBacktrackInt();
    }

    public List<ValueSummary> getBacktrackElement(int depth) {
        return choices.get(depth).getBacktrackElement();
    }

    public void clearRepeat(int depth) {
        choices.get(depth).clearRepeat();
    }

    public void clearBacktrack(int depth) {
        choices.get(depth).clearBacktrack();
    }

    public void restrictFilterForDepth(int depth) {
        Choice choice = choices.get(depth);
        Guard repeat = choice.getRepeatUniverse();
        Guard backtrackOrHandled = choice.getBacktrackUniverse().or(choice.getHandledUniverse());
        restrictFilter(backtrackOrHandled.not().or(repeat.and(backtrackOrHandled)));
    }

    public int size() {
        return choices.size();
    }

    private Map<Class<? extends Machine>, ListVS<PrimitiveVS<Machine>>> createdMachines = new HashMap<>();
    private Set<Machine> machines = new HashSet<>();

    private Guard pc = Guard.constTrue();

    public Schedule() { this.useSleepSets = false; }

    public Schedule(boolean useSleepSets) {
        this.useSleepSets = useSleepSets;
    }

    private Schedule(List<Choice> choices,
                     Map<Class<? extends Machine>, ListVS<PrimitiveVS<Machine>>> createdMachines,
                     Set<Machine> machines,
                     Guard pc,
                     boolean useSleepSets) {
        this.choices = new ArrayList<>(choices);
        this.createdMachines = new HashMap<>(createdMachines);
        this.machines = new HashSet<>(machines);
        this.pc = pc;
        this.useSleepSets = useSleepSets;
    }

    public Set<Machine> getMachines() {
        return machines;
    }

    public Schedule guard(Guard pc) {
        List<Choice> newChoices = new ArrayList<>();
        for (Choice c : choices) {
            newChoices.add(c.restrict(pc));
        }
        return new Schedule(newChoices, createdMachines, machines, pc, useSleepSets);
    }

    public Schedule removeEmptyRepeat() {
        List<Choice> newChoices = new ArrayList<>();
        for (int i = 0; i < size(); i++) {
            if (!choices.get(i).isRepeatEmpty()) {
                newChoices.add(choices.get(i));
            }
        }
        return new Schedule(newChoices, createdMachines, machines, pc, useSleepSets);
    }

    public void makeMachine(Machine m, Guard pc) {
        PrimitiveVS<Machine> toAdd = new PrimitiveVS<>(m).restrict(pc);
        if (createdMachines.containsKey(m.getClass())) {
            createdMachines.put(m.getClass(), createdMachines.get(m.getClass()).add(toAdd));
        } else {
            createdMachines.put(m.getClass(), new ListVS<PrimitiveVS<Machine>>(Guard.constTrue()).add(toAdd));
        }
        machines.add(m);
    }

    public boolean hasMachine(Class<? extends Machine> type, PrimitiveVS<Integer> idx, Guard otherPc) {
        if (!createdMachines.containsKey(type)) return false;
        // TODO: may need fixing
        //ScheduleLogger.log("has machine of type");
        //ScheduleLogger.log(idx + " in range? " + createdMachines.get(type).inRange(idx).getGuard(false));
        if (!createdMachines.get(type).inRange(idx).getGuardFor(false).isFalse()) return false;
        PrimitiveVS<Machine> machines = createdMachines.get(type).get(idx);
        return !machines.restrict(pc).restrict(otherPc).getUniverse().isFalse();
    }

    public PrimitiveVS<Machine> getMachine(Class<? extends Machine> type, PrimitiveVS<Integer> idx) {
        PrimitiveVS<Machine> machines = createdMachines.get(type).get(idx);
        return machines.restrict(pc);
    }

    public Schedule getSingleSchedule() {
        Guard pc = Guard.constTrue();
        for (Choice choice : choices) {
            Choice guarded = choice.restrict(pc);
            PrimitiveVS<Machine> sender = guarded.getRepeatSender();
            if (sender.getGuardedValues().size() > 0) {
                pc = pc.and(sender.getGuardedValues().get(0).getGuard());
            } else {
                PrimitiveVS<Boolean> boolChoice = guarded.getRepeatBool();
                if (boolChoice.getGuardedValues().size() > 0) {
                    pc = pc.and(boolChoice.getGuardedValues().get(0).getGuard());
                } else {
                    PrimitiveVS<Integer> intChoice = guarded.getRepeatInt();
                    if (intChoice.getGuardedValues().size() > 0) {
                        pc = pc.and(intChoice.getGuardedValues().get(0).getGuard());
                    }
                    else {
                        PrimitiveVS<ValueSummary> elementChoice = guarded.getRepeatElement();
                        if (elementChoice.getGuardedValues().size() > 0) {
                            pc = pc.and(elementChoice.getGuardedValues().get(0).getGuard());
                        }
                    }
                }
            }
        }
        return this.guard(pc).removeEmptyRepeat();
    }

    public Guard getLengthCond(int size) {
        if (size == 0) return Guard.constFalse();
        return choices.get(size - 1).getRepeatUniverse();
    }
}


text:
'use strict';

var fs = require('fs');
var path = require('path');
var yaml = require('js-yaml');

var defaultDepPath = path.join(__dirname, '..', 'config', 'dependencies.yml');
var defaultApiPath = path.join(__dirname, '..', 'config', 'api_defaults.yml');

exports.defaults = {
  api: yaml.safeLoad(fs.readFileSync(defaultApiPath, 'utf8')),
  dependencies:  yaml.safeLoad(fs.readFileSync(defaultDepPath, 'utf8'))
}

redpajama_set_name: RedPajamaGithub


text:
package org.openhubframework.openhub.ri;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.openhubframework.openhub.ri.AbstractIntegrationTest.STUB_SERVER_PORT;

import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Rule;
import org.openhubframework.openhub.test.TestConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.TestPropertySource;

/**
 * Simple parent for integration tests.
 *
 * @author Karel Kovarik
 * @since 1.0.0
 */
@TestPropertySource(properties = {
        "stub.server.port = " + STUB_SERVER_PORT,
        "stub.server.url = localhost:${stub.server.port}",
        "test.camel.initAllRoutes = true"
})
@SpringBootTest(
        classes = {
                TestConfig.class,
                AbstractIntegrationTest.WebContextConfig.class
        },
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public abstract class AbstractIntegrationTest extends AbstractRITest {

    static final int STUB_SERVER_PORT = 17777;

    @LocalServerPort
    private int port;

    @Autowired
    protected TestRestTemplate testRestTemplate;

    @Value("${stub.server.port}")
    protected int stubServerPort;

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig()
            .port(STUB_SERVER_PORT));

    /**
     * Get port of embedded web context.
     *
     * @return the port.
     */
    protected int getPort() {
        return port;
    }

    /**
     * Get embedded web container base url.
     *
     * @return the url.
     */
    protected String getWebBaseUrl() {
        return "http://localhost:" + port;
    }

    /**
     * Configuration class to setup web context.
     */
    @ComponentScan(basePackages = {
            "org.openhubframework.openhub.web",
            "org.openhubframework.openhub.admin"
    })
    public static class WebContextConfig {
    }
}


text:
/**
 * License: Bullet3 license
 * Author: Avik De <avikde@gmail.com>
 */
#include <map>
#include <string>
#include <stdio.h>
#include "../Utils/b3Clock.h"
#include "SharedMemory/PhysicsClientC_API.h"
#include "Bullet3Common/b3Vector3.h"
#include "Bullet3Common/b3Quaternion.h"
#include "SharedMemory/SharedMemoryInProcessPhysicsC_API.h"

extern const int CONTROL_RATE;
const int CONTROL_RATE = 500;

// Bullet globals
b3PhysicsClientHandle kPhysClient = 0;
const b3Scalar FIXED_TIMESTEP = 1.0 / ((b3Scalar)CONTROL_RATE);
// temp vars used a lot
b3SharedMemoryCommandHandle command;
b3SharedMemoryStatusHandle statusHandle;
int statusType, ret;
b3JointInfo jointInfo;
b3JointSensorState state;
// test
int twojoint;
std::map<std::string, int> jointNameToId;

int main(int argc, char* argv[])
{
	kPhysClient = b3CreateInProcessPhysicsServerAndConnect(argc, argv);
	if (!kPhysClient)
		return -1;
	// visualizer
	command = b3InitConfigureOpenGLVisualizer(kPhysClient);
	b3ConfigureOpenGLVisualizerSetVisualizationFlags(command, COV_ENABLE_GUI, 0);
	b3SubmitClientCommandAndWaitStatus(kPhysClient, command);
	b3ConfigureOpenGLVisualizerSetVisualizationFlags(command, COV_ENABLE_SHADOWS, 0);
	b3SubmitClientCommandAndWaitStatus(kPhysClient, command);

	b3SetTimeOut(kPhysClient, 10);

	//syncBodies is only needed when connecting to an existing physics server that has already some bodies
	command = b3InitSyncBodyInfoCommand(kPhysClient);
	statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);
	statusType = b3GetStatusType(statusHandle);

	// set fixed time step
	command = b3InitPhysicsParamCommand(kPhysClient);
	ret = b3PhysicsParamSetTimeStep(command, FIXED_TIMESTEP);
	statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);
	ret = b3PhysicsParamSetRealTimeSimulation(command, false);
	statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);

	b3Assert(b3GetStatusType(statusHandle) == CMD_CLIENT_COMMAND_COMPLETED);

	// load test
	command = b3LoadUrdfCommandInit(kPhysClient, "TwoJointRobot_wo_fixedJoints.urdf");
	int flags = URDF_USE_INERTIA_FROM_FILE;
	b3LoadUrdfCommandSetFlags(command, flags);
	b3LoadUrdfCommandSetUseFixedBase(command, true);
	// q.setEulerZYX(0, 0, 0);
	// b3LoadUrdfCommandSetStartOrientation(command, q[0], q[1], q[2], q[3]);
	b3LoadUrdfCommandSetUseMultiBody(command, true);
	statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);
	statusType = b3GetStatusType(statusHandle);
	b3Assert(statusType == CMD_URDF_LOADING_COMPLETED);
	if (statusType == CMD_URDF_LOADING_COMPLETED)
	{
		twojoint = b3GetStatusBodyIndex(statusHandle);
	}

	//disable default linear/angular damping
	b3SharedMemoryCommandHandle command = b3InitChangeDynamicsInfo(kPhysClient);
	double linearDamping = 0;
	double angularDamping = 0;
	b3ChangeDynamicsInfoSetLinearDamping(command, twojoint, linearDamping);
	b3ChangeDynamicsInfoSetAngularDamping(command, twojoint, angularDamping);
	statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);

	int numJoints = b3GetNumJoints(kPhysClient, twojoint);
	printf("twojoint numjoints = %d\n", numJoints);
	// Loop through all joints
	for (int i = 0; i < numJoints; ++i)
	{
		b3GetJointInfo(kPhysClient, twojoint, i, &jointInfo);
		if (jointInfo.m_jointName[0])
		{
			jointNameToId[std::string(jointInfo.m_jointName)] = i;
		}
		else
		{
			continue;
		}
		// Reset before torque control - see #1459
		command = b3JointControlCommandInit2(kPhysClient, twojoint, CONTROL_MODE_VELOCITY);
		b3JointControlSetDesiredVelocity(command, jointInfo.m_uIndex, 0);
		b3JointControlSetMaximumForce(command, jointInfo.m_uIndex, 0);
		statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);
	}

	// loop
	unsigned long dtus1 = (unsigned long)1000000.0 * FIXED_TIMESTEP;
	double simTimeS = 0;
	double q[2], v[2];
	while (b3CanSubmitCommand(kPhysClient))
	{
		simTimeS += 0.000001 * dtus1;
		// apply some torque
		b3GetJointInfo(kPhysClient, twojoint, jointNameToId["joint_2"], &jointInfo);
		command = b3JointControlCommandInit2(kPhysClient, twojoint, CONTROL_MODE_TORQUE);
		b3JointControlSetDesiredForceTorque(command, jointInfo.m_uIndex, 0.5 * sin(10 * simTimeS));
		statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);

		// get joint values
		command = b3RequestActualStateCommandInit(kPhysClient, twojoint);
		statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, command);
		b3GetJointState(kPhysClient, statusHandle, jointNameToId["joint_1"], &state);
		q[0] = state.m_jointPosition;
		v[0] = state.m_jointVelocity;
		b3GetJointState(kPhysClient, statusHandle, jointNameToId["joint_2"], &state);
		q[1] = state.m_jointPosition;
		v[1] = state.m_jointVelocity;

		statusHandle = b3SubmitClientCommandAndWaitStatus(kPhysClient, b3InitStepSimulationCommand(kPhysClient));

		// debugging output
		printf("%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", simTimeS, q[0], q[1], v[0], v[1]);
		b3Clock::usleep(1000. * 1000. * FIXED_TIMESTEP);
	}
	b3DisconnectSharedMemory(kPhysClient);
	return 0;
}


text:
from rest_framework import serializers
from .models import Award, Badge

from utils.serializers import ObjectTypeModelSerializer

class BadgeSerializer(ObjectTypeModelSerializer):
    object_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Badge
        fields = (
            'id', 'name', 'slug', 'description', 'image', 'users_count', 'object_type'
        )

    def get_object_type(self, obj):
        return 'badge'

class AwardSerializer(ObjectTypeModelSerializer):
    object_type = serializers.SerializerMethodField(read_only=True)
    badge = BadgeSerializer(read_only=True)

    class Meta:
        model = Award
        fields = ('id', 'user',  'badge', 'awarded_at', 'object_type')

    def get_object_type(self, obj):
        return 'award'


text:
import * as React from "react";
import * as PropTypes from "prop-types";
import { listenTo, Component, handles, dispatch } from "../CarbonFlux";
import styled, {css} from "styled-components";
import { app } from "carbon-core";
import { FormattedMessage, defineMessages } from 'react-intl';
import * as cx from "classnames";
import appStore from "../AppStore";
import theme from "../theme";
import icons from "../theme-icons";
import Icon from "../components/Icon";

interface IModeSelectorProps extends IReactElementProps {

}

interface IModeSelectorState {
    activeMode?:string;
}

export default class ModeSelector extends Component<IModeSelectorProps, IModeSelectorState> {
    static contextTypes = {
        router: PropTypes.any,
        intl: PropTypes.object
    }

    constructor(props) {
        super(props);
        this.state = {
            activeMode: appStore.state.activeMode,
        }
    }

    @listenTo(appStore)
    onChange() {
        this.setState({
            activeMode: appStore.state.activeMode
        });
    }

    render() {
        return <ModeBar>
            {
                ['edit', 'prototype'].map((item) => {
                    return (
                        <ModeBarItem active={(item === this.state.activeMode)} key={item}
                            onClick={() => app.setMode(item)}>
                            {/* <SelectorIcon icon={icons['top_'+item]} active={(item === this.state.activeMode)}></SelectorIcon> */}
                            <Cap>
                                <FormattedMessage id={'mode.' + item} />
                            </Cap>
                            {(item === this.state.activeMode) && <SelectionIndicator/>}
                        </ModeBarItem>
                    )
                })
            }
        </ModeBar>;
    }
}

const SelectionIndicator = styled.div`
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    width:3px;
    background:${theme.accent};
`;

const ModeBar = styled.div`
    white-space:nowrap;
    position:relative;
    display:flex;
    align-items:center;
    flex-direction:column;
`;

const Cap = styled.div`
    position: relative;
`;

const ModeBarItem = styled.div<{active?:boolean}>`
    color: ${(props:any)=>props.active?theme.text_color:theme.text_inactive};
    font: ${theme.leadFont};
    position: relative;
    display: inline-flex;
    line-height:40px;
    writing-mode: vertical-lr;
    text-orientation: mixed;
    width:40px;
    margin: 20px 0;
    align-items:center;
    cursor:pointer;
    position:relative;
    transform: rotate(180deg);
    text-transform:uppercase;
   ;
`;


text:
package org.locationtech.geomesa.accumulo.data.tables

import java.util.Date

import com.google.common.base.Charsets
import com.google.common.collect.{ImmutableSet, ImmutableSortedSet}
import com.google.common.primitives.{Bytes, Longs, Shorts}
import com.vividsolutions.jts.geom._
import org.apache.accumulo.core.client.BatchDeleter
import org.apache.accumulo.core.client.admin.TableOperations
import org.apache.accumulo.core.conf.Property
import org.apache.accumulo.core.data.{Mutation, Value, Range => aRange}
import org.apache.hadoop.io.Text
import org.joda.time.{DateTime, DateTimeZone, Seconds, Weeks}
import org.locationtech.geomesa.accumulo.data.AccumuloFeatureWriter.{FeatureToMutations, FeatureToWrite}
import org.locationtech.geomesa.accumulo.data.EMPTY_TEXT
import org.locationtech.geomesa.curve.Z3SFC
import org.locationtech.geomesa.features.kryo.KryoFeatureSerializer
import org.locationtech.geomesa.utils.geotools.Conversions._
import org.locationtech.geomesa.utils.geotools.RichSimpleFeatureType.RichSimpleFeatureType
import org.locationtech.geomesa.utils.index.VisibilityLevel
import org.locationtech.sfcurve.zorder.Z3
import org.locationtech.sfcurve.zorder.Z3.ZPrefix
import org.opengis.feature.simple.SimpleFeatureType

import scala.collection.JavaConversions._

object Z3Table extends GeoMesaTable {

  val EPOCH = new DateTime(0) // min value we handle - 1970-01-01T00:00:00.000
  val EPOCH_END = EPOCH.plusSeconds(Int.MaxValue) // max value we can calculate - 2038-01-18T22:19:07.000
  val FULL_CF = new Text("F")
  val BIN_CF = new Text("B")
  val EMPTY_BYTES = Array.empty[Byte]
  val EMPTY_VALUE = new Value(EMPTY_BYTES)
  val NUM_SPLITS = 4 // can't be more than Byte.MaxValue (127)
  val SPLIT_ARRAYS = (0 until NUM_SPLITS).map(_.toByte).toArray.map(Array(_)).toSeq

  // the bytes of z we keep for complex geoms
  // 3 bytes is 15 bits of geometry (not including time bits and the first 2 bits which aren't used)
  // roughly equivalent to 3 digits of geohash (32^3 == 2^15) and ~78km resolution
  // (4 bytes is 20 bits, equivalent to 4 digits of geohash and ~20km resolution)
  // note: we also lose time resolution
  val GEOM_Z_NUM_BYTES = 3
  // mask for zeroing the last (8 - GEOM_Z_NUM_BYTES) bytes
  val GEOM_Z_MASK: Long = Long.MaxValue << (64 - 8 * GEOM_Z_NUM_BYTES)

  override def supports(sft: SimpleFeatureType): Boolean =
    sft.getDtgField.isDefined && ((sft.getSchemaVersion > 6 && sft.getGeometryDescriptor != null) ||
        (sft.getSchemaVersion > 4 && sft.isPoints))

  override val suffix: String = "z3"

  // z3 always needs a separate table since we don't include the feature name in the row key
  override def formatTableName(prefix: String, sft: SimpleFeatureType): String =
    GeoMesaTable.formatSoloTableName(prefix, suffix, sft.getTypeName)

  override def writer(sft: SimpleFeatureType): FeatureToMutations = {
    val dtgIndex = sft.getDtgIndex.getOrElse(throw new RuntimeException("Z3 writer requires a valid date"))
    val getRowKeys: (FeatureToWrite, Int) => Seq[Array[Byte]] =
      if (sft.isPoints) {
        if (hasSplits(sft)) {
          getPointRowKey
        } else {
          (ftw, i) => getPointRowKey(ftw, i).map(_.drop(1))
        }
      } else {
        getGeomRowKeys
      }
    val getValue: (FeatureToWrite) => Value = if (sft.getSchemaVersion > 5) {
      // we know the data is kryo serialized in version 6+
      (fw) => fw.dataValue
    } else {
      // we always want to use kryo - reserialize the value to ensure it
      val writer = new KryoFeatureSerializer(sft)
      (fw) => new Value(writer.serialize(fw.feature))
    }
    sft.getVisibilityLevel match {
      case VisibilityLevel.Feature =>
        (fw: FeatureToWrite) => {
          val rows = getRowKeys(fw, dtgIndex)
          // store the duplication factor in the column qualifier for later use
          val cq = if (rows.length > 1) new Text(Integer.toHexString(rows.length)) else EMPTY_TEXT
          rows.map { row =>
            val mutation = new Mutation(row)
            mutation.put(FULL_CF, cq, fw.columnVisibility, getValue(fw))
            fw.binValue.foreach(v => mutation.put(BIN_CF, cq, fw.columnVisibility, v))
            mutation
          }
        }
      case VisibilityLevel.Attribute =>
        (fw: FeatureToWrite) => {
          val rows = getRowKeys(fw, dtgIndex)
          // TODO GEOMESA-1254 duplication factor, bin values
          rows.map { row =>
            val mutation = new Mutation(row)
            fw.perAttributeValues.foreach(key => mutation.put(key.cf, key.cq, key.vis, key.value))
            mutation
          }
        }
    }
  }

  override def remover(sft: SimpleFeatureType): FeatureToMutations = {
    val dtgIndex = sft.getDtgIndex.getOrElse(throw new RuntimeException("Z3 writer requires a valid date"))
    val getRowKeys: (FeatureToWrite, Int) => Seq[Array[Byte]] =
      if (sft.isPoints) {
        if (hasSplits(sft)) {
          getPointRowKey
        } else {
          (ftw, i) => getPointRowKey(ftw, i).map(_.drop(1))
        }
      } else {
        getGeomRowKeys
      }
    sft.getVisibilityLevel match {
      case VisibilityLevel.Feature =>
        (fw: FeatureToWrite) => {
          val rows = getRowKeys(fw, dtgIndex)
          val cq = if (rows.length > 1) new Text(Integer.toHexString(rows.length)) else EMPTY_TEXT
          rows.map { row =>
            val mutation = new Mutation(row)
            mutation.putDelete(BIN_CF, cq, fw.columnVisibility)
            mutation.putDelete(FULL_CF, cq, fw.columnVisibility)
            mutation
          }
        }
      case VisibilityLevel.Attribute =>
        (fw: FeatureToWrite) => {
          val rows = getRowKeys(fw, dtgIndex)
          // TODO duplication factor, bin values
          rows.map { row =>
            val mutation = new Mutation(row)
            fw.perAttributeValues.foreach(key => mutation.putDelete(key.cf, key.cq, key.vis))
            mutation
          }
        }
    }
  }

  override def getIdFromRow(sft: SimpleFeatureType): (Array[Byte]) => String = {
    val offset = getIdRowOffset(sft)
    (row: Array[Byte]) => new String(row, offset, row.length - offset, Charsets.UTF_8)
  }

  override def deleteFeaturesForType(sft: SimpleFeatureType, bd: BatchDeleter): Unit = {
    bd.setRanges(Seq(new aRange()))
    bd.delete()
  }

  // geoms always have splits, but they weren't added until schema 7
  def hasSplits(sft: SimpleFeatureType) = sft.getSchemaVersion > 6

  // gets week and seconds into that week
  def getWeekAndSeconds(time: DateTime): (Short, Int) = {
    val weeks = Weeks.weeksBetween(EPOCH, time)
    val secondsInWeek = Seconds.secondsBetween(EPOCH, time).getSeconds - weeks.toStandardSeconds.getSeconds
    (weeks.getWeeks.toShort, secondsInWeek)
  }

  // gets week and seconds into that week
  def getWeekAndSeconds(time: Long): (Short, Int) = getWeekAndSeconds(new DateTime(time, DateTimeZone.UTC))

  // split(1 byte), week(2 bytes), z value (8 bytes), id (n bytes)
  private def getPointRowKey(ftw: FeatureToWrite, dtgIndex: Int): Seq[Array[Byte]] = {
    val split = SPLIT_ARRAYS(ftw.idHash % NUM_SPLITS)
    val (week, z) = {
      val dtg = ftw.feature.getAttribute(dtgIndex).asInstanceOf[Date]
      val time = if (dtg == null) 0 else dtg.getTime
      val (w, t) = getWeekAndSeconds(time)
      val geom = ftw.feature.point
      (w, Z3SFC.index(geom.getX, geom.getY, t).z)
    }
    val id = ftw.feature.getID.getBytes(Charsets.UTF_8)
    Seq(Bytes.concat(split, Shorts.toByteArray(week), Longs.toByteArray(z), id))
  }

  // split(1 byte), week (2 bytes), z value (3 bytes), id (n bytes)
  private def getGeomRowKeys(ftw: FeatureToWrite, dtgIndex: Int): Seq[Array[Byte]] = {
    val split = SPLIT_ARRAYS(ftw.idHash % NUM_SPLITS)
    val (week, zs) = {
      val dtg = ftw.feature.getAttribute(dtgIndex).asInstanceOf[Date]
      val time = if (dtg == null) 0 else dtg.getTime
      val (w, t) = getWeekAndSeconds(time)
      val geom = ftw.feature.getDefaultGeometry.asInstanceOf[Geometry]
      (Shorts.toByteArray(w), zBox(geom, t).toSeq)
    }
    val id = ftw.feature.getID.getBytes(Charsets.UTF_8)
    zs.map(z => Bytes.concat(split, week, Longs.toByteArray(z).take(GEOM_Z_NUM_BYTES), id))
  }

  // gets a sequence of (week, z) values that cover the geometry
  private def zBox(geom: Geometry, t: Int): Set[Long] = geom match {
    case g: Point => Set(Z3SFC.index(g.getX, g.getY, t).z)
    case g: LineString =>
      // we flatMap bounds for each line segment so we cover a smaller area
      (0 until g.getNumPoints).map(g.getPointN).sliding(2).flatMap { case Seq(one, two) =>
        val (xmin, xmax) = minMax(one.getX, two.getX)
        val (ymin, ymax) = minMax(one.getY, two.getY)
        zBox(xmin, ymin, xmax, ymax, t)
      }.toSet
    case g: GeometryCollection => (0 until g.getNumGeometries).toSet.map(g.getGeometryN).flatMap(zBox(_, t))
    case g: Geometry =>
      val env = g.getEnvelopeInternal
      zBox(env.getMinX, env.getMinY, env.getMaxX, env.getMaxY, t)
  }

  // gets a sequence of (week, z) values that cover the bounding box
  private def zBox(xmin: Double, ymin: Double, xmax: Double, ymax: Double, t: Int): Set[Long] = {
    val zmin = Z3SFC.index(xmin, ymin, t).z
    val zmax = Z3SFC.index(xmax, ymax, t).z
    getZPrefixes(zmin, zmax)
  }

  private def minMax(a: Double, b: Double): (Double, Double) = if (a < b) (a, b) else (b, a)

  // gets z values that cover the interval
  private def getZPrefixes(zmin: Long, zmax: Long): Set[Long] = {
    val in = scala.collection.mutable.Queue((zmin, zmax))
    val out = scala.collection.mutable.HashSet.empty[Long]

    while (in.nonEmpty) {
      val (min, max) = in.dequeue()
      val ZPrefix(zprefix, zbits) = Z3.longestCommonPrefix(min, max)
      if (zbits < GEOM_Z_NUM_BYTES * 8) {
        // divide the range into two smaller ones using tropf litmax/bigmin
        val (litmax, bigmin) = Z3.zdivide(Z3((min + max) / 2), Z3(min), Z3(max))
        in.enqueue((min, litmax.z), (bigmin.z, max))
      } else {
        // we've found a prefix that contains our z range
        // truncate down to the bytes we use so we don't get dupes
        out.add(zprefix & GEOM_Z_MASK)
      }
    }

    out.toSet
  }

  // gets the offset into the row for the id bytes
  def getIdRowOffset(sft: SimpleFeatureType): Int = {
    val length = if (sft.isPoints) 10 else 2 + GEOM_Z_NUM_BYTES // week + z bytes
    val prefix = if (hasSplits(sft)) 1 else 0 // shard
    prefix + length
  }

  override def configureTable(sft: SimpleFeatureType, table: String, tableOps: TableOperations): Unit = {
    tableOps.setProperty(table, Property.TABLE_BLOCKCACHE_ENABLED.getKey, "true")

    val localityGroups = Seq(BIN_CF, FULL_CF).map(cf => (cf.toString, ImmutableSet.of(cf))).toMap
    tableOps.setLocalityGroups(table, localityGroups)

    // drop first split, otherwise we get an empty tablet
    val splits = SPLIT_ARRAYS.drop(1).map(new Text(_)).toSet
    val splitsToAdd = splits -- tableOps.listSplits(table).toSet
    if (splitsToAdd.nonEmpty) {
      // noinspection RedundantCollectionConversion
      tableOps.addSplits(table, ImmutableSortedSet.copyOf(splitsToAdd.toIterable))
    }
  }
}


text:
<!doctype html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="Peer-to-peer location sharing" content="latlng.in"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,
      maximum-scale=1.0, user-scalable=no" />
    <title>LatLng</title>

    {% block links %} {% endblock links %}

    {% block headscripts %}
    <script type="text/javascript">
    // Don't HTML escape, see
    // http://jinja.pocoo.org/docs/templates/#working-with-automatic-escaping
      appConfig = {{config|safe}};
    </script>

    {% endblock headscripts %}
  </head>

  <body id="body">
    {% block content %} {% endblock content %}

    {% block endscripts %} {% endblock endscripts %}
  </body>
</html>


text:
import './site';

export * from './connectors';
export * from './query';
export * from '../../lib/vulcan-lib/index';
export * from './mutators';
export * from './errors';
export * from './intl';
export * from './staticRoutes';

export * from './apollo-server/context';
export * from './apollo-ssr/apolloClient';

import './utils';
import './apollo-server/authentication';
import '../apolloServer';


text:
package log_streamer

import "io"

type bufferStreamer struct {
	stdout     io.Writer
	stderr     io.Writer
	sourceName string
}

func NewBufferStreamer(stdout, stderr io.Writer) LogStreamer {
	return &bufferStreamer{
		stdout:     stdout,
		stderr:     stderr,
		sourceName: DefaultLogSource,
	}
}

func (bs *bufferStreamer) Stdout() io.Writer {
	return bs.stdout
}

func (bs *bufferStreamer) Stderr() io.Writer {
	return bs.stderr
}

func (bs *bufferStreamer) Flush() {
}

func (bs *bufferStreamer) WithSource(sourceName string) LogStreamer {
	bs.sourceName = sourceName
	return bs
}

func (bs *bufferStreamer) SourceName() string {
	return bs.sourceName
}

func (bs *bufferStreamer) Stop() {}


text:
<?php

class PR_Api_Core_SectionsClass
{
    public function  __construct()
    {

    }
    public function GetListByTeacherId($Id)
    {
        $db = PR_Database::getInstance();
        $select = $db->select();
        $select->from("sections");
        $select->where("fk_teacher_id = '$Id'");
        $select->where("section_status = 'Open'");
        $records = PR_Database::fetchAll($select);
        return $records;
    }

    public function GetSectionWeeks($sectionId)
    {
        $db = PR_Database::getInstance();
        $select = $db->select();
        $select->from(array('s' => 'sections'), array('s.section_weeks'));
        $select->where("section_id = '$sectionId'");
        $records = PR_Database::fetchAll($select);

        if (!empty($records))
            return $records[0]['section_weeks'];
        else
            return 0;
    }

    public function GetSectionNum($sectionId)
    {
        $db = PR_Database::getInstance();
        $select = $db->select();
        $select->from(array('s' => 'sections'), array('s.students_num'));
        $select->where("section_id = '$sectionId'");
        $records = PR_Database::fetchAll($select);

        if (!empty($records))
            return $records[0]['students_num'];
        else
            return 0;
    }

    public function UpdateSectionStudentNum($sectionId, $num)
    {
        $students_num = $this->GetSectionNum($sectionId);
        $students_num = $students_num + $num;
        $dbFields = array();
        $dbFields['students_num'] = $students_num;
        $criteria = "section_id = '$sectionId'";
        $result = PR_Database::update('sections', $dbFields, $criteria);
        return $result;
    }

}


text:
package mn.hart.android.simpleaidl;

import android.os.Bundle;

/**
 * Provides constructs that allow an object to pack and
 * recreate itself before and after IPC, respectively.
 * into a Bundle and r
 * @author Kevin Hartman <kevin@hart.mn>
 * @version 1.0
 */
public interface AIDLBundleable {

    /**
     * Set up instance using provided data.
     * @param instanceData Bundle created by this object before IPC.
     */
	public void contructFromInstanceData(Bundle instanceData);

	/**
	 * Write instance data prior to shuttling.
	 * @param instanceData Bundle in which to write instance data.
	 */
	public void writeInstanceData(Bundle instanceData);
}


text:
package postgres

import (
	"database/sql"
	"time"

	"github.com/dairycart/dairycart/models/v1"
	"github.com/dairycart/dairycart/storage/v1/database"

	"github.com/Masterminds/squirrel"
)

const userQueryByUsername = `
    SELECT
        id,
        first_name,
        last_name,
        username,
        email,
        password,
        is_admin,
        password_last_changed_on,
        created_on,
        updated_on,
        archived_on
    FROM
        users
    WHERE
        archived_on is null
    AND
        username = $1
`

func (pg *postgres) GetUserByUsername(db database.Querier, username string) (*models.User, error) {
	u := &models.User{}
	err := db.QueryRow(userQueryByUsername, username).Scan(&u.ID, &u.FirstName, &u.LastName, &u.Username, &u.Email, &u.Password, &u.IsAdmin, &u.PasswordLastChangedOn, &u.CreatedOn, &u.UpdatedOn, &u.ArchivedOn)
	return u, err
}

const userWithUsernameExistenceQuery = `SELECT EXISTS(SELECT id FROM users WHERE username = $1 and archived_on IS NULL);`

func (pg *postgres) UserWithUsernameExists(db database.Querier, sku string) (bool, error) {
	var exists string

	err := db.QueryRow(userWithUsernameExistenceQuery, sku).Scan(&exists)
	if err == sql.ErrNoRows {
		return false, nil
	} else if err != nil {
		return false, err
	}

	return exists == "true", err
}

const updateUserPasswordQuery = `UPDATE users set password=$1, updated_on=NOW() where id = $2 RETURNING updated_on`

func (pg *postgres) UpdatePasswordForUser(db database.Querier, userID uint64, password string) (time.Time, error) {
	var t time.Time
	err := db.QueryRow(updateUserPasswordQuery, password, userID).Scan(&t)
	return t, err
}

const userExistenceQuery = `SELECT EXISTS(SELECT id FROM users WHERE id = $1 and archived_on IS NULL);`

func (pg *postgres) UserExists(db database.Querier, id uint64) (bool, error) {
	var exists string

	err := db.QueryRow(userExistenceQuery, id).Scan(&exists)
	if err == sql.ErrNoRows {
		return false, nil
	} else if err != nil {
		return false, err
	}

	return exists == "true", err
}

const userSelectionQuery = `
    SELECT
        id,
        first_name,
        last_name,
        username,
        email,
        password,
        is_admin,
        password_last_changed_on,
        created_on,
        updated_on,
        archived_on
    FROM
        users
    WHERE
        archived_on is null
    AND
        id = $1
`

func (pg *postgres) GetUser(db database.Querier, id uint64) (*models.User, error) {
	u := &models.User{}

	err := db.QueryRow(userSelectionQuery, id).Scan(&u.ID, &u.FirstName, &u.LastName, &u.Username, &u.Email, &u.Password, &u.IsAdmin, &u.PasswordLastChangedOn, &u.CreatedOn, &u.UpdatedOn, &u.ArchivedOn)

	return u, err
}

func buildUserListRetrievalQuery(qf *models.QueryFilter) (string, []interface{}) {
	sqlBuilder := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)
	queryBuilder := sqlBuilder.
		Select(
			"id",
			"first_name",
			"last_name",
			"username",
			"email",
			"password",
			"is_admin",
			"password_last_changed_on",
			"created_on",
			"updated_on",
			"archived_on",
		).
		From("users")

	query, args, _ := applyQueryFilterToQueryBuilder(queryBuilder, qf, true).ToSql()
	return query, args
}

func (pg *postgres) GetUserList(db database.Querier, qf *models.QueryFilter) ([]models.User, error) {
	var list []models.User
	query, args := buildUserListRetrievalQuery(qf)

	rows, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var u models.User
		err := rows.Scan(
			&u.ID,
			&u.FirstName,
			&u.LastName,
			&u.Username,
			&u.Email,
			&u.Password,
			&u.IsAdmin,
			&u.PasswordLastChangedOn,
			&u.CreatedOn,
			&u.UpdatedOn,
			&u.ArchivedOn,
		)
		if err != nil {
			return nil, err
		}
		list = append(list, u)
	}
	err = rows.Err()
	if err != nil {
		return nil, err
	}

	return list, err
}

func buildUserCountRetrievalQuery(qf *models.QueryFilter) (string, []interface{}) {
	queryBuilder := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
		Select("count(id)").
		From("users")

	query, args, _ := applyQueryFilterToQueryBuilder(queryBuilder, qf, false).ToSql()
	return query, args
}

func (pg *postgres) GetUserCount(db database.Querier, qf *models.QueryFilter) (uint64, error) {
	var count uint64
	query, args := buildUserCountRetrievalQuery(qf)
	err := db.QueryRow(query, args...).Scan(&count)
	return count, err
}

const userCreationQuery = `
    INSERT INTO users
        (
            first_name, last_name, username, email, password, is_admin, password_last_changed_on
        )
    VALUES
        (
            $1, $2, $3, $4, $5, $6, $7
        )
    RETURNING
        id, created_on;
`

func (pg *postgres) CreateUser(db database.Querier, nu *models.User) (createdID uint64, createdOn time.Time, err error) {
	err = db.QueryRow(userCreationQuery, &nu.FirstName, &nu.LastName, &nu.Username, &nu.Email, &nu.Password, &nu.IsAdmin, &nu.PasswordLastChangedOn).Scan(&createdID, &createdOn)
	return createdID, createdOn, err
}

const userUpdateQuery = `
    UPDATE users
    SET
        first_name = $1,
        last_name = $2,
        username = $3,
        email = $4,
        password = $5,
        is_admin = $6,
        password_last_changed_on = $7,
        updated_on = NOW()
    WHERE id = $8
    RETURNING updated_on;
`

func (pg *postgres) UpdateUser(db database.Querier, updated *models.User) (time.Time, error) {
	var t time.Time
	err := db.QueryRow(userUpdateQuery, &updated.FirstName, &updated.LastName, &updated.Username, &updated.Email, &updated.Password, &updated.IsAdmin, &updated.PasswordLastChangedOn, &updated.ID).Scan(&t)
	return t, err
}

const userDeletionQuery = `
    UPDATE users
    SET archived_on = NOW()
    WHERE id = $1
    RETURNING archived_on
`

func (pg *postgres) DeleteUser(db database.Querier, id uint64) (t time.Time, err error) {
	err = db.QueryRow(userDeletionQuery, id).Scan(&t)
	return t, err
}


text:
A module is basically an object. Modules helps you structure your state and signals. You can think of them as namespaces for state and signals.

```js
export default {
  // Define module state, namespaced by module path
  state: {},
  // Define module signals, namespaced by module path
  signals: {},
  // Define submodules, namespaced by module path
  modules: {},
  // Add a global provider when module instantiates
  provider(context, functionDetails, payload) {}
}
```

It is also possible to define a module using a function.

```js
export default (module) => {
  module.name // Name of module
  module.path // Full path to module
  module.controller // The controller the module is attached to

  return {
    state: {},
    signals: {},
    modules: {},
    provider(context, functionDetails, payload) {}
  }
}
```

You attach a module simply by referencing it:

```js
import {Controller} from 'cerebral'
import FeedModule from './modules/Feed'

const controller = Controller({
  modules: {
    feed: FeedModule
  }
})
```


text:
<dom-module id="call-to-action">
    <template>

Vive la experiencia de nuestros DevFest anteriores

        <paper-dialog class="video-dialog fit" id="videoDialog" entry-animation="scale-up-animation" exit-animation="fade-out-animation">
            <paper-toolbar class="navbar-overlay fit">
                <paper-icon-button icon="icons:arrow-back" on-tap="closeVideoCard"></paper-icon-button>

GDG DevFest Lima 2014 - Highlights

            </paper-toolbar>

                <google-youtube id="video" video-id="t95z_HLMTmM" fluid="true" autohide="1" chromeless="true"></google-youtube>

        </paper-dialog>
    </template>
</dom-module>


text:
<?php

namespace ONGR\MonitoringBundle\Tests\Unit\Metric;

use ONGR\ElasticsearchBundle\ORM\Manager;
use ONGR\ElasticsearchBundle\ORM\Repository;
use ONGR\MonitoringBundle\Document\Metric;
use ONGR\MonitoringBundle\Helper\MetricData;
use ONGR\MonitoringBundle\Metric\CollectorService;

/**
 * Class test CollectorService class.
 */
class CollectorServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string
     */
    protected $metricRepository = 'ONGRMonitoringBundle:Metric';

    /**
     * Method to test collecting of metrics.
     */
    public function testCollect()
    {
        $repository = $this
            ->getMockBuilder('ONGR\ElasticsearchBundle\ORM\Repository')
            ->disableOriginalConstructor()
            ->getMock();

        $repository
            ->expects($this->exactly(2))
            ->method('createDocument')
            ->will($this->returnValue(new Metric()));

        $manager = $this->getManagerMock();
        $manager->expects($this->once())->method('commit');

        $manager->expects($this->exactly(2))->method('persist');

        $metrics = [];
        $metric1 = $this->getMetricMock();
        $metric1->expects($this->any())->method('getRepository')->willReturn('ONGRMonitoringBundle:Metric');
        $metric1->expects($this->once())->method('getName');
        $metric1->expects($this->once())->method('getValue');
        $metrics['metric 1'] = $metric1;

        $metric2 = $this->getMetricMock();
        $metric1->expects($this->any())->method('getRepository')->willReturn('ONGRMonitoringBundle:Event');
        $metric2->expects($this->once())->method('getName');
        $metric2->expects($this->once())->method('getValue');
        $metrics['metric 2'] = $metric2;

        $service = new CollectorService($manager, $repository, $metrics);

        $service->collect();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getManagerMock()
    {
        $manager = $this->getMockBuilder('ONGR\ElasticsearchBundle\ORM\Manager')
            ->setMethods(['flush', 'createDocument', 'persist', 'commit', 'getRepository'])
            ->disableOriginalConstructor()
            ->getMock();

        return $manager;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getMetricMock()
    {
        $metric = $this->getMock('ONGR\MonitoringBundle\Metric\MetricInterface');

        return $metric;
    }

    /**
     * Test to check whether two metric objects are created when metric collector returns array.
     */
    public function testCollectArray()
    {
        /** @var Metric $metricMock */
        $metricMock = $this
            ->getMockBuilder('ONGR\MonitoringBundle\Document\Metric')
            ->disableOriginalConstructor()
            ->getMock();

        /** Repository $repository */
        $repository = $this->getRepositoryMock();
        $repository
            ->expects($this->exactly(2))
            ->method('createDocument')
            ->will($this->returnValue($metricMock));

        /** @var Manager $manager */
        $manager = $this->getManagerMock();

        $manager->expects($this->once())->method('commit');
        $manager->expects($this->exactly(2))->method('persist');

        /** @var \ONGR\MonitoringBundle\Metric\MetricInterface $metric1 */
        $metric1 = $this->getMetricMock();
        $metric1->expects($this->once())->method('getName')->willReturn('DummyMetric');
        $metric1->expects($this->once())->method('getValue')->willReturn([1 => 'value-1', 2 => 'value-2']);

        $service = new CollectorService($manager, $repository, ['metric 1' => $metric1]);

        $service->collect();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getRepositoryMock()
    {
        $repository = $this
            ->getMockBuilder('ONGR\ElasticsearchBundle\ORM\Repository')
            ->disableOriginalConstructor()
            ->getMock();

        return $repository;
    }

    /**
     * Test to check whether two metric objects are created when metric collector returns array of MetricData.
     */
    public function testCollectMetricDataArray()
    {
        /** @var Metric $metricMock */
        $metricMock = $this->getMock('ONGR\MonitoringBundle\Document\Metric');

        /** @var Repository $repository */
        $repository = $this->getRepositoryMock();
        $repository->expects($this->exactly(2))->method('createDocument')->willReturn($metricMock);
        /** @var Manager $manager */
        $manager = $this->getManagerMock();

        $manager->expects($this->once())->method('commit');
        $manager->expects($this->exactly(2))->method('persist');

        /** @var \ONGR\MonitoringBundle\Metric\MetricInterface $metric1 */
        $metricData = new MetricData();
        $metricData->setTag('tag-1');
        $metricData->setValue('value-1');
        $metricData->setMetric('metric-1');

        $values[] = $metricData;
        $metricData = new MetricData();
        $metricData->setTag('tag-2');
        $metricData->setValue('value-2');
        $metricData->setMetric('metric-2');

        $values[] = $metricData;
        $metric1 = $this->getMetricMock();
        $metric1->expects($this->once())->method('getName')->willReturn('DummyMetric');
        $metric1->expects($this->once())->method('getValue')->willReturn($values);

        $service = new CollectorService($manager, $repository, ['metric 1' => $metric1]);

        $service->collect();
    }

    /**
     * Tests if unregistered metric is not executed.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testAddMetricException()
    {
        $manager = $this->getManagerMock();
        $repository = $this->getRepositoryMock();

        $metric1 = new \stdClass();
        $service = new CollectorService($manager, $repository, ['metric 1' => $metric1]);
    }

    /**
     * Tests non existing metric.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testCollectException()
    {
        $manager = $this->getManagerMock();
        $repository = $this->getRepositoryMock();

        $metric1 = $this->getMetricMock();

        $service = new CollectorService($manager, $repository, ['metric 1' => $metric1]);

        $service->collect('not existing metric');
    }

    /**
     * Method to test collecting of specific metrics.
     */
    public function testCollectSpecificMetric()
    {
        /** @var Repository $repository */
        $repository = $this->getRepositoryMock();
        $repository->expects($this->any())->method('createDocument')->willReturn(new Metric());
        /** @var Manager $manager */
        $manager = $this->getManagerMock();

        $manager->expects($this->once())->method('commit');

        $metrics = [];
        $metric1 = $this->getMetricMock();
        $metric1->expects($this->never())->method('getName');
        $metric1->expects($this->never())->method('getValue');
        $metrics['metric 1'] = $metric1;

        $metric2 = $this->getMetricMock();
        $metric2->expects($this->once())->method('getName');
        $metric2->expects($this->once())->method('getValue');
        $metrics['metric 2'] = $metric2;

        $metric3 = $this->getMetricMock();
        $metric3->expects($this->never())->method('getName');
        $metric3->expects($this->never())->method('getValue');
        $metrics['metric 3'] = $metric3;

        $metric4 = $this->getMetricMock();
        $metric4->expects($this->never())->method('getName');
        $metric4->expects($this->never())->method('getValue');
        $metrics['metric 4'] = $metric4;

        $service = new CollectorService($manager, $repository, $metrics);

        $service->collect('metric 2');
    }
}


text:
<?php
class Course{

function  __sleep(){

    echo "I'm now sleeping...zzzzzz!";
    return array();
}
    function  __wakeup(){
        echo "hii,I'm now ready to work....";
    }
}


text:
package org.ofbiz.minilang.method.envops;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.ofbiz.base.util.UtilXml;
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.ofbiz.base.util.string.FlexibleStringExpander;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.minilang.MiniLangValidate;
import org.ofbiz.minilang.SimpleMethod;
import org.ofbiz.minilang.method.MethodContext;
import org.ofbiz.minilang.method.MethodOperation;
import org.ofbiz.minilang.method.conditional.Conditional;
import org.ofbiz.minilang.method.conditional.ConditionalFactory;
import org.w3c.dom.Element;

/**
 * Implements the <assert> element.
 *
 * @see Mini-language Reference
 */
public final class Assert extends MethodOperation {

    public static final String module = Assert.class.getName();

    private final List<Conditional> conditionalList;
    private final FlexibleMapAccessor<List<Object>> errorListFma;
    private final FlexibleStringExpander titleExdr;

    public Assert(Element element, SimpleMethod simpleMethod) throws MiniLangException {
        super(element, simpleMethod);
        if (MiniLangValidate.validationOn()) {
            MiniLangValidate.attributeNames(simpleMethod, element, "title", "error-list-name");
            MiniLangValidate.constantAttributes(simpleMethod, element, "title", "error-list-name");
        }
        errorListFma = FlexibleMapAccessor.getInstance(MiniLangValidate.checkAttribute(element.getAttribute("error-list-name"), "error_list"));
        titleExdr = FlexibleStringExpander.getInstance(element.getAttribute("title"));
        List<? extends Element> childElements = UtilXml.childElementList(element);
        if (MiniLangValidate.validationOn() && childElements.isEmpty()) {
            MiniLangValidate.handleError("No conditional elements.", simpleMethod, element);
        }
        List<Conditional> conditionalList = new ArrayList<Conditional>(childElements.size());
        for (Element conditionalElement : UtilXml.childElementList(element)) {
            conditionalList.add(ConditionalFactory.makeConditional(conditionalElement, simpleMethod));
        }
        this.conditionalList = Collections.unmodifiableList(conditionalList);
    }

    @Override
    public boolean exec(MethodContext methodContext) throws MiniLangException {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Begin assert.");
        }
        List<Object> messages = errorListFma.get(methodContext.getEnvMap());
        String title = titleExdr.expandString(methodContext.getEnvMap());
        for (Conditional condition : conditionalList) {
            if (!condition.checkCondition(methodContext)) {
                StringBuilder messageBuffer = new StringBuilder("Assertion ");
                if (!title.isEmpty()) {
                    messageBuffer.append("[");
                    messageBuffer.append(title);
                    messageBuffer.append("] ");
                }
                messageBuffer.append("failed: ");
                condition.prettyPrint(messageBuffer, methodContext);
                if (messages == null) {
                    messages = new LinkedList<Object>();
                    errorListFma.put(methodContext.getEnvMap(), messages);
                }
                messages.add(messageBuffer.toString());
                if (methodContext.isTraceOn()) {
                    outputTraceMessage(methodContext, "Condition evaluated to false: " + condition + ", adding error message.");
                }
            }
        }
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "End assert.");
        }
        return true;
    }

    @Override
    public String toString() {
        StringBuilder messageBuf = new StringBuilder("<assert");
        if (!titleExdr.isEmpty()) {
            messageBuf.append(" title=\"");
            messageBuf.append(titleExdr);
            messageBuf.append("\"");
        }
        messageBuf.append(">");
        for (Conditional condition : conditionalList) {
            messageBuf.append(condition);
        }
        messageBuf.append("</assert>");
        return messageBuf.toString();
    }

    /**
     * A factory for the <assert> element.
     */
    public static final class AssertFactory implements Factory<Assert> {
        @Override
        public Assert createMethodOperation(Element element, SimpleMethod simpleMethod) throws MiniLangException {
            return new Assert(element, simpleMethod);
        }

        @Override
        public String getName() {
            return "assert";
        }
    }
}


text:
import React from "react";
import {
  Button,
  ButtonProps,
  Input,
  InputOnChangeData,
} from "semantic-ui-react";
import { IURLConnector, UrlHOC } from "redux/modules/url";
import {
  editMeetingDate,
  editMeetingTags,
  editMeetingBeneficiary,
  getMeeting,
  IEditMeetingDate,
  IEditMeetingTags,
  IMeetingResult,
  IEditMeetingBeneficiary,
} from "apollo/modules/meetings";
import { TagInputWithBenSuggestions } from "components/TagInput";
import { Error } from "components/Error";
import { DateTimePicker } from "components/DateTimePicker";
import { Hint } from "components/Hint";
import moment from "moment";
import { Tags } from "components/Tag";
import { PageWrapperHoC } from "components/PageWrapperHoC";
import { ApolloLoaderHoC } from "components/ApolloLoaderHoC";
import { WithTranslation, withTranslation } from "react-i18next";
import { forward, ISearchParam } from "helpers/url";
import "./style.less";

interface IProps
  extends IURLConnector,
    IEditMeetingDate,
    IEditMeetingTags,
    IEditMeetingBeneficiary,
    ISearchParam,
    WithTranslation {
  match: {
    params: {
      id: string;
    };
  };
  data: IMeetingResult;
}

interface IState {
  saveError?: string;
  conducted?: moment.Moment;
  recordTags?: string[];
  beneficiary?: string;
  saving?: boolean;
  tagEditing?: boolean;
  dateEditing?: boolean;
  benEditing?: boolean;
  loaded?: boolean;
}

class RecordEditInner extends React.Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {};
    this.saveRecord = this.saveRecord.bind(this);
    this.setTags = this.setTags.bind(this);
    this.setBen = this.setBen.bind(this);
    this.setConductedDate = this.setConductedDate.bind(this);
    this.nextPage = this.nextPage.bind(this);
    this.loadState = this.loadState.bind(this);
    this.renderTagSection = this.renderTagSection.bind(this);
    this.renderDateSection = this.renderDateSection.bind(this);
    this.renderBeneficiaryID = this.renderBeneficiaryID.bind(this);
    this.editAnswers = this.editAnswers.bind(this);
  }

  public componentDidMount() {
    if (this.props.data.getMeeting !== undefined) {
      this.loadState(this.props);
    }
  }

  public componentDidReceiveProps(prevProps: IProps) {
    if (
      this.props.data.getMeeting !== undefined &&
      prevProps.data.getMeeting === undefined
    ) {
      this.loadState(this.props);
    }
  }

  private loadState(p: IProps) {
    this.setState({
      conducted: moment(p.data.getMeeting.date),
      recordTags: p.data.getMeeting.meetingTags,
      beneficiary: p.data.getMeeting.beneficiary,
      loaded: true,
    });
  }

  private saveRecord() {
    const record = this.props.data.getMeeting;
    const { conducted, recordTags, beneficiary } = this.state;
    this.setState({
      saving: true,
      saveError: undefined,
    });

    let p = Promise.resolve(record);

    if (!this.state.conducted.isSame(record.date)) {
      p = p.then(() => {
        return this.props.editMeetingDate(record.id, conducted.toDate());
      });
    }

    const newTags = JSON.stringify(Array.from(recordTags).sort());
    const oldTags = JSON.stringify(Array.from(record.meetingTags).sort());
    if (newTags !== oldTags) {
      p = p.then(() => {
        return this.props.editMeetingTags(record.id, recordTags);
      });
    }

    if (beneficiary !== record.beneficiary) {
      p = p.then(() => {
        return this.props.editMeetingBeneficiary(record.id, beneficiary);
      });
    }

    return p
      .then(() => {
        this.nextPage();
      })
      .catch((e) => {
        console.error(e);
        this.setState({
          saving: false,
          saveError: e,
        });
      });
  }

  private nextPage() {
    if (!forward(this.props, this.props.setURL)) {
      this.props.setURL(`/beneficiary/${this.state.beneficiary}`);
    }
  }

  private setConductedDate(date: moment.Moment) {
    this.setState({
      conducted: date,
    });
  }

  private setTags(tags: string[]): void {
    this.setState({
      recordTags: tags,
    });
  }

  private setBen(beneficiary: string): void {
    this.setState({ beneficiary });
  }

  private editAnswers(): void {
    this.props.setURL(`/dataentry/${this.props.match.params.id}`);
  }

  private renderEditButton(onClick: () => void): JSX.Element {
    return (
      <Button
        className="field-edit"
        onClick={onClick}
        compact={true}
        size="tiny"
        primary={true}
      >
        {this.props.t("Edit")}
      </Button>
    );
  }

  private renderBeneficiaryID(benEditing: boolean): JSX.Element {
    let control =
;
    if (benEditing) {
      const benChanged = (_, data: InputOnChangeData) => {
        this.setBen(data.value);
      };
      control = (
        <Input
          id="meeting-ben"
          type="text"
          onChange={benChanged}
          value={this.state.beneficiary}
        />
      );
    } else {
      const benEdit = () => {
        this.setState({ benEditing: true });
      };
      const editButton = this.renderEditButton(benEdit);
      control = (

          {this.state.beneficiary} {editButton}

      );
    }
    return (

{this.props.t("Beneficiary")}

        {control}

    );
  }

  private renderDateSection(dateEditing: boolean): JSX.Element {
    if (this.props.data.getMeeting.incomplete) {
      return
;
    }
    let control =
;
    if (dateEditing) {
      control = (
        <DateTimePicker
          moment={this.state.conducted}
          onChange={this.setConductedDate}
          allowFutureDates={false}
        />
      );
    } else {
      const dateEdit = () => {
        this.setState({ dateEditing: true });
      };
      control = this.renderEditButton(dateEdit);
    }
    return (

{this.props.t("Date")}

          {this.state.conducted.format("llll")}

        {control}

    );
  }

  private renderTagSection(
    beneficiary: string,
    tagEditing: boolean
  ): JSX.Element {
    const t = this.props.t;
    let tags =
;
    if (tagEditing) {
      tags = (

          <Tags benTags={this.props.data.getMeeting.benTags} recordTags={[]} />
          <TagInputWithBenSuggestions
            onChange={this.setTags}
            tags={this.state.recordTags}
            id={beneficiary}
          />

      );
    } else {
      const tagEdit = () => {
        this.setState({ tagEditing: true });
      };
      const editButton = this.renderEditButton(tagEdit);
      if (this.props.data.getMeeting.tags.length > 0) {
        tags = (

            <Tags
              benTags={this.props.data.getMeeting.benTags}
              recordTags={this.state.recordTags}
            />
            {editButton}

        );
      } else {
        tags = (

            {t("No tags")}
            {editButton}

        );
      }
    }
    const tagExplanation = t(
      "Tags are words which can be saved against records. They can be used to filter your records when reporting. Common uses of tags include demographic or intervention information."
    );
    return (

          <Hint text={tagExplanation} />
          {t("Tags")}

        {tags}

    );
  }

  public render() {
    const record = this.props.data.getMeeting;
    if (
      this.props.match.params.id === undefined ||
      !this.state.loaded ||
      !record
    ) {
      return
;
    }

    const startProps: ButtonProps = {};
    if (this.state.saving) {
      startProps.loading = true;
      startProps.disabled = true;
    }

    const t = this.props.t;
    return (

        {this.renderBeneficiaryID(this.state.benEditing)}

{t("Questionnaire")}

          {record.outcomeSet.name}

{t("Facilitator")}

          {record.user}

        {this.renderTagSection(record.beneficiary, this.state.tagEditing)}
        {this.renderDateSection(this.state.dateEditing)}
        <Button
          primary={true}
          onClick={this.editAnswers}
          style={{ marginTop: "1em" }}
        >
          {t("Edit Answers...")}
        </Button>

            <Button className="cancel" onClick={this.nextPage}>
              {t("Cancel")}
            </Button>
            <Button
              {...startProps}
              className="submit"
              onClick={this.saveRecord}
            >
              {t("Save")}
            </Button>

          {this.state.saveError && (
            <Error text={t("Failed to save your changes")} />
          )}

    );
  }
}

// t("record")
const RecordEditLoader = ApolloLoaderHoC<IProps>(
  "record",
  (p: IProps) => p.data,
  RecordEditInner
);
const RecordEditData = editMeetingTags<IProps>(
  editMeetingDate<IProps>(
    editMeetingBeneficiary(
      getMeeting<IProps>((props) => props.match.params.id)(RecordEditLoader)
    )
  )
);
const RecordEditI18n = withTranslation()(RecordEditData);
// t("Edit Record")
const RecordEditPage = PageWrapperHoC(
  "Edit Record",
  "record-edit",
  RecordEditI18n
);
const RecordEdit = UrlHOC(RecordEditPage);
export { RecordEdit };


text:
/*
 * Used to test RyanGUIBase class
 */

#include "../Headers/RyanGUIBase.h"
#include "../Headers/RyanGUI.h"

#include <iostream>

int main(int argc, char** argv)
{
	RyanGUIBase* base1 = new RyanGUIBase(0, 0, 100, 100, (char*) "Base 1");
	bool base2_success;
	RyanGUIBase* base2 = new RyanGUIBase(10, 10, 80, 80, (char*) "Base 2", RyanGUI::BLACK, RyanGUI::WHITE, NULL, NULL, base1, &base2_success);
	(void) base2;

	std::cout << base2_success << std::endl;

	return 0;
}


text:
package android.text;

import android.annotation.Nullable;

// Based on the native implementation of TabStops in
// frameworks/base/core/jni/android_text_StaticLayout.cpp revision b808260
public class TabStops {
    @Nullable
    private int[] mStops;
    private final int mTabWidth;

    public TabStops(@Nullable int[] stops, int defaultTabWidth) {
        mTabWidth = defaultTabWidth;
        mStops = stops;
    }

    public float width(float widthSoFar) {
        if (mStops != null) {
            for (int i : mStops) {
                if (i > widthSoFar) {
                    return i;
                }
            }
        }
        // find the next tabStop after widthSoFar.
        return (int) ((widthSoFar + mTabWidth) / mTabWidth) * mTabWidth;
    }
}


text:
try:
    import cPickle as pickle
except ImportError:
    import pickle
from stagecraft.tools import get_credentials_or_die
import requests

import django
django.setup()

from collections import defaultdict
from django.db import connection
from pprint import pprint

from stagecraft.apps.organisation.models import Node, NodeType
from stagecraft.apps.dashboards.models import Dashboard

from stagecraft.tools.spreadsheets import SpreadsheetMunger

# These may not be 100% accurate however the derived
# typeOf will be overwritten with more certain information
# based on iterating through all tx rows in build_up_node_dict.
# We use this to to get the full org graph with types even when orgs are
# not associated with a transaction in txex. This is the best guess mapping.
govuk_to_pp_type = {
    "Advisory non-departmental public body": 'agency',
    "Tribunal non-departmental public body": 'agency',
    "Court": 'agency',
    "Sub-organisation": 'agency',
    "Executive agency": 'agency',
    "Devolved administration": 'agency',
    "Ministerial department": 'department',
    "Non-ministerial department": 'agency',
    "Executive office": 'agency',
    "Civil Service": 'agency',
    "Other": 'agency',
    "Executive non-departmental public body": 'agency',
    "Independent monitoring body": 'agency',
    "Public corporation": 'agency',
    "Ad-hoc advisory group": 'agency'
}

def get_govuk_organisations():
    """
    Fetch organisations from the GOV.UK API. This is the canonical source.
    """

    try:
        with open('govuk_orgs.pickle', 'rb') as pickled:
            results = pickle.load(pickled)
    except IOError:
        def get_page(page):
            response = requests.get('https://www.gov.uk/api/organisations?page={}'.format(page))
            return response.json()

        first_page = get_page(1)
        results = first_page['results']

        for page_num in range(2, first_page['pages'] + 1):
            page = get_page(page_num)
            results = results + page['results']

        # Remove any organisations that have closed.
        results = [org for org in results if org['details']['closed_at'] is None]

        with open('govuk_orgs.pickle', 'wb') as pickled:
            pickle.dump(results, pickled, pickle.HIGHEST_PROTOCOL)

    return results

def load_data(client_email, private_key):
    spreadsheets = SpreadsheetMunger({
        'names_transaction_name': 11,
        'names_transaction_slug': 12,
        'names_service_name': 9,
        'names_service_slug': 10,
        'names_tx_id': 19,
        'names_other_notes': 17,
        'names_description': 8
    })
    records = spreadsheets.load(client_email, private_key)
    govuk_response = get_govuk_organisations()
    return records, govuk_response

def make_node(id, title, slug, abbr, type):
    if abbr is not None:
        abbr = abbr.encode('utf-8').strip()
        if abbr == '':
            abbr = None

    return (
        id,
        title.encode('utf-8').strip(),
        slug,
        abbr,
        type,
    )

def govuk_graph(entries):
    nodes = set()
    edges = set()

    for entry in entries:
        node_slug = entry['details']['slug']
        node_id = 'govuk-{}'.format(node_slug).lower()
        nodes.add(make_node(
            node_id,
            entry['title'],
            node_slug,
            entry['details']['abbreviation'],
            govuk_to_pp_type[entry['format']],
        ))

        for child in entry['child_organisations']:
            child_id = 'govuk-{}'.format(child['id'].split('/')[-1]).lower()
            edges.add((
                node_id,
                child_id,
            ))

    return nodes, edges

def index_nodes(nodes, field_index):
    indexed = {}

    for node in nodes:
        value = node[field_index]

        if value in indexed:
            print('Overwriting node in index. [node[{}]: {}]'.format(
                field_index, value))

        if value is not None and value != '':
            indexed[value.lower()] = node

    return indexed

def govuk_node_for_record(record, by_title, by_abbr):
    parent_org = record['agency'] if 'agency' in record else record['department']
    abbr = parent_org['abbr'].lower()
    title = parent_org['name'].lower()

    node = by_abbr.get(abbr, by_title.get(title, None))
    if node is None:
        if abbr == 'inss':
            node = by_title['the insolvency service']
        elif abbr == 'nmo':
            node = by_title['national measurement and regulation office']
        elif abbr == 'tsol':
            node = by_title['government legal department']
        elif abbr == 'research councils':
            node = by_abbr['beis']
        elif abbr == 'visit england':
            node = by_title['visitengland']
        elif abbr == 'arts council':
            node = by_title['arts council england']
        elif abbr.startswith('planning portal / '):
            node = by_abbr['mhclg']
        elif abbr == 'ha':
            node = by_title['highways england']
        elif abbr == 'english heritage':
            node = by_title['historic england']
        elif abbr == 'hmlr':
            node = by_title['hm land registry']
        elif abbr == "dh":
            node = by_abbr['dhsc']
        elif abbr == "dclg":
            node = by_abbr['mhclg']
        elif abbr == "national college for teaching and leadership":
            node = by_abbr['dfe']
        elif abbr == "glaa":
            node = by_abbr['home office']

    return node

def transactions_graph(records, by_title, by_abbr):
    nodes = set()
    edges = set()
    node_to_transactions = defaultdict(list)

    for record in records:
        parent_node = govuk_node_for_record(record, by_title, by_abbr)

        if 'service' not in record:
            print("'{}' doesn't have a service attached".format(record['name']))
        else:
            service = record['service']
            service_slug = service['slug']
            service_id = 'service-{}'.format(service_slug).lower()

            nodes.add(make_node(
                service_id,
                service['name'],
                service_slug,
                None,
                'service',
            ))
            edges.add((parent_node[0], service_id))

            if 'transaction' in record:
                transaction = record['transaction']
                transaction_id = 'transaction-{}-{}'.format(service_slug, transaction['slug']).lower()

                nodes.add(make_node(
                    transaction_id,
                    transaction['name'],
                    transaction['slug'],
                    None,
                    'transaction',
                ))
                edges.add((service_id, transaction_id))
                node_to_transactions[transaction_id].append(record['tx_id'])
            else:
                node_to_transactions[service_id].append(record['tx_id'])

    return nodes, edges, node_to_transactions

def load_organisations(client_email, private_key):
    records, govuk_response = load_data(client_email, private_key)

    govuk_nodes, govuk_edges = govuk_graph(govuk_response)
    by_title = index_nodes(govuk_nodes, 1)
    by_abbr = index_nodes(govuk_nodes, 3)

    tx_nodes, tx_edges, node_to_transactions = transactions_graph(records, by_title, by_abbr)

    nodes = govuk_nodes | tx_nodes
    edges = govuk_edges | tx_edges

    print('Duplicated nodes')
    print(govuk_nodes & tx_nodes)

    print('Duplicated edges')
    print(govuk_edges & tx_edges)

    print('Nodes with multiple tx dashboards')
    pprint([(node_id, transactions) for node_id,
            transactions in node_to_transactions.items()
            if len(transactions) > 1], width=1)

    return nodes, edges, node_to_transactions

def clear_organisation_relations():
    past_relations = {}
    for dashboard in Dashboard.objects.all():
        if dashboard.organisation is not None:
            past_relations[dashboard.id] = {
                'id': dashboard.organisation.id,
                'name': dashboard.organisation.name,
                'slug': dashboard.organisation.slug,
                'abbr': dashboard.organisation.abbreviation,
            }

        dashboard.organisation = None
        dashboard.transaction_cache = None
        dashboard.service_cache = None
        dashboard.agency_cache = None
        dashboard.department_cache = None
        dashboard.save()

    Node.objects.all().delete()

    return past_relations

def node_types():
    return {
        'department': NodeType.objects.get_or_create(name='department')[0],
        'agency': NodeType.objects.get_or_create(name='agency')[0],
        'service': NodeType.objects.get_or_create(name='service')[0],
        'transaction': NodeType.objects.get_or_create(name='transaction')[0],
    }

def create_edge(parent_id, child_id):
    cursor = connection.cursor()
    cursor.execute(
        'INSERT INTO organisation_node_parents(from_node_id, to_node_id) VALUES(%s,%s);',  # noqa
        [child_id, parent_id]
    )

def create_nodes(nodes, edges, type_to_NodeType):
    nodes_to_db = {}
    for node in nodes:
        slug = node[2]
        abbr = node[3]
        if len(slug) > 150:
            print('slug too long "{}"'.format(slug))
            slug = slug[:150]
        if abbr and len(abbr) > 50:
            print('abbreviation too long "{}"'.format(abbr))
            abbr = abbr[:50]
        db_node = Node(
            name=node[1].decode(
                'utf-8').encode('latin1', 'ignore').decode('latin1'),
            slug=slug.decode(
                'utf-8').encode('latin1', 'ignore').decode('latin1'),
            abbreviation=abbr,
            typeOf=type_to_NodeType[node[4]],
        )
        db_node.save()
        nodes_to_db[node[0]] = db_node

    for edge in edges:
        parent_node = nodes_to_db.get(edge[0], None)
        child_node = nodes_to_db.get(edge[1], None)

        if parent_node and child_node:
            if parent_node.id == child_node.id:
                print("Skipping self-referencing edge: {}".format(
                    parent_node.slug))
            else:
                create_edge(parent_node.id, child_node.id)

    return nodes_to_db

def link_transactions(nodes_to_transactions, nodes_to_db):
    dashboards_linked = set()

    for node, transactions in nodes_to_transactions.items():
        db_node = nodes_to_db[node]
        for transaction in transactions:
            try:
                dashboard = Dashboard.objects.get(slug=transaction)
                dashboard.organisation = db_node
                dashboard.save()
                dashboards_linked.add(dashboard.id)
            except Dashboard.DoesNotExist:
                dashboards = list(Dashboard.objects.by_tx_id(transaction))
                if len(dashboards) == 0:
                    print('Ahh no dashboards for {}'.format(transaction))
                else:
                    for dashboard in dashboards:
                        dashboard.organisation = db_node
                        dashboard.save()
                        dashboards_linked.add(dashboard.id)

    return dashboards_linked

def link_remaining(past_relations, dashboards_linked, nodes_to_db, by_abbr):
    for id, node in past_relations.items():
        try:
            dashboard = Dashboard.objects.get(id=id)
        except Dashboard.DoesNotExist:
            print('Lost a dashboard: {}'.format(id))
        if id not in dashboards_linked:
            if 'abbr' not in node or node['abbr'] is None:
                print('could not find an org for {}'.format(dashboard.slug))
                print(node)
            else:
                new_node = by_abbr.get(node['abbr'].lower(), None)
                if new_node:
                    db_node = nodes_to_db[new_node[0]]
                    dashboard.organisation = db_node
                    dashboard.save()
                else:
                    print('could not find an org for {}'.format(dashboard.slug))
                    print(node)

if __name__ == '__main__':
    client_email, private_key = get_credentials_or_die()

    print('Loading organisations')
    nodes, edges, nodes_to_transactions = load_organisations(client_email, private_key)

    print('Clearing organisations')
    past_relations = clear_organisation_relations()

    print('Creating nodes')
    nodes_to_db = create_nodes(nodes, edges, node_types())

    print('Linking transactions')
    dashboards_linked = link_transactions(nodes_to_transactions, nodes_to_db)

    print('Linking outstanding dashboards')
    link_remaining(past_relations, dashboards_linked, nodes_to_db, index_nodes(nodes, 3))


text:
(function () {

	'use strict';

	angular
		.module('app')
		.controller('PaymentSuccessController', PaymentSuccessController);

	PaymentSuccessController.$inject = ['$scope', '$http', '$location', '$state', '$stateParams'];

	function PaymentSuccessController($scope, $http, $location, $state, $stateParams) {

		var orderId = $stateParams.order;

		$scope.touchDetail = function () {
			$state.go('order-detail', {
				order: orderId
			});
		}

	}

})();


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.genomalysis.plugin.configuration.dialogs;

import java.awt.Frame;

import javax.swing.JComponent;

import org.genomalysis.plugin.configuration.ConfigurationException;
import org.genomalysis.plugin.configuration.IPropertyConfigurator;

/**
 *
 * @author ameyers
 */
public class IntConfigurator implements IPropertyConfigurator {

    private IntConfigDialog dlg = null;

    public Object showDialog(JComponent base, Object target)
            throws ConfigurationException {
        if (dlg == null) {
            Frame frame = DialogHelper.getRootFrame(base);
            dlg = new IntConfigDialog(frame);
        }
        dlg.showDialog(target);
        return dlg.getValue();
    }

}