text:
package org.apache.pig.backend.hadoop.executionengine.tez;

import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.counters.Limits;
import org.apache.hadoop.util.StringUtils;
import org.apache.pig.PigConfiguration;
import org.apache.pig.PigException;
import org.apache.pig.PigWarning;
import org.apache.pig.backend.BackendException;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.backend.hadoop.executionengine.Launcher;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStore;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.TezCompiler;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.TezOperPlan;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.TezPOPackageAnnotator;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.TezPlanContainer;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.TezPlanContainerNode;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.TezPlanContainerPrinter;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.operator.NativeTezOper;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.AccumulatorOptimizer;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.CombinerOptimizer;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.LoaderProcessor;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.MultiQueryOptimizerTez;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.NoopFilterRemover;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.ParallelismSetter;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.SecondaryKeyOptimizerTez;
import org.apache.pig.backend.hadoop.executionengine.tez.plan.optimizer.UnionOptimizer;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.plan.CompilationMessageCollector;
import org.apache.pig.impl.plan.CompilationMessageCollector.MessageType;
import org.apache.pig.impl.plan.OperatorKey;
import org.apache.pig.impl.plan.PlanException;
import org.apache.pig.impl.plan.VisitorException;
import org.apache.pig.impl.util.LogUtils;
import org.apache.pig.impl.util.UDFContext;
import org.apache.pig.tools.pigstats.OutputStats;
import org.apache.pig.tools.pigstats.PigStats;
import org.apache.pig.tools.pigstats.tez.TezPigScriptStats;
import org.apache.pig.tools.pigstats.tez.TezScriptState;
import org.apache.pig.tools.pigstats.tez.TezVertexStats;
import org.apache.tez.dag.api.DAG;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.Vertex;
import org.apache.tez.dag.api.client.DAGStatus;
import org.apache.tez.dag.app.dag.impl.DAGSchedulerNaturalOrderControlled;
import org.apache.tez.runtime.library.api.TezRuntimeConfiguration;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * Main class that launches pig for Tez
 */
public class TezLauncher extends Launcher {
    private static final Log log = LogFactory.getLog(TezLauncher.class);
    private static ThreadFactory namedThreadFactory;
    private ExecutorService executor;
    private boolean aggregateWarning = false;
    private TezScriptState tezScriptState;
    private TezPigScriptStats tezStats;
    private TezJob runningJob;

    public TezLauncher() {
        if (namedThreadFactory == null) {
            namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("PigTezLauncher-%d")
                .setDaemon(true)
                .setUncaughtExceptionHandler(new JobControlThreadExceptionHandler())
                .build();
        }
    }

    @Override
    public PigStats launchPig(PhysicalPlan php, String grpName, PigContext pc) throws Exception {
        synchronized (this) {
            if (executor == null) {
                executor = Executors.newSingleThreadExecutor(namedThreadFactory);
            }
        }
        if (pc.getExecType().isLocal()) {
            pc.getProperties().setProperty(TezConfiguration.TEZ_LOCAL_MODE, "true");
            pc.getProperties().setProperty(TezRuntimeConfiguration.TEZ_RUNTIME_OPTIMIZE_LOCAL_FETCH, "true");
            pc.getProperties().setProperty("tez.runtime.transfer.data-via-events.enabled","false");
            pc.getProperties().setProperty(TezConfiguration.TEZ_IGNORE_LIB_URIS, "true");
            pc.getProperties().setProperty(TezConfiguration.TEZ_AM_DAG_SCHEDULER_CLASS, DAGSchedulerNaturalOrderControlled.class.getName());
        }
        Configuration conf = ConfigurationUtil.toConfiguration(pc.getProperties(), true);
        // Make sure MR counter does not exceed limit
        if (conf.get(TezConfiguration.TEZ_COUNTERS_MAX) != null) {
            conf.setInt(org.apache.hadoop.mapreduce.MRJobConfig.COUNTERS_MAX_KEY, Math.max(
                    conf.getInt(org.apache.hadoop.mapreduce.MRJobConfig.COUNTERS_MAX_KEY, 0),
                    conf.getInt(TezConfiguration.TEZ_COUNTERS_MAX, 0)));
        }
        if (conf.get(TezConfiguration.TEZ_COUNTERS_MAX_GROUPS) != null) {
            conf.setInt(org.apache.hadoop.mapreduce.MRJobConfig.COUNTER_GROUPS_MAX_KEY, Math.max(
                    conf.getInt(org.apache.hadoop.mapreduce.MRJobConfig.COUNTER_GROUPS_MAX_KEY, 0),
                    conf.getInt(TezConfiguration.TEZ_COUNTERS_MAX_GROUPS, 0)));
        }

        // This is hacky, but Limits cannot be initialized twice
        try {
            Field f = Limits.class.getDeclaredField("isInited");
            f.setAccessible(true);
            f.setBoolean(null, false);
            Limits.init(conf);
        } catch (Throwable e) {
            log.warn("Error when setting counter limit: " + e.getMessage());
        }

        if (pc.defaultParallel == -1 && !conf.getBoolean(PigConfiguration.PIG_TEZ_AUTO_PARALLELISM, true)) {
            pc.defaultParallel = 1;
        }
        aggregateWarning = conf.getBoolean("aggregate.warning", false);

        TezResourceManager tezResourceManager = TezResourceManager.getInstance();
        tezResourceManager.init(pc, conf);

        String stagingDir = conf.get(TezConfiguration.TEZ_AM_STAGING_DIR);
        String resourcesDir = tezResourceManager.getResourcesDir().toString();
        if (stagingDir == null) {
            // If not set in tez-site.xml, use Pig's tez resources directory as staging directory
            // instead of TezConfiguration.TEZ_AM_STAGING_DIR_DEFAULT
            stagingDir = resourcesDir;
            conf.set(TezConfiguration.TEZ_AM_STAGING_DIR, resourcesDir);
        }
        log.info("Tez staging directory is " + stagingDir + " and resources directory is " + resourcesDir);

        List<TezOperPlan> processedPlans = new ArrayList<TezOperPlan>();

        tezScriptState = TezScriptState.get();
        tezStats = new TezPigScriptStats(pc);
        PigStats.start(tezStats);

        conf.setIfUnset(TezConfiguration.TEZ_USE_CLUSTER_HADOOP_LIBS, "true");
        TezJobCompiler jc = new TezJobCompiler(pc, conf);
        TezPlanContainer tezPlanContainer = compile(php, pc);

        tezStats.initialize(tezPlanContainer);
        tezScriptState.emitInitialPlanNotification(tezPlanContainer);
        tezScriptState.emitLaunchStartedNotification(tezPlanContainer.size()); //number of DAGs to Launch

        boolean stop_on_failure =
                Boolean.valueOf(pc.getProperties().getProperty("stop.on.failure", "false"));
        boolean stoppedOnFailure = false;

        TezPlanContainerNode tezPlanContainerNode;
        TezOperPlan tezPlan;
        int processedDAGs = 0;
        while ((tezPlanContainerNode = tezPlanContainer.getNextPlan(processedPlans)) != null) {
            tezPlan = tezPlanContainerNode.getTezOperPlan();
            processLoadAndParallelism(tezPlan, pc);
            processedPlans.add(tezPlan);
            ProgressReporter reporter = new ProgressReporter(tezPlanContainer.size(), processedDAGs);
            if (tezPlan.size()==1 && tezPlan.getRoots().get(0) instanceof NativeTezOper) {
                // Native Tez Plan
                NativeTezOper nativeOper = (NativeTezOper)tezPlan.getRoots().get(0);
                tezScriptState.emitJobsSubmittedNotification(1);
                nativeOper.runJob(tezPlanContainerNode.getOperatorKey().toString());
            } else {
                TezPOPackageAnnotator pkgAnnotator = new TezPOPackageAnnotator(tezPlan);
                pkgAnnotator.visit();

                runningJob = jc.compile(tezPlanContainerNode, tezPlanContainer);
                //TODO: Exclude vertex groups from numVerticesToLaunch ??
                tezScriptState.dagLaunchNotification(runningJob.getName(), tezPlan, tezPlan.size());
                runningJob.setPigStats(tezStats);

                // Set the thread UDFContext so registered classes are available.
                final UDFContext udfContext = UDFContext.getUDFContext();
                Runnable task = new Runnable() {
                    @Override
                    public void run() {
                        Thread.currentThread().setContextClassLoader(PigContext.getClassLoader());
                        UDFContext.setUdfContext(udfContext.clone());
                        runningJob.run();
                    }
                };

                // Mark the times that the jobs were submitted so it's reflected in job
                // history props. TODO: Fix this. unused now
                long scriptSubmittedTimestamp = System.currentTimeMillis();
                // Job.getConfiguration returns the shared configuration object
                Configuration jobConf = runningJob.getConfiguration();
                jobConf.set("pig.script.submitted.timestamp",
                        Long.toString(scriptSubmittedTimestamp));
                jobConf.set("pig.job.submitted.timestamp",
                        Long.toString(System.currentTimeMillis()));

                Future<?> future = executor.submit(task);
                tezScriptState.emitJobsSubmittedNotification(1);

                boolean jobStarted = false;

                while (!future.isDone()) {
                    if (!jobStarted && runningJob.getApplicationId() != null) {
                        jobStarted = true;
                        String appId = runningJob.getApplicationId().toString();
                        //For Oozie Pig action job id matching compatibility with MR mode
                        log.info("HadoopJobId: "+ appId.replace("application", "job"));
                        tezScriptState.emitJobStartedNotification(appId);
                        tezScriptState.dagStartedNotification(runningJob.getName(), appId);
                    }
                    reporter.notifyUpdate();
                    Thread.sleep(1000);
                }
                // For tez_local mode where PigProcessor destroys all UDFContext
                UDFContext.setUdfContext(udfContext);
                try {
                    // In case of FutureTask there is no uncaught exception
                    // Need to do future.get() to get any exception
                    future.get();
                } catch (ExecutionException e) {
                    setJobException(e.getCause());
                }
            }
            processedDAGs++;
            if (tezPlanContainer.size() == processedDAGs) {
                tezScriptState.emitProgressUpdatedNotification(100);
            } else {
                tezScriptState.emitProgressUpdatedNotification(
                    ((tezPlanContainer.size() - processedDAGs)/tezPlanContainer.size()) * 100);
            }
            handleUnCaughtException(pc);
            boolean tezDAGSucceeded = reporter.notifyFinishedOrFailed();
            tezPlanContainer.updatePlan(tezPlan, tezDAGSucceeded);
            // if stop_on_failure is enabled, we need to stop immediately when any job has failed
            if (!tezDAGSucceeded) {
                if (stop_on_failure) {
                    stoppedOnFailure = true;
                    break;
                } else {
                    log.warn("Ooops! Some job has failed! Specify -stop_on_failure if you "
                            + "want Pig to stop immediately on failure.");
                }
            }
        }

        tezStats.finish();
        tezScriptState.emitLaunchCompletedNotification(tezStats.getNumberSuccessfulJobs());

        for (OutputStats output : tezStats.getOutputStats()) {
            POStore store = output.getPOStore();
            try {
                if (!output.isSuccessful()) {
                    store.getStoreFunc().cleanupOnFailure(
                            store.getSFile().getFileName(),
                            Job.getInstance(output.getConf()));
                } else {
                    store.getStoreFunc().cleanupOnSuccess(
                            store.getSFile().getFileName(),
                            Job.getInstance(output.getConf()));
                }
            } catch (IOException e) {
                throw new ExecException(e);
            } catch (AbstractMethodError nsme) {
                // Just swallow it.  This means we're running against an
                // older instance of a StoreFunc that doesn't implement
                // this method.
            }
        }

        if (stoppedOnFailure) {
            throw new ExecException("Stopping execution on job failure with -stop_on_failure option", 6017,
                    PigException.REMOTE_ENVIRONMENT);
        }

        return tezStats;
    }

    private void handleUnCaughtException(PigContext pc) throws Exception {
      //check for the uncaught exceptions from TezJob thread
        //if the job controller fails before launching the jobs then there are
        //no jobs to check for failure
        if (jobControlException != null) {
            if (jobControlException instanceof PigException) {
                if (jobControlExceptionStackTrace != null) {
                    LogUtils.writeLog("Error message from Tez Job",
                            jobControlExceptionStackTrace, pc
                            .getProperties().getProperty(
                                    "pig.logfile"), log);
                }
                throw jobControlException;
            } else {
                int errCode = 2117;
                String msg = "Unexpected error when launching Tez job.";
                throw new ExecException(msg, errCode, PigException.BUG,
                        jobControlException);
            }
        }
    }

    private void computeWarningAggregate(Map<String, Map<String, Long>> counterGroups, Map<Enum, Long> aggMap) {
        for (Map<String, Long> counters : counterGroups.values()) {
            for (Enum e : PigWarning.values()) {
                if (counters.containsKey(e.toString())) {
                    if (aggMap.containsKey(e.toString())) {
                        Long currentCount = aggMap.get(e.toString());
                        currentCount = (currentCount == null ? 0 : currentCount);
                        if (counters != null) {
                            currentCount += counters.get(e.toString());
                        }
                        aggMap.put(e, currentCount);
                    } else {
                        aggMap.put(e, counters.get(e.toString()));
                    }
                }
            }
        }
    }

    private class ProgressReporter {
        private int totalDAGs;
        private int processedDAGS;
        private int count = 0;
        private int prevProgress = 0;

        public ProgressReporter(int totalDAGs, int processedDAGs) {
            this.totalDAGs = totalDAGs;
            this.processedDAGS = processedDAGs;
        }

        public void notifyUpdate() {
            DAGStatus dagStatus = runningJob.getDAGStatus();
            if (dagStatus != null && dagStatus.getState() == DAGStatus.State.RUNNING) {
                // Emit notification when the job has progressed more than 1%,
                // or every 20 seconds
                int currProgress = Math.round(runningJob.getDAGProgress() * 100f);
                if (currProgress - prevProgress >= 1 || count % 100 == 0) {
                    tezScriptState.dagProgressNotification(runningJob.getName(), -1, currProgress);
                    tezScriptState.emitProgressUpdatedNotification((currProgress + (100 * processedDAGS))/totalDAGs);
                    prevProgress = currProgress;
                }
                count++;
            }
            // TODO: Add new vertex tracking methods to PigTezProgressNotificationListener
            // and emit notifications for individual vertex start, progress and completion
        }

        public boolean notifyFinishedOrFailed() {
            DAGStatus dagStatus = runningJob.getDAGStatus();
            if (dagStatus == null) {
                return false;
            }
            if (dagStatus.getState() == DAGStatus.State.SUCCEEDED) {
                Map<Enum, Long> warningAggMap = new HashMap<Enum, Long>();
                DAG dag = runningJob.getDAG();
                for (Vertex v : dag.getVertices()) {
                    TezVertexStats tts = tezStats.getVertexStats(dag.getName(), v.getName());
                    if (tts == null) {
                        continue; //vertex groups
                    }
                    Map<String, Map<String, Long>> counterGroups = tts.getCounters();
                    if (counterGroups == null) {
                        log.warn("Counters are not available for vertex " + v.getName() + ". Not computing warning aggregates.");
                    } else {
                        computeWarningAggregate(counterGroups, warningAggMap);
                    }
                }
                if (aggregateWarning) {
                    CompilationMessageCollector.logAggregate(warningAggMap, MessageType.Warning, log);
                }
                return true;
            }
            return false;
        }
    }

    @Override
    public void explain(PhysicalPlan php, PigContext pc, PrintStream ps,
            String format, boolean verbose) throws PlanException,
            VisitorException, IOException {
        log.debug("Entering TezLauncher.explain");
        TezPlanContainer tezPlanContainer = compile(php, pc);

        if (format.equals("text")) {
            TezPlanContainerPrinter printer = new TezPlanContainerPrinter(ps, tezPlanContainer);
            printer.setVerbose(verbose);
            printer.visit();
        } else {
            // TODO: add support for other file format
            throw new IOException("Non-text output of explain is not supported.");
        }
    }

    public TezPlanContainer compile(PhysicalPlan php, PigContext pc)
            throws PlanException, IOException, VisitorException {
        TezCompiler comp = new TezCompiler(php, pc);
        comp.compile();
        TezPlanContainer planContainer = comp.getPlanContainer();
        // Doing a sort so that test plan printed remains same between jdk7 and jdk8
        List<OperatorKey> opKeys = new ArrayList<>(planContainer.getKeys().keySet());
        Collections.sort(opKeys);
        for (OperatorKey opKey : opKeys) {
            TezOperPlan tezPlan = planContainer.getOperator(opKey).getTezOperPlan();
            optimize(tezPlan, pc);
        }
        return planContainer;
    }

    private void optimize(TezOperPlan tezPlan, PigContext pc) throws VisitorException {
        Configuration conf = ConfigurationUtil.toConfiguration(pc.getProperties());
        boolean aggregateWarning = conf.getBoolean("aggregate.warning", false);

        NoopFilterRemover filter = new NoopFilterRemover(tezPlan);
        filter.visit();

        // Run CombinerOptimizer on Tez plan
        boolean nocombiner = conf.getBoolean(PigConfiguration.PIG_EXEC_NO_COMBINER, false);
        if (!pc.inIllustrator && !nocombiner)  {
            boolean doMapAgg = Boolean.parseBoolean(pc.getProperties().getProperty(
                    PigConfiguration.PIG_EXEC_MAP_PARTAGG, "false"));
            CombinerOptimizer co = new CombinerOptimizer(tezPlan, doMapAgg);
            co.visit();
            co.getMessageCollector().logMessages(MessageType.Warning, aggregateWarning, log);
        }

        // Run optimizer to make use of secondary sort key when possible for nested foreach
        // order by and distinct. Should be done before AccumulatorOptimizer
        boolean noSecKeySort = conf.getBoolean(PigConfiguration.PIG_EXEC_NO_SECONDARY_KEY, false);
        if (!pc.inIllustrator && !noSecKeySort)  {
            SecondaryKeyOptimizerTez skOptimizer = new SecondaryKeyOptimizerTez(tezPlan);
            skOptimizer.visit();
        }

        boolean isUnionOpt = conf.getBoolean(PigConfiguration.PIG_TEZ_OPT_UNION, true);
        List<String> supportedStoreFuncs = null;
        String unionSupported = conf.get(PigConfiguration.PIG_TEZ_OPT_UNION_SUPPORTED_STOREFUNCS);
        if (unionSupported != null && unionSupported.trim().length() > 0) {
            supportedStoreFuncs = Arrays
                    .asList(StringUtils.split(unionSupported.trim()));
        }
        List<String> unionUnsupportedStoreFuncs = null;
        String unionUnSupported = conf.get(PigConfiguration.PIG_TEZ_OPT_UNION_UNSUPPORTED_STOREFUNCS);
        if (unionUnSupported != null && unionUnSupported.trim().length() > 0) {
            unionUnsupportedStoreFuncs = Arrays
                    .asList(StringUtils.split(unionUnSupported.trim()));
        }

        boolean isMultiQuery = conf.getBoolean(PigConfiguration.PIG_OPT_MULTIQUERY, true);
        if (isMultiQuery) {
            // reduces the number of TezOpers in the Tez plan generated
            // by multi-query (multi-store) script.
            MultiQueryOptimizerTez mqOptimizer = new MultiQueryOptimizerTez(
                    tezPlan, isUnionOpt, supportedStoreFuncs,
                    unionUnsupportedStoreFuncs);
            mqOptimizer.visit();
        }

        // Run AccumulatorOptimizer on Tez plan
        boolean isAccum = conf.getBoolean(PigConfiguration.PIG_OPT_ACCUMULATOR, true);
        if (isAccum) {
            AccumulatorOptimizer accum = new AccumulatorOptimizer(tezPlan);
            accum.visit();
        }

        // Use VertexGroup in Tez
        if (isUnionOpt) {
            UnionOptimizer uo = new UnionOptimizer(tezPlan, supportedStoreFuncs, unionUnsupportedStoreFuncs);
            uo.visit();
        }

    }

    public static void processLoadAndParallelism(TezOperPlan tezPlan, PigContext pc) throws VisitorException {
        if (!pc.inExplain && !pc.inDumpSchema) {
            LoaderProcessor loaderStorer = new LoaderProcessor(tezPlan, pc);
            loaderStorer.visit();

            ParallelismSetter parallelismSetter = new ParallelismSetter(tezPlan, pc);
            parallelismSetter.visit();
            tezPlan.setEstimatedParallelism(parallelismSetter.getEstimatedTotalParallelism());
        }
    }

    @Override
    public void kill() throws BackendException {
        if (runningJob != null) {
            try {
                runningJob.killJob();
            } catch (Exception e) {
                throw new BackendException(e);
            }
        }
        destroy();
    }

    @Override
    public void killJob(String jobID, Configuration conf) throws BackendException {
        if (runningJob != null && runningJob.getApplicationId().toString().equals(jobID)) {
            try {
                runningJob.killJob();
            } catch (Exception e) {
                throw new BackendException(e);
            }
        } else {
            log.info("Cannot find job: " + jobID);
        }
    }

    @Override
    public void destroy() {
        try {
            if (executor != null && !executor.isShutdown()) {
                log.info("Shutting down thread pool");
                executor.shutdownNow();
            }
        } catch (Exception e) {
            log.warn("Error shutting down threadpool");
        }
    }

}


text:
<!DOCTYPE html>

A single line must not be split into two pages.
This test checks if a single line is not split into two pages.
To run this test manually, print this page.

And now for some really long unbreakable lines:

redpajama_set_name: RedPajamaGithub


text:
using namespace llvm;

//===----------------------------------------------------------------------===//
// Instruction Selector Implementation
//===----------------------------------------------------------------------===//

//===----------------------------------------------------------------------===//
// MBlazeDAGToDAGISel - MBlaze specific code to select MBlaze machine
// instructions for SelectionDAG operations.
//===----------------------------------------------------------------------===//
namespace {

class MBlazeDAGToDAGISel : public SelectionDAGISel {

  /// TM - Keep a reference to MBlazeTargetMachine.
  MBlazeTargetMachine &TM;

  /// Subtarget - Keep a pointer to the MBlazeSubtarget around so that we can
  /// make the right decision when generating code for different targets.
  const MBlazeSubtarget &Subtarget;

public:
  explicit MBlazeDAGToDAGISel(MBlazeTargetMachine &tm) :
  SelectionDAGISel(tm),
  TM(tm), Subtarget(tm.getSubtarget<MBlazeSubtarget>()) {}

  // Pass Name
  virtual const char *getPassName() const {
    return "MBlaze DAG->DAG Pattern Instruction Selection";
  }
private:
  // Include the pieces autogenerated from the target description.
  #include "MBlazeGenDAGISel.inc"

  /// getTargetMachine - Return a reference to the TargetMachine, casted
  /// to the target-specific type.
  const MBlazeTargetMachine &getTargetMachine() {
    return static_cast<const MBlazeTargetMachine &>(TM);
  }

  /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
  /// to the target-specific type.
  const MBlazeInstrInfo *getInstrInfo() {
    return getTargetMachine().getInstrInfo();
  }

  SDNode *getGlobalBaseReg();
  SDNode *Select(SDNode *N);

  // Complex Pattern.
  bool SelectAddr(SDNode *Op, SDValue N,
                  SDValue &Base, SDValue &Offset);

  // Address Selection
  bool SelectAddrRegReg(SDNode *Op, SDValue N, SDValue &Base, SDValue &Index);
  bool SelectAddrRegImm(SDNode *Op, SDValue N, SDValue &Disp, SDValue &Base);

  // getI32Imm - Return a target constant with the specified value, of type i32.
  inline SDValue getI32Imm(unsigned Imm) {
    return CurDAG->getTargetConstant(Imm, MVT::i32);
  }
};

}

/// isIntS32Immediate - This method tests to see if the node is either a 32-bit
/// or 64-bit immediate, and if the value can be accurately represented as a
/// sign extension from a 32-bit value.  If so, this returns true and the
/// immediate.
static bool isIntS32Immediate(SDNode *N, int32_t &Imm) {
  unsigned Opc = N->getOpcode();
  if (Opc != ISD::Constant)
    return false;

  Imm = (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
  if (N->getValueType(0) == MVT::i32)
    return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
  else
    return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
}

static bool isIntS32Immediate(SDValue Op, int32_t &Imm) {
  return isIntS32Immediate(Op.getNode(), Imm);
}

/// SelectAddressRegReg - Given the specified addressed, check to see if it
/// can be represented as an indexed [r+r] operation.  Returns false if it
/// can be more efficiently represented with [r+imm].
bool MBlazeDAGToDAGISel::
SelectAddrRegReg(SDNode *Op, SDValue N, SDValue &Base, SDValue &Index) {
  if (N.getOpcode() == ISD::FrameIndex) return false;
  if (N.getOpcode() == ISD::TargetExternalSymbol ||
      N.getOpcode() == ISD::TargetGlobalAddress)
    return false;  // direct calls.

  int32_t imm = 0;
  if (N.getOpcode() == ISD::ADD || N.getOpcode() == ISD::OR) {
    if (isIntS32Immediate(N.getOperand(1), imm))
      return false;    // r+i

    if (N.getOperand(0).getOpcode() == ISD::TargetJumpTable ||
        N.getOperand(1).getOpcode() == ISD::TargetJumpTable)
      return false; // jump tables.

    Base = N.getOperand(1);
    Index = N.getOperand(0);
    return true;
  }

  return false;
}

/// Returns true if the address N can be represented by a base register plus
/// a signed 32-bit displacement [r+imm], and if it is not better
/// represented as reg+reg.
bool MBlazeDAGToDAGISel::
SelectAddrRegImm(SDNode *Op, SDValue N, SDValue &Disp, SDValue &Base) {
  // If this can be more profitably realized as r+r, fail.
  if (SelectAddrRegReg(Op, N, Disp, Base))
    return false;

  if (N.getOpcode() == ISD::ADD || N.getOpcode() == ISD::OR) {
    int32_t imm = 0;
    if (isIntS32Immediate(N.getOperand(1), imm)) {
      Disp = CurDAG->getTargetConstant(imm, MVT::i32);
      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
        Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
      } else {
        Base = N.getOperand(0);
      }
      DEBUG( errs() << "WESLEY: Using Operand Immediate\n" );
      return true; // [r+i]
    }
  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
    // Loading from a constant address.
    uint32_t Imm = CN->getZExtValue();
    Disp = CurDAG->getTargetConstant(Imm, CN->getValueType(0));
    Base = CurDAG->getRegister(MBlaze::R0, CN->getValueType(0));
    DEBUG( errs() << "WESLEY: Using Constant Node\n" );
    return true;
  }

  Disp = CurDAG->getTargetConstant(0, TM.getTargetLowering()->getPointerTy());
  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
    Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
  else
    Base = N;
  return true;      // [r+0]
}

/// getGlobalBaseReg - Output the instructions required to put the
/// GOT address into a register.
SDNode *MBlazeDAGToDAGISel::getGlobalBaseReg() {
  unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
  return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
}

/// ComplexPattern used on MBlazeInstrInfo
/// Used on MBlaze Load/Store instructions
bool MBlazeDAGToDAGISel::
SelectAddr(SDNode *Op, SDValue Addr, SDValue &Offset, SDValue &Base) {
  // if Address is FI, get the TargetFrameIndex.
  if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
    Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
    Offset = CurDAG->getTargetConstant(0, MVT::i32);
    return true;
  }

  // on PIC code Load GA
  if (TM.getRelocationModel() == Reloc::PIC_) {
    if ((Addr.getOpcode() == ISD::TargetGlobalAddress) ||
        (Addr.getOpcode() == ISD::TargetConstantPool) ||
        (Addr.getOpcode() == ISD::TargetJumpTable)){
      Base   = CurDAG->getRegister(MBlaze::R15, MVT::i32);
      Offset = Addr;
      return true;
    }
  } else {
    if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
        Addr.getOpcode() == ISD::TargetGlobalAddress))
      return false;
  }

  // Operand is a result from an ADD.
  if (Addr.getOpcode() == ISD::ADD) {
    if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
      if (Predicate_immSExt16(CN)) {

        // If the first operand is a FI, get the TargetFI Node
        if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
                                    (Addr.getOperand(0))) {
          Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
        } else {
          Base = Addr.getOperand(0);
        }

        Offset = CurDAG->getTargetConstant(CN->getZExtValue(), MVT::i32);
        return true;
      }
    }
  }

  Base   = Addr;
  Offset = CurDAG->getTargetConstant(0, MVT::i32);
  return true;
}

/// Select instructions not customized! Used for
/// expanded, promoted and normal instructions
SDNode* MBlazeDAGToDAGISel::Select(SDNode *Node) {
  unsigned Opcode = Node->getOpcode();
  DebugLoc dl = Node->getDebugLoc();

  // Dump information about the Node being selected
  DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");

  // If we have a custom node, we already have selected!
  if (Node->isMachineOpcode()) {
    DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
    return NULL;
  }

  ///
  // Instruction Selection not handled by the auto-generated
  // tablegen selection should be handled here.
  ///
  switch(Opcode) {
    default: break;

    // Get target GOT address.
    case ISD::GLOBAL_OFFSET_TABLE:
      return getGlobalBaseReg();

    case ISD::FrameIndex: {
        SDValue imm = CurDAG->getTargetConstant(0, MVT::i32);
        int FI = dyn_cast<FrameIndexSDNode>(Node)->getIndex();
        EVT VT = Node->getValueType(0);
        SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);
        unsigned Opc = MBlaze::ADDI;
        if (Node->hasOneUse())
          return CurDAG->SelectNodeTo(Node, Opc, VT, TFI, imm);
        return CurDAG->getMachineNode(Opc, dl, VT, TFI, imm);
    }

    /// Handle direct and indirect calls when using PIC. On PIC, when
    /// GOT is smaller than about 64k (small code) the GA target is
    /// loaded with only one instruction. Otherwise GA's target must
    /// be loaded with 3 instructions.
    case MBlazeISD::JmpLink: {
      if (TM.getRelocationModel() == Reloc::PIC_) {
        SDValue Chain  = Node->getOperand(0);
        SDValue Callee = Node->getOperand(1);
        SDValue R20Reg = CurDAG->getRegister(MBlaze::R20, MVT::i32);
        SDValue InFlag(0, 0);

        if ( (isa<GlobalAddressSDNode>(Callee)) ||
             (isa<ExternalSymbolSDNode>(Callee)) )
        {
          /// Direct call for global addresses and external symbols
          SDValue GPReg = CurDAG->getRegister(MBlaze::R15, MVT::i32);

          // Use load to get GOT target
          SDValue Ops[] = { Callee, GPReg, Chain };
          SDValue Load = SDValue(CurDAG->getMachineNode(MBlaze::LW, dl,
                                 MVT::i32, MVT::Other, Ops, 3), 0);
          Chain = Load.getValue(1);

          // Call target must be on T9
          Chain = CurDAG->getCopyToReg(Chain, dl, R20Reg, Load, InFlag);
        } else
          /// Indirect call
          Chain = CurDAG->getCopyToReg(Chain, dl, R20Reg, Callee, InFlag);

        // Emit Jump and Link Register
        SDNode *ResNode = CurDAG->getMachineNode(MBlaze::BRLID, dl, MVT::Other,
                                                 MVT::Flag, R20Reg, Chain);
        Chain  = SDValue(ResNode, 0);
        InFlag = SDValue(ResNode, 1);
        ReplaceUses(SDValue(Node, 0), Chain);
        ReplaceUses(SDValue(Node, 1), InFlag);
        return ResNode;
      }
    }
  }

  // Select the default instruction
  SDNode *ResNode = SelectCode(Node);

  DEBUG(errs() << "=> ");
  if (ResNode == NULL || ResNode == Node)
    DEBUG(Node->dump(CurDAG));
  else
    DEBUG(ResNode->dump(CurDAG));
  DEBUG(errs() << "\n");
  return ResNode;
}

/// createMBlazeISelDag - This pass converts a legalized DAG into a
/// MBlaze-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createMBlazeISelDag(MBlazeTargetMachine &TM) {
  return new MBlazeDAGToDAGISel(TM);
}


text:
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var ObjectId = mongoose.Schema.Types.ObjectId;
var Tag = require("./tag_model");

var TrackSchema   = new Schema({
	name: String,
	tag_id: [{ type: ObjectId, index: true, ref: "Tag" }],
	tasks: [{
		name: String,
		category: { type: String, validate: /call|email|follow_up|meeting|milestone|site_visit/, index: true, default: "email" },
		due_after_event: { type: String, validate: /track_start|last_task/, index: true, default: "last_task" },
		due_after_days: Number,
	}],
	date_created: { type: Date, default: Date.now },
	_owner_id: ObjectId
}, {
	timestamps: true
});

TrackSchema.set("_perms", {
	setup: "crud",
	admin: "r",
});

module.exports = mongoose.model('Track', TrackSchema);


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

function getViewportWidth() {
  var width = void 0;
  if (document.documentElement) {
    width = document.documentElement.clientWidth;
  }

  if (!width && document.body) {
    width = document.body.clientWidth;
  }

  return width || 0;
}

function getViewportHeight() {
  var height = void 0;
  if (document.documentElement) {
    height = document.documentElement.clientHeight;
  }

  if (!height && document.body) {
    height = document.body.clientHeight;
  }

  return height || 0;
}

function getViewportDimensions() {
  return {
    width: window.innerWidth || getViewportWidth(),
    height: window.innerHeight || getViewportHeight()
  };
}

getViewportDimensions.withoutScrollbars = function () {
  return {
    width: getViewportWidth(),
    height: getViewportHeight()
  };
};

exports.default = getViewportDimensions;


text:
<?php
/*
Author: Kevin Griffiths
URL: http://chasemg.com
*/
include "db_include.php";
$html = '';
$id = $_POST['id'];
$patient_id = $_POST['patient_id'];
if(get_user_role() == 'subscriber')	{
		$lookup = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix. "users WHERE ID=$patient_id");
		foreach($lookup as $lu)	{
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$patient = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "patients WHERE user_id=$patient_id");
			foreach($patient as $p)	{
				$goal = $p->top_goal;
				if($p->image != '')	{
					$html .= "image."'>";
				} else {
					$html .= "";
				}
			}
			$html .= '
';
			$html .= "
Welcome ". $lu->display_name ."";
			$html .= '
Your top goal is to ';
			$goals = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "goals WHERE goal_id=$goal");
			foreach($goals as $g)	{
				$html .= $g->goal.".";
			}
			$html .= '
';
			$html .= '

';
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
';
/******************** Recent Vitals ***************************/
			$html .= '
';
			$html .= '
';
			$html .= '
recent vitals
';
			$html .= '
';
			$vitals = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "vitals WHERE user_id='$patient_id' ORDER BY taken_date DESC LIMIT 1");
			foreach($vitals as $v)	{
				$bp = $v->bp;
				$html .= '

Blood Pressure

'.$bp.'

';
				$html .= '

Resting Pulse

'.$v->pulse.'

';
				$html .= '

Temperature

'.$v->temperature.'

';
				$html .= '

Respiration

'.$v->respiration.'

';
			}
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
See full recent vitals list
';
			$html .= '
';
			$html .= '
'; // END OF .widget_row

/********************* Small Widgets *************************************/
			$html .= '
';

/********************** Immunizations ***************************************/
			//$html .= '
';

			$html .= '
';

			$html .= '
';
			$html .= '
';
			$html .= '
Immunizations
';
			$html .= '
';
			$immun = $pdb->get_results("SELECT *, date_format(date, '%m/%d/%Y') as date FROM ".$wpdb->prefix. "immunizations WHERE user_id='$patient_id'");
			$html .= '
';
			$html .= '
	Doses	Date
';
			foreach($immun as $x => $i)
			{

				$html .= sprintf("
immune %s	%s	%s
", $x + 1, $i->doses, $i->date);

			}
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
See full immunizations list
';
			$html .= '
';
			$html .= '
';

/********************** Allergies ***************************************/
			//$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
Allergies
';
			$html .= '
';
			$allergies = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "allergies WHERE user_id='$patient_id'");
			foreach($allergies as $allergy)	{
				$x=0;
				$html .= '
';
				$html .= '
	Severity
';
				$unserialized_allergies = unserialize($allergy->allergies);
				foreach($unserialized_allergies as $a)	{
					if($x >= 3)	{
						break;
					}
					$html .= '
';
					$html .= "".$a[0]."	".$a[1]."	";
					$html .= '
';
					$x++;
				}
				$html .= '
';
			}
			$html .= '

';
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
See full allergies list
';
			$html .= '
';
			$html .= '
';
			$html .= '
';	// END OF .widget_row
/********************** Labs ***************************************/
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
Lab Results
';
			$html .= '
';

			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
See full lab results
';
			$html .= '
';
			$html .= '
';

/********************** Medical History ***************************************/
			$html .= '
';
			$html .= '
';
			$html .= '
Medical History
';
			$html .= '
';
			$exam_dates = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "exams WHERE user_id='$patient_id' AND exam_type='1' ORDER BY exam_date DESC LIMIT 1");
			foreach($exam_dates as $exam)	{
				$exam_date = $exam->exam_date;
			}
			$medical = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "medical_history WHERE user_id='$patient_id' LIMIT 1");
			foreach($medical as $m)	{
				$html .= '
Date of last physical exam: '.date("m/d/Y", $exam_date).'
';
				$notes = $m->notes;
				$stripped_notes = (strlen($notes) > 225) ? substr($notes,0,225).'...' : $notes;
				$html .= '
'.$stripped_notes.'
';

			}
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
See full recent medical history
';
			$html .= '
';
			$html .= '
';
			$html .= '
';	// END OF .widget_row

/********************** Medications ***************************************/
			$html .= '
';

			$html .= '
';

			$html .= '
';
			$html .= '
Medications
';
			$html .= '
';

			$html .= '
';
			$html .= '
';

			$html .= '
';
			$html .= '
See medication list
';
			$html .= '
';

			$html .= '
';

			//$html .= '
';
/********************** Social Life ***************************************/
			$html .= '
';
			$html .= '
';
			$html .= '
My Social Life
';
			$html .= '
';
			$social_life = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "social_life WHERE user_id='$patient_id'");

			foreach($social_life as $s)	{
				$smoker = $s->smoker;
				$marital_state = $s->marital_state;
				$month = date("m",$s->dob);
				$day = date("d",$s->dob);
				$questions = unserialize($s->questions);
				$html .= '
';
					$html .= '
';
						$html .= '
';
							$ms = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "marital_status WHERE id='$marital_state'");
							foreach($ms as $m)	{
								$html .= '
'.$m->marital_status.'
';
								$html .= '
icon.'.png">
';
							}
						$html .= '
';
						$html .= '
';
							$st = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "smoker_type WHERE id='$smoker'");
							foreach($st as $sp)	{
								$html .= '
'.$sp->smoker_type.'
';
								$html .= '
icon.'.png">
';
							}
						$html .= '
';
						$html .= '
';
							$html .= '
Birthday
';
							$html .= '

'.$month.'|'.$day.'

';
						$html .= '
';
					$html .= '
';
				$html .= '
';
				$description = $s->description;
				$stripped_description = (strlen($description) > 120) ? substr($description,0,120).'...' : $description;
				$html .= '
'.$stripped_description.'
';
			}

			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
My Social Life
';
			$html .= '
';
			$html .= '
';
			$html .= '
';
			$html .= '
';	// END OF .widget_row
		}
		echo $html;
} else {

		if (get_user_role() == 'lab_doctor')
		{
			include('lab_dashboard.php');
		}
		elseif (get_user_role() == 'doctor')
		{

			$lookup = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix. "users WHERE ID=$id");

			foreach($lookup as $lu)	{
				$html .= '
';
					$html .= '
';
						$html .= '
';
							$html .= '';
						$html .= '
';
						$html .= '
';
							$html .= 'Welcome, Dr. ' . $lu->display_name . '.';
						$html .= '
';
					$html .= '
';
				$html .= '
'; // End .dashboard_goals

			$html .= '
';
			$html .= '
';
				$html .= '
';
					$html .= '
soap notes
';
					$html .= '
';
						$html .= '
Please select a patient to get started.
';
						$html .= '';
						$html .= '
Patient Search
';
					$html .= '
';
				$html .= '
';
			$html .= '
';
			$html .= '

';

/******************** Small widgets ***************************/
			$html .= '
';

				$html .= '
';
/******************** Scheduling ******************************/
					$html .= '
';
						$html .= '
';
							$html .= '
';
								$html .= '
';
									$html .= '

';
									$html .= '

';
									$html .= '

';
								$html .= '
';
							$html .= '
';
							$html .= '
';
							$html .= '
Appointments
';
							$html .= '
';
								$html .= '

01/12/15 at 10:00am

01/12/15 at 10:10am

01/12/15 at 10:20am

01/12/15 at 10:30am

01/12/15 at 10:40am

01/12/15 at 10:50am

01/12/15 at 11:00am

01/12/15 at 11:10am

01/12/15 at 11:20am

01/12/15 at 11:30am

01/12/15 at 11:40am

01/12/15 at 11:50am

';
							$html .= '
';
							$html .= '
';
						$html .= '
';
						$html .= '
';
						$html .= '
See full schedule
';
						$html .= '
';
					$html .= '
';
/******************** Messaging *******************************/
					$html .= '
';
						$html .= '
';
						$html .= '
Messages (

)
';
						$html .= '
';
						$html .= "
";
						$html .= '<input type="hidden" id="message_id" value="0">';
							$limit = 3;
								$messages = $pdb->get_results("SELECT * FROM ".$wpdb->prefix. "communication AS c INNER JOIN ".$wpdb->prefix. "doctors AS d  ON d.user_id=c.user_id WHERE c.user_id='$id' order by c.id desc LIMIT ". $limit * 1 . "");

							if($messages)	{
								foreach($messages as $message)	{
									$html .= "
id."'>";
									if($message->read == 0)	{
										$html .= '
';
									} else {
										$html .= '
';
									}
									$html .= '
';
									$html .= "
";
									$subject = $message->subject;
									$stripped_subject = (strlen($subject) > 25) ? substr($subject,0,25).'...' : $subject;
									$html .= "
".$stripped_subject."

";
									$from = $message->from;
									$from_query = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix. "users WHERE ID='$from'");
									foreach($from_query as $f)	{
										$html .= "
".$f->display_name."
";
									}
									$html .= "
";
									$html .= "
".date('M d, Y', $message->date_sent)."
";
									$html .= "
";
									$html .= "
";
									$html .= "
";
								}
							} else {
								$html .= "
";
								$html .= '
';
								$html .= '
';
								$html .= 'No Messages.';
								$html .= "
";
								$html .= "
";
							}
						$html .= "
";
						$html .= '
';
						$html .= '
';
						$html .= '
';
						$html .= '
See full messages
';
						$html .= '
';
					$html .= '
';

				$html .= '
';

				$html .= '
';
/******************** Labs ************************************/
					$html .= '
';
						$html .= '
';
						$html .= '';
						$html .= 'Launch';
						$html .= '
';
						$html .= '
';
						$html .= '
See full incoming labs
';
						$html .= '
';
					$html .= '
';
/******************** Referrals *******************************/
					$html .= '
';
						$html .= '
';
						$html .= '
Referrals
';

						$html .= '
';

						$html .= '
';
						$html .= '';
						$html .= '
Add Referral Doctor
';
						$html .= '
';

						$html .= '
';

						$html .= '
';
						$html .= '';
						$html .= '
View all Referral Doctors
';
						$html .= '
';

						$html .= '
';

						$html .= '
';
						$html .= '
';
						$html .= '
See referrals
';
						$html .= '
';
					$html .= '
';

				$html .= '
';

			$html .= '
';

			echo $html;
		}

	}
}
?>


text:
class Restaurant < ActiveRecord::Base
  has_many   :recipe
  belongs_to :user

  validates :name,   presence:true
  validates :phone1, presence:true, format:{ with: /\A[0-9\-]*\z/, on: :create}

  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "200x200>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

end


text:
var moment = require("moment");

var events = Alloy.Collections.events;

var currentDay = moment().day(1);
var currentDayNext = moment().day(7);

events.thisWeek(currentDay, currentDayNext);

$.weekNow.text = currentDay.format("MM/DD/YYYY")+' - '+ currentDayNext.format("MM/DD/YYYY");

//function updateUI(){}

function transformData(model) {
	var attrs = model.toJSON();
	var date = moment.unix(model.get('time'));
	var dateEnd = moment.unix(model.get('end'));
	attrs.date_day = date.format("DD");
	attrs.date_dow = date.format("ddd");
	attrs.time = 'from ' + date.format("h:mm a") + ' to' + dateEnd.format("h:mm a");

	return attrs;
}

$.table.addEventListener('click', function(_e) {
    var detailController = Alloy.createController('event_detail', {
        parentTab : $.eventsTab,
        data : events.at(_e.index)
    });
    $.eventsTab.open(detailController.getView());
});

function doClickNext(e){
    Titanium.API.info("You clicked the next week button");
    currentDay.add('days', 7);
    currentDayNext.add('days', 7);
    $.weekNow.text = currentDay.format("MM/DD/YYYY")+' - '+ currentDayNext.format("MM/DD/YYYY");
    events.thisWeek(currentDay, currentDayNext);
};

function doClickPrev(e){
    Titanium.API.info("You clicked the previous week button");
    $.weekNow.text = 'Last Week';
    currentDay.subtract('days', 7);
    currentDayNext.subtract('days', 7);
    $.weekNow.text = currentDay.format("MM/DD/YYYY")+' - '+ currentDayNext.format("MM/DD/YYYY");
    events.thisWeek(currentDay, currentDayNext);
};


text:
var Ellipse = require('./Ellipse');

/**
 * Creates a new Ellipse instance based on the values contained in the given source.
 *
 * @function Phaser.Geom.Ellipse.Clone
 * @since 3.0.0
 *
 * @param {Phaser.Geom.Ellipse} source - The Ellipse to be cloned. Can be an instance of an Ellipse or a ellipse-like object, with x, y, width and height properties.
 *
 * @return {Phaser.Geom.Ellipse} A clone of the source Ellipse.
 */
var Clone = function (source)
{
    return new Ellipse(source.x, source.y, source.width, source.height);
};

module.exports = Clone;


text:
<?php

namespace Mweb\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;

class MenuController extends EntityController
{
//    public function deleteAction($entity,$id, Request $request)
//    {
//
//        $em = $this->getDoctrine()->getManager();
//        $repo = $em->getRepository('LECMSBundle:MenuElement');
//
//        $menu = $repo->find($id);
//
//        if (null === $menu)
//        {
//            return $this->createNotFoundException('This menu doesn\'t exists');
//        }
//        $name = $menu->getName();
//        $em->remove($menu);
//        $em->flush();
//
//        $this->get('session')->getFlashBag()->add(
//                'success',
//                'Menu '.$name.' Deleted :)'
//                );
//        $url = $this->generateUrl('sk_admin_menulist');
//        return $this->redirect($url);
//
//    }

    public function listAction($entity,Request $request)
    {

        $em = $this->getDoctrine()->getManager();
        $repo = $em->getRepository('LECMSBundle:MenuElement');

        $adminParams= $this->container->getParameter('le_admin.entities');
        $entityParams = $adminParams[$entity];
//        $repo->setDefaultLocale($locale);
        $entities = $repo->findRootMenu($request->getLocale());
//        die('sfsdf');
        return $this->render('LEAdminBundle:entity:list.html.twig',['entityName'=>$entity,'entities'=>$entities,'entityParams'=>$entityParams]);

    }

    public function editAction(Request $request)
    {
        $locale = $request->getLocale();
        $em = $this->getDoctrine()->getManager();
        $repo = $em->getRepository('LECMSBundle:MenuElement');
        if (null !== $id)
        {
            $repo->setDefaultLocale($locale);
            $menu = $repo->findMenu($id);
        }
        else
        {
            $menu = new MenuElement();
        }

        $entitiesParams = $this->container->getParameter('le_admin.entities');
        $entities = [];
        foreach ($entitiesParams as $entityName => $entityParams)
        {

            if (array_key_exists( 'menuIntegrable',$entityParams) && $entityParams['menuIntegrable'])
            {
                $repo = $em->getRepository($entityParams['class']);
                $subEntities = $repo->findAll();
                $entities[$entityName] = $subEntities;
            }

        }

        $form = $this->createForm(new MenuElementType($entities),$menu);

        $request = $this->get('request');

        if ($request->getMethod() == 'POST')
        {
            $menuArray = json_decode($request->request->get('jsonmenu'));
            $children = $this->menuArrayToEntities($menuArray,$em,$menu,$locale);
            $menu->setName($request->request->get('name'));
            $menu->setTextId($request->request->get('textId'));
            $menu->setChildren($children);
            $em->persist($menu);

            $em->flush();

            $url = $this->generateUrl('le_admin_list_entity',['entity'=>'Menu']);

            return $this->redirect($url);

        }

        $currentMenuArray = $this->menuEntitiesToArray($menu);

        return $this->render('LEAdminBundle:Menu:menu-edit.html.twig',['entity'=>$menu,'menu'=>$menu,'form'=>$form->createView(),'currentMenuArray'=>$currentMenuArray,'entities'=>$entities]);
    }

    private function menuArrayToEntities($menuArray, \Doctrine\ORM\EntityManager $em,  MenuElement $parent = null,$locale)
    {

        $collection = new \Doctrine\Common\Collections\ArrayCollection();
        $repo = $em->getRepository('LECMSBundle:MenuElement');
        $repo->setDefaultLocale($locale);
        foreach ($menuArray as $menuElement)
        {
//            //dump($menuElement);
//            die();
            $element = null;
            if (isset($menuElement->elementId))
            {
                $element = $repo->find($menuElement->elementId);
                $element->setTranslatableLocale($locale);
                $em->refresh($element);
            }
            if (null === $element)
            {
                $element = new MenuElement();
            }
            $element->setName($menuElement->name);
            $element->setEntityId($menuElement->targetId);
            $element->setEntityClass($menuElement->entityClass);
            $element->setPosition($menuElement->position);
            if (isset($menuElement->children) && count($menuElement->children))
            {
                $element->setChildren($this->menuArrayToEntities($menuElement->children,$em,$element,$locale));
            }
            $collection->add($element);
            if (null !== $parent)
            {
                $element->setParent($parent);
            }
            $em->persist($element);

        }

        return $collection;

    }

    private function translateChildren($menu,$locale,$em)
    {
//        if ($locale == 'en') // JE sens que ce truc va rester des plombes comme ça, pas vrai ? 20/2/2015
//        {
//            $locale = 'en_US';
//        }

        foreach ($menu->getChildren() as $child)
        {
            $child->setTranslatableLocale($locale);
            $em->refresh($child);
            //dump($locale);
            //dump($child);
            $child = $this->translateChildren($child,$locale,$em);
        }
        return $menu;
    }

    private function deletePreviousChildren($em,MenuElement $menu)
    {
        foreach ($menu->getChildren() as $children)
        {
            $this->deletePreviousChildren($em, $children);
            $em->remove($children);
        }
    }

    private function menuEntitiesToArray(MenuElement $menu)
    {
        $toReturn = [];
        foreach ($menu->getChildren() as $children)
        {
            $toReturn[$children->getPosition()]['name']=$children->getName();
            $toReturn[$children->getPosition()]['targetId']=$children->getEntityId();
            $toReturn[$children->getPosition()]['elementId']=$children->getId();
            $toReturn[$children->getPosition()]['entityClass']=$children->getEntityClass();
            $toReturn[$children->getPosition()]['position']=$children->getPosition();
            if (count($children->getChildren()))
            {
                $toReturn[$children->getPosition()]['children']=$this->menuEntitiesToArray($children);
            }
        }

        return $toReturn;
    }
}


text:
module MyFields
  class Hidden < Field

    attr_accessor :label, :name, :options, :method, :value

  end
end


text:
package test.java.framework.manager.cucumber.runtime.xstream;

import cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter;
import test.java.framework.manager.cucumber.runtime.CucumberException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

class ClassWithStringAssignableConstructorConverter implements SingleValueConverter {
    private final Constructor ctor;

    ClassWithStringAssignableConstructorConverter(Constructor constructor) {
        this.ctor = constructor;
    }

    @Override
    public String toString(Object obj) {
        return obj.toString();
    }

    @Override
    public Object fromString(String str) {
        try {
            return ctor.newInstance(str);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new CucumberException(e);
        } catch (InvocationTargetException e) {
            throw new CucumberException(e.getTargetException());
        }
    }

    @Override
    public boolean canConvert(Class type) {
        return ctor.getDeclaringClass().equals(type);
    }

}


text:
import tg
from brie.config import plugins_config
from decorator import decorator
from tg.decorators import Decoration

from brie.lib.aurore_helper import *
from brie.model.ldap import Plugins

""" Classe permettant d'utiliser les resultats dictionnaires d'un plugin
    comme une classe (à la manière des LdapResult).
    e.g.
        au lieu de shell_show["uid"] on utilise comme : shell_show.uid
"""
class PluginVars:
    def __init__(self, vars_dict):
        self.__dict__ = vars_dict
    #end def
#end class

def plugin_name_from_function(function, suffix = ".controller", prefix = "brie.plugins."):
    return function.__module__[len(prefix):-len(suffix)]
#end def

""" Decorateur plugin, execute toutes les fonctions du scope donné """
def plugins(scope):
    def plugin(f, *args, **kw):
        results_dict = f(*args, **kw)
        user = args[0].user
        residence_var = "residence"

        plugins_templates = list()

        # un plugin est defini pour le scope et residence est defini
        if scope in plugins_config.mappings and residence_var in results_dict:
            residence_dn = Residences.get_dn_by_name(user, results_dict[residence_var])

            scope_mappings = plugins_config.mappings[scope]

            for function in scope_mappings:
                plugin_name = plugin_name_from_function(function)

                plugin_activated = Plugins.get_by_name(user, residence_dn, plugin_name)

                if plugin_activated is None:
                    continue
                #end if

                template_name = None

                # obtenir le nom du template à partir du decorator "expose"
                deco = Decoration.get_decoration(function)
                try:
                    template_name = deco.engines["text/html"][1]
                except:
                    pass

                if template_name is not None:
                    # transformer le nom de template en chemin fichier
                    template_path = (
                        tg.config['pylons.app_globals']
                          .dotted_filename_finder
                          .get_dotted_filename(template_name, template_extension='.html')
                    )

                    # ajouter dans les plugin templates
                    plugins_templates.append(template_path)
                #end if

                # executer la fonction du plugin
                mapping_results = function(results_dict)

                # constuire le nom de regroupement des variable de ce plugin
                method_name = function.__name__
                plugin_section = str.lower(plugin_name + "_" + method_name)

                # ajout du groupe au dictionnaire de la methode du controlleur
                results_dict[plugin_section] = PluginVars(mapping_results)
            #end for

        #end if

        # ajout des templates dans un champs spécial du dictionnaire pour le rendu
        results_dict["_plugins_templates"] = plugins_templates

        return results_dict
    #end def

    return decorator(plugin)
#end def

""" Decorateur plugin action, passe en paramettre de la fonction d'un plugin """
def plugin_action(scope):
    def plugin(f, *args, **kw):
        user = args[0].user

        plugins_functions = []

        # un plugin est defini pour le scope et residence est defini
        if scope in plugins_config.mappings:
            residence_dn = user.residence_dn

            scope_mappings = plugins_config.mappings[scope]

            for function in scope_mappings:
                plugin_name = plugin_name_from_function(function)
                plugin_activated = Plugins.get_by_name(user, residence_dn, plugin_name)

                if plugin_activated is None:
                    continue
                #end if

                # constuire le nom de regroupement des variable de ce plugin
                method_name = function.__name__
                plugin_section = str.lower(plugin_name + "_" + method_name)

                # ajout du groupe au dictionnaire de la methode du controlleur
                plugins_functions.append((plugin_name, lambda user, resid, models: PluginVars(function(user, resid, models))))
            #end for

        #end if

        # ajout des templates dans un champs spécial du dictionnaire pour le rendu
        def plugin_action(user, resid, models):
            result_dict = dict()
            for plugin_name, plugin_function in plugins_functions:
                result_dict[plugin_name] = plugin_function(user, resid, models)
            #end for
        #end def

        # on remplace la dernière variable par un plugin_action
        new_args = args[:-1] + (plugin_action,)

        return f(*new_args, **kw)
    #end def

    return decorator(plugin)
#end def


text:
#pragma once
#include <aws/events/CloudWatchEvents_EXPORTS.h>
#include <aws/events/CloudWatchEventsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CloudWatchEvents
{
namespace Model
{

  /**
   */
  class AWS_CLOUDWATCHEVENTS_API DeactivateEventSourceRequest : public CloudWatchEventsRequest
  {
  public:
    DeactivateEventSourceRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeactivateEventSource"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the partner event source to deactivate.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the partner event source to deactivate.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the partner event source to deactivate.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the partner event source to deactivate.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the partner event source to deactivate.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The name of the partner event source to deactivate.

     */
    inline DeactivateEventSourceRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the partner event source to deactivate.

     */
    inline DeactivateEventSourceRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the partner event source to deactivate.

     */
    inline DeactivateEventSourceRequest& WithName(const char* value) { SetName(value); return *this;}

  private:

    Aws::String m_name;
    bool m_nameHasBeenSet;
  };

} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws


text:
module CloudstackRubyClient
  module Api
    module Snapshot
      cmd_processor :create_snapshot,
                    :list_snapshots,
                    :delete_snapshot,
                    :create_snapshot_policy,
                    # FIXME: Weird deleteSnapshotPolicies command
                    :delete_snapshot_policies,
                    :list_snapshot_policies
    end
  end
end


text:
package io.github.htools.io.struct;

import io.github.htools.io.Datafile;
import io.github.htools.io.EOCException;
import io.github.htools.io.buffer.BufferReaderWriter;
import io.github.htools.lib.Log;

public abstract class StructuredFileShortJumpTable extends StructuredFile implements StructuredFileIntID {

   public static Log log = new Log(StructuredFileShortJumpTable.class);
   public StructuredFileShortJumptableInternal jumparray;
   boolean loaded = false;
   private int id = 0;

   public StructuredFileShortJumpTable(Datafile df) {
      super(df);
   }

   @Override
   public void closeWrite() {
      super.closeWrite();
      if (jumparray != null) {
         jumparray.closeWrite();
      }
   }

   @Override
   public void setDatafile(Datafile df){
      super.setDatafile(df);
      jumparray = new StructuredFileShortJumptableInternal(new Datafile(this.getDatafile().getSubFile(".jumparray")));
      id = 0;
      loaded = false;
   }

   @Override
   public void openWrite() {
      super.openWrite();
      //log.info("openWrite()");
      id = 0;
      jumparray.openWrite();
   }

   @Override
   public void hookRecordWritten() {
      jumparray.write(id++, this);
   }

   @Override
   public void openRead(){
      super.openRead();
      jumparray.openRead();
   }

   @Override
   public void closeRead() {
      super.closeRead();
      jumparray.closeRead();
      unloadMem();
   }

   @Override
   public void read(int id) {
      find(id);
      //log.info("read offset %d", this.datafile.getOffset());
      nextRecord();
   }

   @Override
   public void find(int id) {
      jumparray.openRead();
      long offset = jumparray.getOffset(id);
      //log.info("find id %d offset %d", id, offset);
      this.setOffset(offset);
      super.openRead();
      int skip = jumparray.getSkip(id);
      for (int s = 0; s < skip; s++) {
         skipRecord();
      }
   }

   public void loadMem() throws EOCException {
      if (!loaded) {
              this.reader = new BufferReaderWriter(getDatafile().readFully());
              loaded = true;
      }
   }

   public boolean isLoadedInMem() {
      return loaded;
   }

   public void unloadMem() {
      if (loaded) {
         this.reader = null;
         loaded = false;
      }
   }

   @Override
   public void readResident(int id) throws EOCException {
      loadMem();
   }

   @Override
   public void readResident() throws EOCException {
      loadMem();
   }

   public boolean isReadResident() {
      return loaded;
   }

   @Override
   public void reuseBuffer() {
   }
}


text:
namespace SolidEdgeSpy.Forms
{
    partial class SelectEventsDialog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SelectEventsDialog));
            this.buttonOK = new System.Windows.Forms.Button();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.listView1 = new System.Windows.Forms.ListView();
            this.imageList = new System.Windows.Forms.ImageList(this.components);
            this.SuspendLayout();
            //
            // buttonOK
            //
            this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonOK.Location = new System.Drawing.Point(297, 229);
            this.buttonOK.Name = "buttonOK";
            this.buttonOK.Size = new System.Drawing.Size(75, 23);
            this.buttonOK.TabIndex = 0;
            this.buttonOK.Text = "&OK";
            this.buttonOK.UseVisualStyleBackColor = true;
            this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
            //
            // buttonCancel
            //
            this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancel.Location = new System.Drawing.Point(378, 229);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 1;
            this.buttonCancel.Text = "&Cancel";
            this.buttonCancel.UseVisualStyleBackColor = true;
            this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
            //
            // listView1
            //
            this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.listView1.Location = new System.Drawing.Point(12, 12);
            this.listView1.Name = "listView1";
            this.listView1.Size = new System.Drawing.Size(441, 205);
            this.listView1.TabIndex = 2;
            this.listView1.UseCompatibleStateImageBehavior = false;
            //
            // imageList
            //
            this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
            this.imageList.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList.Images.SetKeyName(0, "Event_16x16.png");
            //
            // SelectEventsDialog
            //
            this.AcceptButton = this.buttonOK;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.buttonCancel;
            this.ClientSize = new System.Drawing.Size(465, 264);
            this.Controls.Add(this.listView1);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.buttonOK);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "SelectEventsDialog";
            this.Text = "Select Events";
            this.Load += new System.EventHandler(this.SelectEventsDialog_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button buttonOK;
        private System.Windows.Forms.Button buttonCancel;
        private System.Windows.Forms.ListView listView1;
        private System.Windows.Forms.ImageList imageList;
    }
}


text:
layout: page_v2
title: Prebid Mobile | Prebid
description: Prebid Mobile Download
sidebarType: 0

---

## Prebid Mobile Download Page


text:
Lunáapeewi-hulŭniixsuwáakan keyboard
======================

Copyright (C) 2015 First Peoples' Cultural Foundation

Version 9.0

Lunáapeewi-hulŭniixsuwáakan keyboard layout for Unicode

Links
-----

 * Home:     <http://www.fpcf.ca/>
 * Deployed: <http://s.keyman.com/keyboard/fv_lunaapeewi_huluniixsuwaakan>
 * Help:     <http://help.keyman.com/keyboard/fv_lunaapeewi_huluniixsuwaakan>

Supported Platforms
-------------------

 * Windows
 * Web
 * Mobile


text:
package org.apache.servicecomb.foundation.protobuf.internal.schema.scalar;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;

import org.apache.servicecomb.foundation.common.utils.ReflectUtils;
import org.apache.servicecomb.foundation.protobuf.internal.TestSchemaBase;
import org.apache.servicecomb.foundation.protobuf.internal.model.ProtobufRoot;
import org.apache.servicecomb.foundation.test.scaffolding.model.User;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import io.protostuff.compiler.model.Field;
import io.protostuff.compiler.model.Type;

@Ignore
public abstract class TestNumberBaseSchema extends TestSchemaBase {
  protected Object minValue;

  protected Object maxValue;

  @Test
  public void normal() throws Throwable {
    byte[] primitiveBytes = doTestPojoNormal(primitiveFieldName);
    byte[] bytes = doTestPojoNormal(fieldName);

    doTestMapNormal(primitiveFieldName, maxValue, primitiveBytes);
    doTestMapNormal(fieldName, maxValue, bytes);
  }

  private void doTestMapNormal(String field, Object value, byte[] expectBytes) throws IOException {
    // null
    scbMap = new HashMap<>();
    scbMap.put(field, null);
    Assert.assertEquals(0, rootSerializer.serialize(scbMap).length);

    // empty string[]
    scbMap.put(field, new String[] {});
    Assert.assertEquals(0, rootSerializer.serialize(scbMap).length);

    // string[]
    scbMap.put(field, new String[] {String.valueOf(value)});
    Assert.assertArrayEquals(expectBytes, rootSerializer.serialize(scbMap));

    // string
    scbMap.put(field, String.valueOf(value));
    Assert.assertArrayEquals(expectBytes, rootSerializer.serialize(scbMap));
  }

  private byte[] doTestPojoNormal(String name) throws Throwable {
    builder = ProtobufRoot.Root.newBuilder();
    String setName = "set" + name.substring(0, 1).toUpperCase(Locale.US) + name.substring(1);
    Method builderSetter = ReflectUtils.findMethod(builder.getClass(), setName);

    builderSetter.invoke(builder, minValue);
    check();

    builderSetter.invoke(builder, maxValue);
    check();

    return protobufBytes;
  }

  @Test
  public void primitiveStrings_invalid() throws Throwable {
    strings_invalid(primitiveProtoField);
  }

  @Test
  public void strings_invalid() throws Throwable {
    strings_invalid(protoField);
  }

  private void strings_invalid(Field field) throws IOException {
    expectedException.expect(NumberFormatException.class);
    expectedException.expectMessage(Matchers.is("For input string: \"a\""));

    scbMap = new HashMap<>();
    scbMap.put(field.getName(), new String[] {"a"});
    rootSerializer.serialize(scbMap);
  }

  @Test
  public void primitiveString_invalid() throws Throwable {
    string_invalid(primitiveProtoField);
  }

  @Test
  public void string_invalid() throws Throwable {
    string_invalid(protoField);
  }

  private void string_invalid(Field field) throws IOException {
    expectedException.expect(NumberFormatException.class);
    expectedException.expectMessage(Matchers.is("For input string: \"a\""));

    scbMap = new HashMap<>();
    scbMap.put(field.getName(), "a");
    rootSerializer.serialize(scbMap);
  }

  @Test
  public void primitiveType_invalid() throws Throwable {
    type_invalid(primitiveProtoField);
  }

  @Test
  public void type_invalid() throws Throwable {
    type_invalid(protoField);
  }

  private void type_invalid(Field field) throws IOException {
    expectedException.expect(IllegalStateException.class);
    expectedException.expectMessage(Matchers
        .is(String.format("not support serialize from %s to proto %s, field=%s:%s",
            User.class.getName(),
            field.getTypeName(),
            ((Type) field.getParent()).getCanonicalName(),
            field.getName())));

    scbMap = new HashMap<>();
    scbMap.put(field.getName(), new User());
    rootSerializer.serialize(scbMap);
  }
}


text:
package jenkins.management;

import hudson.Extension;
import hudson.diagnosis.ReverseProxySetupMonitor;
import hudson.model.AdministrativeMonitor;
import hudson.model.PageDecorator;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import jenkins.diagnostics.URICheckEncodingMonitor;
import jenkins.model.Jenkins;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;

/**
 * Show notifications and popups for active administrative monitors on all pages.
 */
@Extension
@Restricted(NoExternalUse.class)
public class AdministrativeMonitorsDecorator extends PageDecorator {
    private final Collection<String> ignoredJenkinsRestOfUrls = new ArrayList<>();

    public AdministrativeMonitorsDecorator() {
        // redundant
        ignoredJenkinsRestOfUrls.add("manage");

        // otherwise this would be added to every internal context menu building request
        ignoredJenkinsRestOfUrls.add("contextMenu");

        // don't show here to allow admins to disable malfunctioning monitors via AdministrativeMonitorsDecorator
        ignoredJenkinsRestOfUrls.add("configure");
    }

    @Override
    public String getDisplayName() {
        return Messages.AdministrativeMonitorsDecorator_DisplayName();
    }

    // Used by Jelly
    public Collection<AdministrativeMonitor> filterNonSecurityAdministrativeMonitors(Collection<AdministrativeMonitor> activeMonitors) {
        return this.filterActiveAdministrativeMonitors(activeMonitors, false);
    }

    // Used by Jelly
    public Collection<AdministrativeMonitor> filterSecurityAdministrativeMonitors(Collection<AdministrativeMonitor> activeMonitors) {
        return this.filterActiveAdministrativeMonitors(activeMonitors, true);
    }

    /**
     * Prevent us to compute multiple times the {@link AdministrativeMonitor#isActivated()} by re-using the same list
     */
    private Collection<AdministrativeMonitor> filterActiveAdministrativeMonitors(Collection<AdministrativeMonitor> activeMonitors, boolean isSecurity) {
        Collection<AdministrativeMonitor> active = new ArrayList<>();
        for (AdministrativeMonitor am : activeMonitors) {
            if (am.isSecurity() == isSecurity) {
                active.add(am);
            }
        }
        return active;
    }

    // Used by API
    public List<AdministrativeMonitor> getNonSecurityAdministrativeMonitors() {
        Collection<AdministrativeMonitor> allowedMonitors = getMonitorsToDisplay();

        if (allowedMonitors == null) {
            return Collections.emptyList();
        }

        return allowedMonitors.stream()
                .filter(administrativeMonitor -> !administrativeMonitor.isSecurity())
                .collect(Collectors.toList());
    }

    // Used by API
    public List<AdministrativeMonitor> getSecurityAdministrativeMonitors() {
        Collection<AdministrativeMonitor> allowedMonitors = getMonitorsToDisplay();

        if (allowedMonitors == null) {
            return Collections.emptyList();
        }

        return allowedMonitors.stream()
                .filter(AdministrativeMonitor::isSecurity)
                .collect(Collectors.toList());
    }

    private Collection<AdministrativeMonitor> getAllActiveAdministrativeMonitors() {
        Collection<AdministrativeMonitor> active = new ArrayList<>();
        for (AdministrativeMonitor am : Jenkins.get().getActiveAdministrativeMonitors()) {
            if (am instanceof ReverseProxySetupMonitor) {
                // TODO make reverse proxy monitor work when shown on any URL
                continue;
            }
            if (am instanceof URICheckEncodingMonitor) {
                // TODO make URI encoding monitor work when shown on any URL
                continue;
            }
            active.add(am);
        }
        return active;
    }

    /**
     * Compute the administrative monitors that are active and should be shown.
     * This is done only when the instance is currently running and the user has the permission to read them.
     *
     * @return the list of active monitors if we should display them, otherwise null.
     */
    public Collection<AdministrativeMonitor> getMonitorsToDisplay() {
        if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
            return null;
        }

        StaplerRequest req = Stapler.getCurrentRequest();

        if (req == null) {
            return null;
        }
        List<Ancestor> ancestors = req.getAncestors();

        if (ancestors == null || ancestors.size() == 0) {
            // ???
            return null;
        }

        Ancestor a = ancestors.get(ancestors.size() - 1);
        Object o = a.getObject();

        // don't show while Jenkins is loading
        if (o instanceof HudsonIsLoading || o instanceof HudsonIsRestarting) {
            return null;
        }

        // don't show for some URLs served directly by Jenkins
        if (o instanceof Jenkins) {
            String url = a.getRestOfUrl();

            if (ignoredJenkinsRestOfUrls.contains(url)) {
                return null;
            }
        }

        return getAllActiveAdministrativeMonitors();
    }
}


text:
using UnityEngine;

/// <summary>
///  Assign main camera of the scene to the Canvas' Render Camera property.
///
///  Note: This script should will probably carried over between scenes with
///  DontDestroy() call, therefore - use OnEnable() instead of Start() for the
///  main logic.
/// </summary>
[RequireComponent(typeof(Canvas))]
public class CameraToCanvas : MonoBehaviour {

    protected Canvas _canvas;

    public void OnEnable() {
        if (_canvas == null)
            _canvas = GetComponent<Canvas>();
        if (_canvas.worldCamera != null)
            return;
        _canvas.worldCamera = Camera.main;
    }//OnEnable

}//class


text:
<?php

declare(strict_types=1);

namespace Arrayy\Type;

use function Arrayy\array_first;
use Arrayy\Arrayy;
use Arrayy\ArrayyIterator;
use Arrayy\Collection\Collection;

/**
 * @template TKey of array-key
 * @template T
 * @extends Collection<TKey,T>
 */
final class DetectFirstValueTypeCollection extends Collection implements TypeInterface
{
    /**
     * @var string
     */
    private $getTypeHelper;

    /**
     * @param array|Arrayy|mixed $data
     * @param string             $iteratorClass
     * @param bool               $checkPropertiesInConstructor
     *
     * @phpstan-param array<TKey,T>|Arrayy<TKey,T> $data
     * @phpstan-param class-string<\Arrayy\ArrayyIterator> $iteratorClass
     */
    public function __construct(
        $data = [],
        string $iteratorClass = ArrayyIterator::class,
        bool $checkPropertiesInConstructor = true
    ) {
        /**
         * @psalm-suppress RedundantConditionGivenDocblockType - We also allow other types here,
         * but I don't know how to tell psalm about that. :/
         */
        if ($data instanceof Arrayy) {
            $firstValue = $data->first();
        } elseif (\is_array($data)) {
            $firstValue = array_first($data);
        } else {
            $firstValue = $data;
            $data = [$data];
        }

        $this->getTypeHelper = $this->getTypeFromFirstValue($firstValue);

        parent::__construct(
            $data,
            $iteratorClass,
            $checkPropertiesInConstructor
        );
    }

    /**
     * The type (FQCN) associated with this collection.
     *
     * @return string
     */
    public function getType()
    {
        return $this->getTypeHelper;
    }

    /**
     * @param mixed $value
     *
     * @return string
     */
    private function getTypeFromFirstValue($value): string
    {
        return \is_object($value) ? \get_class($value) : \gettype($value);
    }
}


text:
module Sendhub
  class Rails
    def initialize(options)
      @client = Sendhub::Client.new(
        :host => options[:host],
        :protocol => options[:protocol],
        :api_key => options[:api_key],
        :secret_key => options[:secret_key],
        :notification_url => options[:notification_url]
      )
    end

    def deliver!(message)
      body = message.body
      body = collect_parts(message) if message.multipart?
      headers = collect_sendhub_headers(message)

      res = @client.send_email(
        :from => message.from,
        :to => message.to,
        :reply_to => message.reply_to,
        :subject => message.subject,
        :body => body,
        :content_type => message.content_type,
        :content_transfer_encoding => message.content_transfer_encoding,
        :headers => headers
      )

      puts res.inspect
    end

    def collect_parts(message)
      message.parts.inject("\n\n\n") {|x, part| x << "--#{message.boundary}\n"; x << "#{part.to_s}\n\n"}
    end

    def collect_sendhub_headers(message)
      message.header.fields.find_all{|x| x.name =~ /X-SendHub/}.collect{|x| {x.name => x.value}}
    end
  end
end

ActionMailer::Base.add_delivery_method :sendhub, Sendhub::Rails


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.resources.commerce.customer;

import com.mozu.api.ApiContext;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

/**
 * Use the Customer Authentication Tickets resource to generate and refresh authentication tickets for customer accounts.
 *
 */
public class CustomerAuthTicketResource {
	///
	/// <see cref="Mozu.Api.ApiContext"/>
	///
	private ApiContext _apiContext;

	public CustomerAuthTicketResource(ApiContext apiContext)
	{
		_apiContext = apiContext;
	}

	/**
	 * Creates an authentication ticket for an anonymous shopper user.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	Stream stream = customerauthticket.createAnonymousShopperAuthTicket();
	 *

	 * @return Stream
	 * @see Stream
	 */
	public java.io.InputStream createAnonymousShopperAuthTicket() throws Exception
	{
		MozuClient<java.io.InputStream> client = com.mozu.api.clients.commerce.customer.CustomerAuthTicketClient.createAnonymousShopperAuthTicketClient();
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Creates an authentication ticket for an anonymous shopper user.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CountDownLatch latch = customerauthticket.createAnonymousShopperAuthTicket( callback );
	 *	latch.await()	 *

	 * @param  callback callback handler for asynchronous operations
	 * @return Stream
	 * @see Stream
	 */
	public CountDownLatch createAnonymousShopperAuthTicketAsync( AsyncCallback<java.io.InputStream> callback) throws Exception
	{
		MozuClient<java.io.InputStream> client = com.mozu.api.clients.commerce.customer.CustomerAuthTicketClient.createAnonymousShopperAuthTicketClient();
		client.setContext(_apiContext);
		return client.executeRequest(callback);

	}

	/**
	 * Generates a new authentication ticket for a customer account.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CustomerAuthTicket customerAuthTicket = customerauthticket.createUserAuthTicket( userAuthInfo);
	 *

	 * @param userAuthInfo The authentication information required to generate an authentication ticket for a customer account.
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerUserAuthInfo
	 */
	public com.mozu.api.contracts.customer.CustomerAuthTicket createUserAuthTicket(com.mozu.api.contracts.customer.CustomerUserAuthInfo userAuthInfo) throws Exception
	{
		return createUserAuthTicket( userAuthInfo,  null);
	}

	/**
	 * Generates a new authentication ticket for a customer account.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CountDownLatch latch = customerauthticket.createUserAuthTicket( userAuthInfo, callback );
	 *	latch.await()	 *

	 * @param  callback callback handler for asynchronous operations
	 * @param userAuthInfo The authentication information required to generate an authentication ticket for a customer account.
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerUserAuthInfo
	 */
	public CountDownLatch createUserAuthTicketAsync(com.mozu.api.contracts.customer.CustomerUserAuthInfo userAuthInfo, AsyncCallback<com.mozu.api.contracts.customer.CustomerAuthTicket> callback) throws Exception
	{
		return createUserAuthTicketAsync( userAuthInfo,  null, callback);
	}

	/**
	 * Generates a new authentication ticket for a customer account.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CustomerAuthTicket customerAuthTicket = customerauthticket.createUserAuthTicket( userAuthInfo,  responseFields);
	 *

	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param userAuthInfo The authentication information required to generate an authentication ticket for a customer account.
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerUserAuthInfo
	 */
	public com.mozu.api.contracts.customer.CustomerAuthTicket createUserAuthTicket(com.mozu.api.contracts.customer.CustomerUserAuthInfo userAuthInfo, String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.customer.CustomerAuthTicket> client = com.mozu.api.clients.commerce.customer.CustomerAuthTicketClient.createUserAuthTicketClient( userAuthInfo,  responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Generates a new authentication ticket for a customer account.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CountDownLatch latch = customerauthticket.createUserAuthTicket( userAuthInfo,  responseFields, callback );
	 *	latch.await()	 *

	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param  callback callback handler for asynchronous operations
	 * @param userAuthInfo The authentication information required to generate an authentication ticket for a customer account.
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerUserAuthInfo
	 */
	public CountDownLatch createUserAuthTicketAsync(com.mozu.api.contracts.customer.CustomerUserAuthInfo userAuthInfo, String responseFields, AsyncCallback<com.mozu.api.contracts.customer.CustomerAuthTicket> callback) throws Exception
	{
		MozuClient<com.mozu.api.contracts.customer.CustomerAuthTicket> client = com.mozu.api.clients.commerce.customer.CustomerAuthTicketClient.createUserAuthTicketClient( userAuthInfo,  responseFields);
		client.setContext(_apiContext);
		return client.executeRequest(callback);

	}

	/**
	 * Refreshes an existing authentication ticket for a customer account by providing the refresh token string.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CustomerAuthTicket customerAuthTicket = customerauthticket.refreshUserAuthTicket( refreshToken);
	 *

	 * @param refreshToken Alphanumeric string used for access tokens. This token refreshes access for accounts by generating a new developer or application account authentication ticket after an access token expires.
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 */
	public com.mozu.api.contracts.customer.CustomerAuthTicket refreshUserAuthTicket(String refreshToken) throws Exception
	{
		return refreshUserAuthTicket( refreshToken,  null);
	}

	/**
	 * Refreshes an existing authentication ticket for a customer account by providing the refresh token string.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CountDownLatch latch = customerauthticket.refreshUserAuthTicket( refreshToken, callback );
	 *	latch.await()	 *

	 * @param refreshToken Alphanumeric string used for access tokens. This token refreshes access for accounts by generating a new developer or application account authentication ticket after an access token expires.
	 * @param  callback callback handler for asynchronous operations
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 */
	public CountDownLatch refreshUserAuthTicketAsync(String refreshToken, AsyncCallback<com.mozu.api.contracts.customer.CustomerAuthTicket> callback) throws Exception
	{
		return refreshUserAuthTicketAsync( refreshToken,  null, callback);
	}

	/**
	 * Refreshes an existing authentication ticket for a customer account by providing the refresh token string.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CustomerAuthTicket customerAuthTicket = customerauthticket.refreshUserAuthTicket( refreshToken,  responseFields);
	 *

	 * @param refreshToken Alphanumeric string used for access tokens. This token refreshes access for accounts by generating a new developer or application account authentication ticket after an access token expires.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 */
	public com.mozu.api.contracts.customer.CustomerAuthTicket refreshUserAuthTicket(String refreshToken, String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.customer.CustomerAuthTicket> client = com.mozu.api.clients.commerce.customer.CustomerAuthTicketClient.refreshUserAuthTicketClient( refreshToken,  responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Refreshes an existing authentication ticket for a customer account by providing the refresh token string.
	 *

	 *	CustomerAuthTicket customerauthticket = new CustomerAuthTicket();
	 *	CountDownLatch latch = customerauthticket.refreshUserAuthTicket( refreshToken,  responseFields, callback );
	 *	latch.await()	 *

	 * @param refreshToken Alphanumeric string used for access tokens. This token refreshes access for accounts by generating a new developer or application account authentication ticket after an access token expires.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param  callback callback handler for asynchronous operations
	 * @return com.mozu.api.contracts.customer.CustomerAuthTicket
	 * @see com.mozu.api.contracts.customer.CustomerAuthTicket
	 */
	public CountDownLatch refreshUserAuthTicketAsync(String refreshToken, String responseFields, AsyncCallback<com.mozu.api.contracts.customer.CustomerAuthTicket> callback) throws Exception
	{
		MozuClient<com.mozu.api.contracts.customer.CustomerAuthTicket> client = com.mozu.api.clients.commerce.customer.CustomerAuthTicketClient.refreshUserAuthTicketClient( refreshToken,  responseFields);
		client.setContext(_apiContext);
		return client.executeRequest(callback);

	}

}


text:
import sys
import os

from rpython.translator.goal.translate import main

if __name__ == "__main__":
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    sys.path.append(root_dir)

    sys.argv = [arg for arg in
                sys.argv + [
                    '--opt=jit', '--output', 'rrec',
                    os.path.join(root_dir, 'tools/cli.py')
                ]
                ]
    main()


text:
package com.coolweather.android.gson;

/**
 * Created by nano on 2017/3/28.
 */

public class AQI {
    public AQICity city;
    public class AQICity {
        public String aqi;
        public String pm25;
    }
}


text:
require_relative File.join('support', 'coverage')
require_relative File.join('..', 'lib', 'opushon')

require 'spectus'