text:
package org.seqcode.projects.multigps.framework;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.seqcode.deepseq.StrandedBaseCount;
import org.seqcode.deepseq.events.BindingManager;
import org.seqcode.deepseq.events.BindingModel;
import org.seqcode.deepseq.events.EventsConfig;
import org.seqcode.deepseq.experiments.ControlledExperiment;
import org.seqcode.deepseq.experiments.ExperimentCondition;
import org.seqcode.deepseq.experiments.ExperimentManager;
import org.seqcode.deepseq.experiments.ExptConfig;
import org.seqcode.deepseq.experiments.Sample;
import org.seqcode.deepseq.stats.BackgroundCollection;
import org.seqcode.deepseq.stats.PoissonBackgroundModel;
import org.seqcode.genome.Genome;
import org.seqcode.genome.GenomeConfig;
import org.seqcode.genome.location.Region;
import org.seqcode.gsebricks.verbs.location.ChromosomeGenerator;
import org.seqcode.gseutils.RealValuedHistogram;

/**
 * PotentialRegionFilter: Find a set of regions that are above a threshold in at least one condition.
 * 		A region the size of the model span (i.e. 2x model range) potentially contains a binding site if
 * 		it passes the Poisson threshold in at least one condition.
 * 		The Poisson thresholds are based on the model span size to keep consistent with the final used thresholds.
 * Overall counts for reads in potential regions and outside potential regions are maintained to assist noise model initialization.
 *
 * @author Shaun Mahony
 * @version	%I%, %G%
 */
public class PotentialRegionFilter {

	protected ExperimentManager manager;
	protected BindingManager bindingManager;
	protected EventsConfig evconfig;
	protected MultiGPSConfig config;
	protected ExptConfig econfig;
	protected Genome gen;
	protected float maxBinWidth=0, binStep, winExt;
	protected boolean loadControl=true;
	protected boolean stranded=false;
	protected List<Region> potentialRegions = new ArrayList<Region>();
	protected double potRegionLengthTotal=0;
	protected HashMap<ExperimentCondition, BackgroundCollection> conditionBackgrounds=new HashMap<ExperimentCondition, BackgroundCollection>(); //Background models for each replicate
	protected HashMap<ExperimentCondition, Double> potRegCountsSigChannel = new HashMap<ExperimentCondition, Double>();
	protected HashMap<ExperimentCondition, Double> nonPotRegCountsSigChannel = new HashMap<ExperimentCondition, Double>();
	protected HashMap<ExperimentCondition, Double> potRegCountsCtrlChannel = new HashMap<ExperimentCondition, Double>();
	protected HashMap<ExperimentCondition, Double> nonPotRegCountsCtrlChannel = new HashMap<ExperimentCondition, Double>();
	protected HashMap<ControlledExperiment, Double> potRegCountsSigChannelByRep = new HashMap<ControlledExperiment, Double>();
	protected HashMap<ControlledExperiment, Double> nonPotRegCountsSigChannelByRep = new HashMap<ControlledExperiment, Double>();

	public PotentialRegionFilter(EventsConfig ec, MultiGPSConfig c, ExptConfig econ, ExperimentManager eman, BindingManager bman){
		manager = eman;
		bindingManager = bman;
		evconfig = ec;
		config = c;
		econfig = econ;
		gen = config.getGenome();
		//Initialize background models
		for(ExperimentCondition cond : manager.getConditions()){
			conditionBackgrounds.put(cond, new BackgroundCollection());
			int maxIR = 0; boolean hasControls=true;
			for(ControlledExperiment rep : cond.getReplicates()){
				if(bindingManager.getBindingModel(rep).getInfluenceRange()>maxIR)
					maxIR = bindingManager.getBindingModel(rep).getInfluenceRange();
				hasControls = hasControls && rep.hasControl();
			}

			float binWidth = maxIR;
    		if(binWidth>maxBinWidth){maxBinWidth=binWidth;}

    		//global threshold
    		conditionBackgrounds.get(cond).addBackgroundModel(new PoissonBackgroundModel(-1, config.getPRLogConf(), cond.getTotalSignalCount(), config.getGenome().getGenomeLength(), econfig.getMappableGenomeProp(), binWidth, '.', 1, true));
    		//local windows won't work since we are testing per condition and we don't have a way to scale signal vs controls at the condition level (at least at this stage of execution)

    		double thres = conditionBackgrounds.get(cond).getGenomicModelThreshold();
    		System.err.println("PotentialRegionFilter: genomic threshold for "+cond.getName()+" with bin width "+binWidth+" = "+thres);

    		//Initialize counts
    		potRegCountsSigChannel.put(cond, 0.0);
    		nonPotRegCountsSigChannel.put(cond, 0.0);
    		potRegCountsCtrlChannel.put(cond, 0.0);
    		nonPotRegCountsCtrlChannel.put(cond, 0.0);
    		for(ControlledExperiment rep : cond.getReplicates()){
    			potRegCountsSigChannelByRep.put(rep, 0.0);
        		nonPotRegCountsSigChannelByRep.put(rep, 0.0);
    		}
    	}
		binStep = config.POTREG_BIN_STEP;
		if(binStep>maxBinWidth/2)
			binStep=maxBinWidth/2;
		winExt = maxBinWidth/2;
	}

	//Accessors for read counts
	public Double getPotRegCountsSigChannel(ExperimentCondition e){ return potRegCountsSigChannel.get(e);}
	public Double getNonPotRegCountsSigChannel(ExperimentCondition e){ return nonPotRegCountsSigChannel.get(e);}
	public Double getPotRegCountsCtrlChannel(ExperimentCondition e){ return potRegCountsCtrlChannel.get(e);}
	public Double getNonPotRegCountsCtrlChannel(ExperimentCondition e){ return nonPotRegCountsCtrlChannel.get(e);}
	public Double getPotRegCountsSigChannelByRep(ControlledExperiment e){ return potRegCountsSigChannelByRep.get(e);}
	public Double getNonPotRegCountsSigChannelByRep(ControlledExperiment e){ return nonPotRegCountsSigChannelByRep.get(e);}
	public List<Region> getPotentialRegions(){return potentialRegions;}
	public double getPotRegionLengthTotal(){return potRegionLengthTotal;}

	/**
	 * Find list of potentially enriched regions
	 * (windows that contain the minimum number of reads needed to pass the Poisson backgrounds).
	 * @param testRegions
	 */
	public List<Region> execute(){
		//TODO: check config for defined subset of regions
		Iterator<Region> testRegionsIter = new ChromosomeGenerator().execute(config.getGenome());
		List<Region> testRegions = new ArrayList<Region>();
		while(testRegionsIter.hasNext())
			testRegions.add(testRegionsIter.next());

		//If we put the exclude filter here, we can deal with large regions that overlap exclude regions more smoothly
		//However, this method of filtering is safest when excluding regions from whole chromosomes or other large regions
		testRegions = filterExcludedLeaveRemaining(testRegions);

		//Threading divides analysis over entire chromosomes. This approach is not compatible with file caching.
		int numThreads = econfig.getCacheAllData() ? config.getMaxThreads() : 1;

		Thread[] threads = new Thread[numThreads];
        List<Region> threadRegions[] = new ArrayList[numThreads];
        int i = 0;
        for (i = 0 ; i < threads.length; i++) {
            threadRegions[i] = new ArrayList<Region>();
        }i=0;
        for(Region r : testRegions){
            threadRegions[(i++) % numThreads].add(r);
        }

        for (i = 0 ; i < threads.length; i++) {
            Thread t = new Thread(new PotentialRegionFinderThread(threadRegions[i]));
            t.start();
            threads[i] = t;
        }
        boolean anyrunning = true;
        while (anyrunning) {
            anyrunning = false;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) { }
            for (i = 0; i < threads.length; i++) {
                if (threads[i].isAlive()) {
                    anyrunning = true;
                    break;
                }
            }
        }

        //Initialize signal & noise counts based on potential region calls
        for(ExperimentCondition cond : manager.getConditions()){
    		for(ControlledExperiment rep : cond.getReplicates()){
    			if(rep.getSignalVsNoiseFraction()==0) //Only update if not already initialized
    				rep.setSignalVsNoiseFraction(potRegCountsSigChannelByRep.get(rep)/(potRegCountsSigChannelByRep.get(rep)+nonPotRegCountsSigChannelByRep.get(rep)));
    		}
        }

        for(Region r : potentialRegions)
        	potRegionLengthTotal+=(double)r.getWidth();

     	return potentialRegions;
	}

    /**
     * Filter out pre-defined regions to ignore (e.g. blacklist regions)
     * This version returns segments of regions that don't overlap.
     * Safest to apply to whole chromosomes, I think
     */
    protected List<Region> filterExcludedLeaveRemaining(List<Region> testRegions) {
		if(config.getRegionsToIgnore().size()==0)
			return testRegions;

		List<Region> filtered = new ArrayList<Region>();
		filtered.addAll(testRegions);
		for(Region i : config.getRegionsToIgnore()){
			boolean overlaps = false;
			int x=0;
			while(x < filtered.size() && overlaps==false){
				Region t = filtered.get(x);
				if(t.overlaps(i)){
					overlaps = true;
					Collection<Region> subFrags = t.getSubtractionFragments(i);
					filtered.remove(x);
					if(subFrags.size()>0)
						filtered.addAll(subFrags);
				}
				x++;
			}
		}
		return filtered;
	}

	/**
     * Print potential regions to a file.
     * TESTING ONLY
     */
    public void printPotentialRegionsToFile(){
    	try {
    		String filename = config.getOutputIntermediateDir()+File.separator+config.getOutBase()+".potential.regions";
			FileWriter fout = new FileWriter(filename);
			for(Region r : potentialRegions){
	    		fout.write(r.getLocationString()+"\n");
	    	}
			fout.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    class PotentialRegionFinderThread implements Runnable {
        private Collection<Region> regions;
        private float[][] landscape=null;
        private float[][] starts=null;
        private List<Region> threadPotentials = new ArrayList<Region>();

        public PotentialRegionFinderThread(Collection<Region> r) {
            regions = r;
        }

        public void run() {
        	int expansion = (int)(winExt + maxBinWidth/2);
        	for (Region currentRegion : regions) {
            	Region lastPotential=null;
                //Split the job up into large chunks
                for(int x=currentRegion.getStart(); x<=currentRegion.getEnd(); x+=config.MAXSECTION){
                    int y = (int) (x+config.MAXSECTION+(expansion)); //Leave a little overhang to handle enriched regions that may hit the border. Since lastPotential is defined above, a region on the boundary should get merged in.
                    if(y>currentRegion.getEnd()){y=currentRegion.getEnd();}
                    Region currSubRegion = new Region(gen, currentRegion.getChrom(), x, y);

                    List<Region> currPotRegions = new ArrayList<Region>();
                    List<List<StrandedBaseCount>> ipHits = new ArrayList<List<StrandedBaseCount>>();
                    List<List<StrandedBaseCount>> backHits = new ArrayList<List<StrandedBaseCount>>();
                    List<List<StrandedBaseCount>> ipHitsByRep = new ArrayList<List<StrandedBaseCount>>();

                    synchronized(manager){
	                    //Initialize the read lists
                    	for(ExperimentCondition cond : manager.getConditions()){
                    		ipHits.add(new ArrayList<StrandedBaseCount>());
                			backHits.add(new ArrayList<StrandedBaseCount>());
                    		for(ControlledExperiment rep : cond.getReplicates())
                    			ipHitsByRep.add(new ArrayList<StrandedBaseCount>());
                    	}
                    	//Load signal reads by condition and by replicate, so that signal proportion estimates can be assigned to each replicate
                    	for(ExperimentCondition cond : manager.getConditions()){
                    		for(ControlledExperiment rep : cond.getReplicates()){
                    			ipHits.get(cond.getIndex()).addAll(rep.getSignal().getBases(currSubRegion));
                    			ipHitsByRep.get(rep.getIndex()).addAll(rep.getSignal().getBases(currSubRegion));
                    		}for(Sample ctrl : cond.getControlSamples())
                    			backHits.get(cond.getIndex()).addAll(ctrl.getBases(currSubRegion));
                    		Collections.sort(ipHits.get(cond.getIndex()));
                    		Collections.sort(backHits.get(cond.getIndex()));
                    	}
                    }

            		int numStrandIter = stranded ? 2 : 1;
                    for(int stranditer=1; stranditer<=numStrandIter; stranditer++){
                        //If stranded peak-finding, run over both strands separately
                        char str = !stranded ? '.' : (stranditer==1 ? '+' : '-');

                        makeHitLandscape(ipHits, currSubRegion, maxBinWidth, binStep, str);
                        float ipHitCounts[][] = landscape.clone();
                        float ipBinnedStarts[][] = starts.clone();
                        float backBinnedStarts[][] = null;
                        if (loadControl) {
                            makeHitLandscape(backHits, currSubRegion, maxBinWidth, binStep, str);
                            backBinnedStarts = starts.clone();
                        }

                        //Scan regions
                        int currBin=0;
                        for(int i=currSubRegion.getStart(); i<currSubRegion.getEnd()-(int)maxBinWidth; i+=(int)binStep){
                        	boolean regionPasses=false;
                        	for(ExperimentCondition cond : manager.getConditions()){
                        		double ipWinHits=ipHitCounts[cond.getIndex()][currBin];
                        		//First Test: is the read count above the genome-wide thresholds?
                        		//If there is a fixed alpha, we should use that as the only threshold
                        		if(config.getFixedAlpha()>0){
                        			if(ipWinHits>config.getFixedAlpha()){
                        				regionPasses=true;
                        				break;
                        			}
                        		}else if(conditionBackgrounds.get(cond).passesGenomicThreshold((int)ipWinHits, str)){
                        			//Second Test: refresh all thresholds & test again
                        			conditionBackgrounds.get(cond).updateModels(currSubRegion, i-x, ipBinnedStarts[cond.getIndex()], backBinnedStarts==null ? null : backBinnedStarts[cond.getIndex()], binStep);
                        			if(conditionBackgrounds.get(cond).passesAllThresholds((int)ipWinHits, str)){
                        				//If the region passes the thresholds for one condition, it's a potential
                        				regionPasses=true;
                        				break;
		                            }
		                        }
                        	}
                        	if(regionPasses){
                        		Region currPotential = new Region(gen, currentRegion.getChrom(), Math.max(i-expansion, 1), Math.min((int)(i-1+expansion), currentRegion.getEnd()));
                        		if(lastPotential!=null && currPotential.overlaps(lastPotential)){
                        			lastPotential = lastPotential.expand(0, currPotential.getEnd()-lastPotential.getEnd());
                        		}else{
                        			//Add the last recorded region to the list
                        			if(lastPotential!=null){
                        				if(lastPotential.getWidth()<=config.getBMAnalysisWindowMax()){
                        					currPotRegions.add(lastPotential);
                        					threadPotentials.add(lastPotential);
                        				}else{
                        					//Break up long windows
                        					List<Region> parts = breakWindow(lastPotential, ipHits, config.getBMAnalysisWindowMax(), str);
                        					for(Region p : parts){
                        						currPotRegions.add(p);
                        						threadPotentials.add(p);
                        					}
                        				}
                        			}lastPotential = currPotential;
                        		}
                        	}
                            currBin++;
                        }
					}
                    //Count all "signal" reads overlapping the regions in currPotRegions (including the lastPotential)
                    if(lastPotential!=null)
                    	currPotRegions.add(lastPotential);
                    currPotRegions = filterExcluded(currPotRegions);
                    countReadsInRegions(currPotRegions, ipHits, backHits, y==currentRegion.getEnd() ? y : y-expansion);
                    countReadsInRegionsByRep(currPotRegions, ipHitsByRep, y==currentRegion.getEnd() ? y : y-expansion);
                    //Note: it looks like currPotRegions and threadPotentials are redundant in the above, but they are not.
                    //currPotRegions is only used to count sig/noise reads in the current section. threadPotentials stores regions over the entire run.
                }
                //Add the final recorded region to the list
                if(lastPotential!=null)
    				threadPotentials.add(lastPotential);
                threadPotentials = filterExcluded(threadPotentials);
            }
        	if(threadPotentials.size()>0){
        		synchronized(potentialRegions){
        			potentialRegions.addAll(threadPotentials);
        		}
        	}
        }

        //Break up a long window into parts
        //For now, we just choose the break points as the bins with the lowest total signal read count around the desired length.
        //TODO: improve?
        protected List<Region> breakWindow(Region lastPotential, List<List<StrandedBaseCount>> ipHits, int preferredWinLen, char str) {
			List<Region> parts = new ArrayList<Region>();
			makeHitLandscape(ipHits, lastPotential, maxBinWidth, binStep, str);
            float ipHitCounts[][] = landscape.clone();

            int currPartStart = lastPotential.getStart();
            double currPartTotalMin=Double.MAX_VALUE; int currPartTotalMinPos = -1;
            int currBin=0;
            for(int i=lastPotential.getStart(); i<lastPotential.getEnd()-(int)maxBinWidth; i+=(int)binStep){
            	if(lastPotential.getEnd()-currPartStart < (preferredWinLen*1.5))
            		break;
            	float currBinTotal=0;
            	for(ExperimentCondition cond : manager.getConditions())
                	currBinTotal+=ipHitCounts[cond.getIndex()][currBin];

            	if(i>(currPartStart+preferredWinLen-1000) && i<(currPartStart+preferredWinLen+1000)){
            		if(currBinTotal<currPartTotalMin){
            			currPartTotalMin=currBinTotal;
            			currPartTotalMinPos=i;
            		}
            	}
            	//Add a new part
            	if(i>=(currPartStart+preferredWinLen+1000)){
            		parts.add(new Region(lastPotential.getGenome(), lastPotential.getChrom(), currPartStart, currPartTotalMinPos));
            		currPartStart = currPartTotalMinPos+1;
            		currPartTotalMin=Double.MAX_VALUE; currPartTotalMinPos = -1;
            	}
            	currBin++;
            }
            parts.add(new Region(lastPotential.getGenome(), lastPotential.getChrom(), currPartStart, lastPotential.getEnd()));

			return parts;
		}

		//Filter out pre-defined regions to ignore (e.g. tower regions)
        protected List<Region> filterExcluded(List<Region> testRegions) {
			List<Region> filtered = new ArrayList<Region>();
			if(config.getRegionsToIgnore().size()==0)
				return testRegions;

			for(Region t : testRegions){
				boolean ignore = false;
				for(Region i : config.getRegionsToIgnore()){
					if(t.overlaps(i)){
						ignore = true; break;
					}
				}
				if(!ignore)
					filtered.add(t);
			}
			return filtered;
		}

		//Makes integer arrays corresponding to the read landscape over the current region.
        //Reads are semi-extended out to bin width to account for the bin step
        //No needlefiltering here as that is taken care of during read loading (i.e. in Sample)
    	protected void makeHitLandscape(List<List<StrandedBaseCount>> hits, Region currReg, float binWidth, float binStep, char strand){
    		int numBins = (int)(currReg.getWidth()/binStep);
    		landscape = new float[hits.size()][numBins+1];
    		starts = new float[hits.size()][numBins+1];
    		float halfWidth = binWidth/2;

    		for(ExperimentCondition cond : manager.getConditions()){
        		List<StrandedBaseCount> currHits = hits.get(cond.getIndex());
    			for(int i=0; i<=numBins; i++){landscape[cond.getIndex()][i]=0; starts[cond.getIndex()][i]=0; }
	    		for(StrandedBaseCount r : currHits){
	    			if(strand=='.' || r.getStrand()==strand){
	    				int offset=inBounds(r.getCoordinate()-currReg.getStart(),0,currReg.getWidth());
	    				int binoff = inBounds((int)(offset/binStep), 0, numBins);
	    				starts[cond.getIndex()][binoff]+=r.getCount();
	    				int binstart = inBounds((int)((double)(offset-halfWidth)/binStep), 0, numBins);
	    				int binend = inBounds((int)((double)(offset)/binStep), 0, numBins);
	    				for(int b=binstart; b<=binend; b++)
	    					landscape[cond.getIndex()][b]+=r.getCount();
	    			}
            	}
    		}
    	}
    	protected final int inBounds(int x, int min, int max){
    		if(x<min){return min;}
    		if(x>max){return max;}
    		return x;
    	}

    	/**
    	 * Count the total reads within potential regions via semi binary search (by condition).
    	 * Assumes both regs and ipHits are sorted.
    	 * We don't have to check chr String matches, as the hits were extracted from the chromosome
    	 * EndCoord accounts for the extra overhang added to some wide regions
    	 * We also ignore strandedness here -- the object is to count ALL reads that will be loaded for analysis later
    	 * (and that thus will not be accounted for by the global noise model)
    	 * @param regs
    	 * @param ipHits
    	 * @param ctrlHits
    	 * @param endCoord
    	 */
    	protected void countReadsInRegions(List<Region> regs, List<List<StrandedBaseCount>> ipHits, List<List<StrandedBaseCount>> ctrlHits, int endCoord){
    		//Iterate through experiments
    		for(ExperimentCondition cond : manager.getConditions()){
    			double currPotWeightSig=0, currNonPotWeightSig=0, currPotWeightCtrl=0, currNonPotWeightCtrl=0;
    			//Iterate through signal hits
    			for(StrandedBaseCount hit : ipHits.get(cond.getIndex())){
    				if(regs.size()==0)
    					currNonPotWeightSig+=hit.getCount();
    				else{
    					//Binary search for closest region start
        				int hpoint = hit.getCoordinate();
        				if(hpoint<endCoord){ //Throw this check in for the overhang
	        				int l = 0, r = regs.size()-1;
	        	            while (r - l > 1) {
	        	                int c = (l + r) / 2;
	        	                if (hpoint >= regs.get(c).getStart()) {
	        	                    l = c;
	        	                } else {
	        	                    r = c;
	        	                }
	        	            }
	        	            boolean inPot = false;
	        	            for(int x=l; x<=r; x++){
	        	            	if(hpoint >= regs.get(x).getStart() && hpoint <= regs.get(x).getEnd()){
	        	            		currPotWeightSig+=hit.getCount(); inPot=true; break;
	        	            	}
	        	            }
	        	            if(!inPot)
	        	            	currNonPotWeightSig+=hit.getCount();
        				}
    				}
    			}
    			//Iterate through control hits
    			for(StrandedBaseCount hit : ctrlHits.get(cond.getIndex())){
    				if(regs.size()==0)
    					currNonPotWeightCtrl+=hit.getCount();
    				else{
        				//Binary search for closest region start
        				int hpoint = hit.getCoordinate();
        				if(hpoint<endCoord){ //Throw this check in for the overhang
	        				int l = 0, r = regs.size()-1;
	        	            while (r - l > 1) {
	        	                int c = (l + r) / 2;
	        	                if (hpoint >= regs.get(c).getStart()) {
	        	                    l = c;
	        	                } else {
	        	                    r = c;
	        	                }
	        	            }
	        	            boolean inPot = false;
	        	            for(int x=l; x<=r; x++){
	        	            	if(hpoint >= regs.get(x).getStart() && hpoint <= regs.get(x).getEnd()){
	        	            		currPotWeightCtrl+=hit.getCount(); inPot=true; break;
	        	            	}
	        	            }
	        	            if(!inPot)
	        	            	currNonPotWeightCtrl+=hit.getCount();
        				}
    				}
    			}
    			synchronized(potRegCountsSigChannel){
    				potRegCountsSigChannel.put(cond, potRegCountsSigChannel.get(cond)+currPotWeightSig);
    			}
    			synchronized(nonPotRegCountsSigChannel){
    				nonPotRegCountsSigChannel.put(cond, nonPotRegCountsSigChannel.get(cond)+currNonPotWeightSig);
    			}
    			synchronized(potRegCountsCtrlChannel){
    				potRegCountsCtrlChannel.put(cond, potRegCountsCtrlChannel.get(cond)+currPotWeightCtrl);
    			}
    			synchronized(nonPotRegCountsCtrlChannel){
    				nonPotRegCountsCtrlChannel.put(cond, nonPotRegCountsCtrlChannel.get(cond)+currNonPotWeightCtrl);
    			}
    		}
	    }
    }

    /**
	 * Count the total reads within potential regions via semi binary search (by replicate).
	 * Assumes both regs and ipHitsByRep are sorted.
	 * We don't have to check chr String matches, as the hits were extracted from the chromosome
	 * EndCoord accounts for the extra overhang added to some wide regions
	 * We also ignore strandedness here -- the object is to count ALL reads that will be loaded for analysis later
	 * (and that thus will not be accounted for by the global noise model)
	 * @param regs
	 * @param ipHitsByRep
	 * @param ctrlHits
	 * @param endCoord
	 */
	protected void countReadsInRegionsByRep(List<Region> regs, List<List<StrandedBaseCount>> ipHitsByRep, int endCoord){
		//Iterate through experiments
		for(ExperimentCondition cond : manager.getConditions()){
			for(ControlledExperiment rep : cond.getReplicates()){
				double currPotWeightSig=0, currNonPotWeightSig=0;
				//Iterate through signal hits
				for(StrandedBaseCount hit : ipHitsByRep.get(rep.getIndex())){
					if(regs.size()==0)
						currNonPotWeightSig+=hit.getCount();
					else{
						//Binary search for closest region start
	    				int hpoint = hit.getCoordinate();
	    				if(hpoint<endCoord){ //Throw this check in for the overhang
	        				int l = 0, r = regs.size()-1;
	        	            while (r - l > 1) {
	        	                int c = (l + r) / 2;
	        	                if (hpoint >= regs.get(c).getStart()) {
	        	                    l = c;
	        	                } else {
	        	                    r = c;
	        	                }
	        	            }
	        	            boolean inPot = false;
	        	            for(int x=l; x<=r; x++){
	        	            	if(hpoint >= regs.get(x).getStart() && hpoint <= regs.get(x).getEnd()){
	        	            		currPotWeightSig+=hit.getCount(); inPot=true; break;
	        	            	}
	        	            }
	        	            if(!inPot)
	        	            	currNonPotWeightSig+=hit.getCount();
	    				}
					}
				}

				synchronized(potRegCountsSigChannelByRep){
					potRegCountsSigChannelByRep.put(rep, potRegCountsSigChannelByRep.get(rep)+currPotWeightSig);
				}
				synchronized(nonPotRegCountsSigChannelByRep){
					nonPotRegCountsSigChannelByRep.put(rep, nonPotRegCountsSigChannelByRep.get(rep)+currNonPotWeightSig);
				}
			}
		}
    }

    /**
	 * This main method is only for testing the PotentialRegionFilter
	 * @param args
	 */
	public static void main(String[] args){
		GenomeConfig gconfig = new GenomeConfig(args);
		ExptConfig econfig = new ExptConfig(gconfig.getGenome(), args);
		EventsConfig evconfig = new EventsConfig(gconfig, args);
		MultiGPSConfig config = new MultiGPSConfig(gconfig, args);
		if(config.helpWanted()){
			System.err.println("PotentialRegionFilter:");
			System.err.println(config.getArgsList());
		}else{
			ExperimentManager manager = new ExperimentManager(econfig);
			BindingManager bman = new BindingManager(evconfig, manager);
			//Initialize binding models & binding model record
			Map<ControlledExperiment, List<BindingModel>> repBindingModels = new HashMap<ControlledExperiment, List<BindingModel>>();
			for(ControlledExperiment rep : manager.getReplicates()){
				if(evconfig.getDefaultBindingModel()!=null)
					bman.setBindingModel(rep, evconfig.getDefaultBindingModel());
				else if(rep.getExptType()!=null && rep.getExptType().getName().toLowerCase().equals("chipexo"))
					bman.setBindingModel(rep, new BindingModel(BindingModel.defaultChipExoEmpiricalDistribution));
				else
					bman.setBindingModel(rep, new BindingModel(BindingModel.defaultChipSeqEmpiricalDistribution));
				repBindingModels.put(rep, new ArrayList<BindingModel>());
				repBindingModels.get(rep).add(bman.getBindingModel(rep));
			}
			for(ExperimentCondition cond : manager.getConditions())
				bman.updateMaxInfluenceRange(cond);

			RealValuedHistogram histo = new RealValuedHistogram(0, 10000, 20);

			System.err.println("Conditions:\t"+manager.getConditions().size());
			for(ExperimentCondition c : manager.getConditions()){
				System.err.println("Condition "+c.getName()+":\t#Replicates:\t"+c.getReplicates().size());
			}
			for(ExperimentCondition c : manager.getConditions()){
				for(ControlledExperiment r : c.getReplicates()){
					System.err.println("Condition "+c.getName()+":\tRep "+r.getName());
					if(r.getControl()==null)
						System.err.println("\tSignal:\t"+r.getSignal().getHitCount());
					else
						System.err.println("\tSignal:\t"+r.getSignal().getHitCount()+"\tControl:\t"+r.getControl().getHitCount());
				}
			}

			PotentialRegionFilter filter = new PotentialRegionFilter(evconfig, config, econfig, manager, bman);
			List<Region> potentials = filter.execute();

			int min = Integer.MAX_VALUE;
			int max = -Integer.MAX_VALUE;
			for(Region r : potentials){
				System.out.println(r.getLocationString()+"\t"+r.getWidth());
				histo.addValue(r.getWidth());
				if(r.getWidth()<min)
					min = r.getWidth();
				if(r.getWidth()>max)
					max = r.getWidth();
			}
			System.err.println("Potential Regions: "+potentials.size());
			System.err.println("Min width: "+min+"\tMax width: "+max);
			histo.printContents(true);

			System.err.println("Proportions of tags in potential regions");
			for(ExperimentCondition c : manager.getConditions())
				for(ControlledExperiment r : c.getReplicates())
					System.err.println("Condition "+c.getName()+":\tRep "+r.getName()+"\t"+r.getSignalVsNoiseFraction());

			manager.close();
		}
	}
}


text:
package org.apache.ignite.internal.client.impl;

import org.apache.ignite.internal.client.GridClientDataMetrics;

/**
 * Adapter for cache metrics.
 */
public class GridClientDataMetricsAdapter implements GridClientDataMetrics {
    /** */
    private static final long serialVersionUID = 0L;

    /** Create time. */
    private long createTime = System.currentTimeMillis();

    /** Last read time. */
    private volatile long readTime = System.currentTimeMillis();

    /** Last update time. */
    private volatile long writeTime = System.currentTimeMillis();

    /** Number of reads. */
    private volatile int reads;

    /** Number of writes. */
    private volatile int writes;

    /** Number of hits. */
    private volatile int hits;

    /** Number of misses. */
    private volatile int misses;

    /** {@inheritDoc} */
    @Override public long createTime() {
        return createTime;
    }

    /** {@inheritDoc} */
    @Override public long writeTime() {
        return writeTime;
    }

    /** {@inheritDoc} */
    @Override public long readTime() {
        return readTime;
    }

    /** {@inheritDoc} */
    @Override public int reads() {
        return reads;
    }

    /** {@inheritDoc} */
    @Override public int writes() {
        return writes;
    }

    /** {@inheritDoc} */
    @Override public int hits() {
        return hits;
    }

    /** {@inheritDoc} */
    @Override public int misses() {
        return misses;
    }

    /**
     * Sets creation time.
     *
     * @param createTime Creation time.
     */
    public void createTime(long createTime) {
        this.createTime = createTime;
    }

    /**
     * Sets read time.
     *
     * @param readTime Read time.
     */
    public void readTime(long readTime) {
        this.readTime = readTime;
    }

    /**
     * Sets write time.
     *
     * @param writeTime Write time.
     */
    public void writeTime(long writeTime) {
        this.writeTime = writeTime;
    }

    /**
     * Sets number of reads.
     *
     * @param reads Number of reads.
     */
    public void reads(int reads) {
        this.reads = reads;
    }

    /**
     * Sets number of writes.
     *
     * @param writes Number of writes.
     */
    public void writes(int writes) {
        this.writes = writes;
    }

    /**
     * Sets number of hits.
     *
     * @param hits Number of hits.
     */
    public void hits(int hits) {
        this.hits = hits;
    }

    /**
     * Sets number of misses.
     *
     * @param misses Number of misses.
     */
    public void misses(int misses) {
        this.misses = misses;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return "GridClientDataMetricsAdapter [" +
            "createTime=" + createTime +
            ", hits=" + hits +
            ", misses=" + misses +
            ", reads=" + reads +
            ", readTime=" + readTime +
            ", writes=" + writes +
            ", writeTime=" + writeTime +
            ']';
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Hyena.Data;
using Tripod.Sources;
using Tripod.Sources.SqliteCache;

namespace Tripod.Model
{
    public static class PhotoModelFactory
    {
        public static IListModel<IPhoto> GetModel (IEnumerable<IPhoto> enumerator)
        {
            if (enumerator is TripodQuery<SqliteCachedPhoto>) {
                return new HyenaLINQModel<SqliteCachedPhoto, IPhoto> (enumerator as TripodQuery<SqliteCachedPhoto>);
            } else {
                return new EnumerableListModel<IPhoto> (enumerator);
            }
        }
    }
}


text:
/* BEGIN PN:DTS2013051703879 ,Added by l00184147, 2013/5/17*/
//add Touch driver for G610-T11
/* BEGIN PN:SPBB-1218 ,Added by l00184147, 2012/12/20*/
/*
 * cyttsp4_mt_common.h
 * Cypress TrueTouch(TM) Standard Product V4 Multi-touch module.
 * For use with Cypress Txx4xx parts.
 * Supported parts include:
 * TMA4XX
 * TMA1036
 *
 * Copyright (C) 2012 Cypress Semiconductor
 * Copyright (C) 2011 Sony Ericsson Mobile Communications AB.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2, and only version 2, as published by the
 * Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Contact Cypress Semiconductor at www.cypress.com <ttdrivers@cypress.com>
 *
 */

#include "cyttsp4_bus.h"

#include <linux/delay.h>
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/limits.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/workqueue.h>

#include "cyttsp4_core.h"
#include "cyttsp4_mt.h"
#include "cyttsp4_regs.h"

struct cyttsp4_mt_data;
struct cyttsp4_mt_function {
	int (*mt_release)(struct cyttsp4_device *ttsp);
	int (*mt_probe)(struct cyttsp4_device *ttsp,
			struct cyttsp4_mt_data *md);
	void (*report_slot_liftoff)(struct cyttsp4_mt_data *md);
	void (*input_sync)(struct input_dev *input);
	void (*input_report)(struct input_dev *input, int sig, int t);
	void (*final_sync)(struct input_dev *input, int max_tchs,
			int mt_sync_count, int *ids);
	int (*input_register_device)(struct input_dev *input, int max_tchs);
};

struct cyttsp4_mt_data {
	struct cyttsp4_device *ttsp;
	struct cyttsp4_mt_platform_data *pdata;
	struct cyttsp4_sysinfo *si;
	struct input_dev *input;
	struct cyttsp4_mt_function mt_function;
#ifdef CONFIG_HAS_EARLYSUSPEND
	struct early_suspend es;
	bool is_suspended;
#endif
	/* BEGIN PN:DTS2013041400018 ,Added by l00184147, 2013/4/12*/
	struct mutex report_lock;
	/* END PN:DTS2013041400018 ,Added by l00184147, 2013/4/12*/
	bool input_device_registered;
	char phys[NAME_MAX];
	int num_prv_tch;
	int prv_tch_type;
#ifdef VERBOSE_DEBUG
	u8 pr_buf[CY_MAX_PRBUF_SIZE];
#endif
};

extern void cyttsp4_init_function_ptrs(struct cyttsp4_mt_data *md);
extern struct cyttsp4_driver cyttsp4_mt_driver;
/* END PN:SPBB-1218 ,Added by l00184147, 2012/12/20*/
/* END PN:DTS2013051703879 ,Added by l00184147, 2013/5/17*/


text:
package core

import (
	"fmt"
	"testing"

	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/planner/property"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/stretchr/testify/require"
)

type mockDataSource struct {
	baseLogicalPlan
}

func (ds mockDataSource) Init(ctx sessionctx.Context) *mockDataSource {
	ds.baseLogicalPlan = newBaseLogicalPlan(ctx, "mockDS", &ds, 0)
	return &ds
}

func (ds *mockDataSource) findBestTask(prop *property.PhysicalProperty, planCounter *PlanCounterTp, opt *physicalOptimizeOp) (task, int64, error) {
	// It can satisfy any of the property!
	// Just use a TableDual for convenience.
	p := PhysicalTableDual{}.Init(ds.ctx, &property.StatsInfo{RowCount: 1}, 0)
	task := &rootTask{
		p: p,
	}
	planCounter.Dec(1)
	return task, 1, nil
}

// mockLogicalPlan4Test is a LogicalPlan which is used for unit test.
// The basic assumption:
//  1. mockLogicalPlan4Test can generate tow kinds of physical plan: physicalPlan1 and
//     physicalPlan2. physicalPlan1 can pass the property only when they are the same
//     order; while physicalPlan2 cannot match any of the property(in other words, we can
//     generate it only when then property is empty).
//  2. We have a hint for physicalPlan2.
//  3. If the property is empty, we still need to check `canGeneratePlan2` to decide
//     whether it can generate physicalPlan2.
type mockLogicalPlan4Test struct {
	baseLogicalPlan
	// hasHintForPlan2 indicates whether this mockPlan contains hint.
	// This hint is used to generate physicalPlan2. See the implementation
	// of exhaustPhysicalPlans().
	hasHintForPlan2 bool
	// canGeneratePlan2 indicates whether this plan can generate physicalPlan2.
	canGeneratePlan2 bool
	// costOverflow indicates whether this plan will generate physical plan whose cost is overflowed.
	costOverflow bool
}

func (p mockLogicalPlan4Test) Init(ctx sessionctx.Context) *mockLogicalPlan4Test {
	p.baseLogicalPlan = newBaseLogicalPlan(ctx, "mockPlan", &p, 0)
	return &p
}

func (p *mockLogicalPlan4Test) getPhysicalPlan1(prop *property.PhysicalProperty) PhysicalPlan {
	physicalPlan1 := mockPhysicalPlan4Test{planType: 1}.Init(p.ctx)
	physicalPlan1.stats = &property.StatsInfo{RowCount: 1}
	physicalPlan1.childrenReqProps = make([]*property.PhysicalProperty, 1)
	physicalPlan1.childrenReqProps[0] = prop.CloneEssentialFields()
	return physicalPlan1
}

func (p *mockLogicalPlan4Test) getPhysicalPlan2(prop *property.PhysicalProperty) PhysicalPlan {
	physicalPlan2 := mockPhysicalPlan4Test{planType: 2}.Init(p.ctx)
	physicalPlan2.stats = &property.StatsInfo{RowCount: 1}
	physicalPlan2.childrenReqProps = make([]*property.PhysicalProperty, 1)
	physicalPlan2.childrenReqProps[0] = property.NewPhysicalProperty(prop.TaskTp, nil, false, prop.ExpectedCnt, false)
	return physicalPlan2
}

func (p *mockLogicalPlan4Test) exhaustPhysicalPlans(prop *property.PhysicalProperty) ([]PhysicalPlan, bool, error) {
	plan1 := make([]PhysicalPlan, 0, 1)
	plan2 := make([]PhysicalPlan, 0, 1)
	if prop.IsSortItemEmpty() && p.canGeneratePlan2 {
		// Generate PhysicalPlan2 when the property is empty.
		plan2 = append(plan2, p.getPhysicalPlan2(prop))
		if p.hasHintForPlan2 {
			return plan2, true, nil
		}
	}
	if all, _ := prop.AllSameOrder(); all {
		// Generate PhysicalPlan1 when properties are the same order.
		plan1 = append(plan1, p.getPhysicalPlan1(prop))
	}
	if p.hasHintForPlan2 {
		// The hint cannot work.
		if prop.IsSortItemEmpty() {
			p.ctx.GetSessionVars().StmtCtx.AppendWarning(fmt.Errorf("the hint is inapplicable for plan2"))
		}
		return plan1, false, nil
	}
	return append(plan1, plan2...), true, nil
}

type mockPhysicalPlan4Test struct {
	basePhysicalPlan
	// 1 or 2 for physicalPlan1 or physicalPlan2.
	// See the comment of mockLogicalPlan4Test.
	planType int
}

func (p mockPhysicalPlan4Test) Init(ctx sessionctx.Context) *mockPhysicalPlan4Test {
	p.basePhysicalPlan = newBasePhysicalPlan(ctx, "mockPlan", &p, 0)
	return &p
}

func (p *mockPhysicalPlan4Test) attach2Task(tasks ...task) task {
	t := tasks[0].copy()
	attachPlan2Task(p, t)
	return t
}

// MemoryUsage of mockPhysicalPlan4Test is only for testing
func (p *mockPhysicalPlan4Test) MemoryUsage() (sum int64) {
	return
}

func TestCostOverflow(t *testing.T) {
	ctx := MockContext()
	// Plan Tree: mockPlan -> mockDataSource
	mockPlan := mockLogicalPlan4Test{costOverflow: true}.Init(ctx)
	mockDS := mockDataSource{}.Init(ctx)
	mockPlan.SetChildren(mockDS)
	// An empty property is enough for this test.
	prop := property.NewPhysicalProperty(property.RootTaskType, nil, false, 0, false)
	task, _, err := mockPlan.findBestTask(prop, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	// The cost should be overflowed, but the task shouldn't be invalid.
	require.False(t, task.invalid())
}

func TestEnforcedProperty(t *testing.T) {
	ctx := MockContext()
	// PlanTree : mockLogicalPlan -> mockDataSource
	mockPlan := mockLogicalPlan4Test{}.Init(ctx)
	mockDS := mockDataSource{}.Init(ctx)
	mockPlan.SetChildren(mockDS)

	col0 := &expression.Column{UniqueID: 1}
	col1 := &expression.Column{UniqueID: 2}
	// Use different order, so that mockLogicalPlan cannot generate any of the
	// physical plans.
	item0 := property.SortItem{Col: col0, Desc: false}
	item1 := property.SortItem{Col: col1, Desc: true}
	items := []property.SortItem{item0, item1}

	prop0 := &property.PhysicalProperty{
		SortItems:      items,
		CanAddEnforcer: false,
	}
	// should return invalid task because no physical plan can match this property.
	task, _, err := mockPlan.findBestTask(prop0, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	require.True(t, task.invalid())

	prop1 := &property.PhysicalProperty{
		SortItems:      items,
		CanAddEnforcer: true,
	}
	// should return the valid task when the property is enforced.
	task, _, err = mockPlan.findBestTask(prop1, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	require.False(t, task.invalid())
}

func TestHintCannotFitProperty(t *testing.T) {
	ctx := MockContext()
	// PlanTree : mockLogicalPlan -> mockDataSource
	mockPlan0 := mockLogicalPlan4Test{
		hasHintForPlan2:  true,
		canGeneratePlan2: true,
	}.Init(ctx)
	mockDS := mockDataSource{}.Init(ctx)
	mockPlan0.SetChildren(mockDS)

	col0 := &expression.Column{UniqueID: 1}
	item0 := property.SortItem{Col: col0}
	items := []property.SortItem{item0}
	// case 1, The property is not empty and enforced, should enforce a sort.
	prop0 := &property.PhysicalProperty{
		SortItems:      items,
		CanAddEnforcer: true,
	}
	task, _, err := mockPlan0.findBestTask(prop0, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	require.False(t, task.invalid())
	_, enforcedSort := task.plan().(*PhysicalSort)
	require.True(t, enforcedSort)
	plan2 := task.plan().Children()[0]
	mockPhysicalPlan, ok := plan2.(*mockPhysicalPlan4Test)
	require.True(t, ok)
	require.Equal(t, 2, mockPhysicalPlan.planType)

	// case 2, The property is not empty but not enforced, still need to enforce a sort
	// to ensure the hint can work
	prop1 := &property.PhysicalProperty{
		SortItems:      items,
		CanAddEnforcer: false,
	}
	task, _, err = mockPlan0.findBestTask(prop1, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	require.False(t, task.invalid())
	_, enforcedSort = task.plan().(*PhysicalSort)
	require.True(t, enforcedSort)
	plan2 = task.plan().Children()[0]
	mockPhysicalPlan, ok = plan2.(*mockPhysicalPlan4Test)
	require.True(t, ok)
	require.Equal(t, 2, mockPhysicalPlan.planType)

	// case 3, The hint cannot work even if the property is empty, should return a warning
	// and generate physicalPlan1.
	prop2 := &property.PhysicalProperty{
		SortItems:      items,
		CanAddEnforcer: false,
	}
	mockPlan1 := mockLogicalPlan4Test{
		hasHintForPlan2:  true,
		canGeneratePlan2: false,
	}.Init(ctx)
	mockPlan1.SetChildren(mockDS)
	task, _, err = mockPlan1.findBestTask(prop2, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	require.False(t, task.invalid())
	require.Equal(t, uint16(1), ctx.GetSessionVars().StmtCtx.WarningCount())
	// Because physicalPlan1 can match the property, so we should get it.
	mockPhysicalPlan, ok = task.plan().(*mockPhysicalPlan4Test)
	require.True(t, ok)
	require.Equal(t, 1, mockPhysicalPlan.planType)

	// case 4, Similar to case 3, but the property is enforced now. Ths result should be
	// the same with case 3.
	ctx.GetSessionVars().StmtCtx.SetWarnings(nil)
	prop3 := &property.PhysicalProperty{
		SortItems:      items,
		CanAddEnforcer: true,
	}
	task, _, err = mockPlan1.findBestTask(prop3, &PlanCounterDisabled, defaultPhysicalOptimizeOption())
	require.NoError(t, err)
	require.False(t, task.invalid())
	require.Equal(t, uint16(1), ctx.GetSessionVars().StmtCtx.WarningCount())
	// Because physicalPlan1 can match the property, so we don't need to enforce a sort.
	mockPhysicalPlan, ok = task.plan().(*mockPhysicalPlan4Test)
	require.True(t, ok)
	require.Equal(t, 1, mockPhysicalPlan.planType)
}


text:
using base::WaitableEvent;

namespace browser_sync {

void DatabaseModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
  if (BrowserThread::CurrentlyOn(BrowserThread::DB)) {
    DLOG(WARNING) << "DoWorkAndWaitUntilDone called from the DB thread.";
    work->Run();
    return;
  }
  WaitableEvent done(false, false);
  if (!BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
      NewRunnableMethod(this, &DatabaseModelWorker::CallDoWorkAndSignalTask,
                        work, &done))) {
    NOTREACHED() << "Failed to post task to the db thread.";
    return;
  }
  done.Wait();
}

void DatabaseModelWorker::CallDoWorkAndSignalTask(Callback0::Type* work,
                                                  WaitableEvent* done) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  work->Run();
  done->Signal();
}

ModelSafeGroup DatabaseModelWorker::GetModelSafeGroup() {
  return GROUP_DB;
}

bool DatabaseModelWorker::CurrentThreadIsWorkThread() {
  return BrowserThread::CurrentlyOn(BrowserThread::DB);
}

}  // namespace browser_sync


text:
package github.nisrulz.intents;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ShareCompat;
import java.io.File;

public class ImplicitIntents {

    void openAppPageInPlaystore(Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName()));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void openUrlInBrowser(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void sendEmail(Context context, String[] sendTo, String subject, String body) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("plain/text");
        intent.putExtra(Intent.EXTRA_EMAIL, sendTo);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.putExtra(Intent.EXTRA_TEXT, body);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(Intent.createChooser(intent, ""));
        }
    }

    void call(Context context, String number) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + number));
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) !=
                PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void sendSMS(Context context, String sendToNumber, String message) {
        Uri smsUri = Uri.parse("tel:" + sendToNumber);
        Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
        intent.putExtra("address", sendToNumber);
        intent.putExtra("sms_body", message);
        intent.setType("vnd.android-dir/mms-sms");

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void showLocationInMap(Context context, String latitude, String longitude, String zoomLevel) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        String data = String.format("geo:%s,%s", latitude, longitude);
        if (zoomLevel != null) {
            data = String.format("%s?z=%s", data, zoomLevel);
        }
        intent.setData(Uri.parse(data));

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void showLocationInMap(Context context, String locationName) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + locationName));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void takeAPic(Context context, String dir, String fileName) {
        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString() + "/" + dir, fileName));
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    void shareData(Context context, String dir, String fileName, String type, String data) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType(type);
        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString() + "/" + dir, fileName));
        intent.putExtra(Intent.EXTRA_STREAM, uri.toString());
        intent.putExtra("data", data);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(Intent.createChooser(intent, "Share using"));
        }
    }

    void shareText(Activity activity, String title, String textData) {
        ShareCompat.IntentBuilder.from(activity).setType("text/plain").setChooserTitle(title)
                .setText(textData).startChooser();
    }
}


text:
<?php

namespace Aedart\Laravel\Helpers\Contracts\Notifications;

use Illuminate\Contracts\Notifications\Dispatcher;

/**
 * @deprecated Use \Aedart\Contracts\Support\Helpers\Notifications\NotificationDispatcherAware, in aedart/athenaeum package
 *
 * Notification Dispatcher Aware
 *
 * @see \Illuminate\Contracts\Notifications\Dispatcher
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Laravel\Helpers\Contracts\Notifications
 */
interface NotificationDispatcherAware
{
    /**
     * Set notification dispatcher
     *
     * @param Dispatcher|null $dispatcher Notification Dispatcher Instance
     *
     * @return self
     */
    public function setNotificationDispatcher(?Dispatcher $dispatcher);

    /**
     * Get notification dispatcher
     *
     * If no notification dispatcher has been set, this method will
     * set and return a default notification dispatcher, if any such
     * value is available
     *
     * @see getDefaultNotificationDispatcher()
     *
     * @return Dispatcher|null notification dispatcher or null if none notification dispatcher has been set
     */
    public function getNotificationDispatcher(): ?Dispatcher;

    /**
     * Check if notification dispatcher has been set
     *
     * @return bool True if notification dispatcher has been set, false if not
     */
    public function hasNotificationDispatcher(): bool;

    /**
     * Get a default notification dispatcher value, if any is available
     *
     * @return Dispatcher|null A default notification dispatcher value or Null if no default value is available
     */
    public function getDefaultNotificationDispatcher(): ?Dispatcher;
}


text:
<resources>
    <string name="title_activity_general_settings">General Settings</string>

    <!-- Strings related to Settings -->
    <string name="pref_header_general">General</string>
    <string name="pref_header_lockscreen">Lock Screen</string>
    <string name="pref_header_pattern">Pattern Lock</string>

    <string name="pref_key_enable_notification">enable_notification</string>
    <string name="pref_title_enable_notification">Enable notification</string>
    <string name="pref_description_notification">Status bar notification indicating your
        current environment</string>

    <string name="pref_key_show_lockscreen_notifications">show_lockscreen_notifications</string>
    <string name="pref_title_show_lockscreen_notifications">Show notifications in lockscreen</string>

    <string name="pref_key_hide_persistent_notifications">hide_persistent_notifications</string>
    <string name="pref_title_hide_persistent_notifications">Hide persistent notifications</string>

    <string name="pref_key_hide_low_priority_notifications">hide_low_priority_notifications</string>
    <string name="pref_title_hide_low_priority_notifications">Hide low priority notifications</string>

    <string name="pref_key_lockscreen_wallpaper">lockscreen_wallpaper</string>
    <string name="pref_title_lockscreen_wallpaper">Set wallpaper</string>
    <string name="pref_description_lockscreen_wallpaper_system">Using system wallpaper</string>
    <string name="pref_description_lockscreen_wallpaper_custom">Using custom wallpaper</string>
    <string-array name="pref_entries_lockscreen_wallpaper">
        <item>Use system wallpaper</item>
        <item>Choose custom wallpaper</item>
    </string-array>
    <string-array name="pref_values_lockscreen_wallpaper">
        <item>system</item>
        <item>custom</item>
    </string-array>

    <string name="pref_key_pattern_type">pattern_type</string>
    <string name="pref_title_pattern_type">Pattern lock type</string>
    <string-array name="pref_entries_pattern_type">
        <item>Inbuilt pattern lock (May not work on all devices)</item>
        <item>System pattern lock (Requires root)</item>
        <!--<item>Disabled</item>-->
    </string-array>
    <string-array name="pref_values_pattern_type">
        <item>inbuilt</item>
        <item>system</item>
        <!--<item>disabled</item>-->
    </string-array>

    <string name="pref_key_is_visible_pattern">visible_pattern</string>
    <string name="pref_title_is_visible_pattern">Make pattern visible</string>
    <string name="pref_summary_system_pattern">System pattern</string>
</resources>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudsearch.v1.model;

/**
 * Model definition for AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Search API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime extends com.google.api.client.json.GenericJson {

  /**
   * All day event.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Date allDay;

  /**
   * Non all day event.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String timed;

  /**
   * All day event.
   * @return value or {@code null} for none
   */
  public Date getAllDay() {
    return allDay;
  }

  /**
   * All day event.
   * @param allDay allDay or {@code null} for none
   */
  public AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime setAllDay(Date allDay) {
    this.allDay = allDay;
    return this;
  }

  /**
   * Non all day event.
   * @return value or {@code null} for none
   */
  public String getTimed() {
    return timed;
  }

  /**
   * Non all day event.
   * @param timed timed or {@code null} for none
   */
  public AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime setTimed(String timed) {
    this.timed = timed;
    return this;
  }

  @Override
  public AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime set(String fieldName, Object value) {
    return (AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime) super.set(fieldName, value);
  }

  @Override
  public AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime clone() {
    return (AppsDynamiteSharedCalendarEventAnnotationDataCalendarEventTime) super.clone();
  }

}


text:
"""Scraper for the 4th District Court of Appeals
CourtID: ohioctap_4
Court Short Name: Ohio Dist Ct App 4
Author: Andrei Chelaru
"""

from juriscraper.opinions.united_states.state import ohio

class Site(ohio.Site):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.court_id = self.__module__
        self.court_index = 4


text:
layout: default
---

Nick Jacob

      (617)-680-0337
      me@nickjacob.com
      New York

Generalist engineer with knowledge of web architectures, ops, front-end development.

Education

BAx2, Computer Science, Modern Culture & Media

Brown University 2014 | GPA: 3.8

Skills & Knowledge

languages/runtimes

python

ruby

node.js

c/c++

javascript

html, CSS

java

go

c#

bash/awk/perl

frameworks/tools

redis

nginx/openresty

rack/sinatra

django

mongodb

aws/ec2, s3

docker

etcd, consul

...

Professional Experience

        Founder/CTO

          Mirador Technologies

            12/2013 - Current

Built pipeline for collection & labeling of large image datasets—generated labelled dataset/1.2mil images

Wrote system for parallel classification of images on convolutional neural networks

Developed distributed architecture for realtime image moderation, leveraging NGINX/openresty, gearmand, custom C++ stack to download, resize, and classify images across 6 neural networks in ← 100ms RTT

Deployed, administered, and monitored heterogenous architecture on EC2, 250k+ reqs/day

        Software Development Engineer Intern

          Microsoft Advertising (Display Ad Relevance)

            6/2013 - 9/2013

Implemented image-processing solution to improve ad (creative) categorization

Developed flexible web scraping system for analysis of third-party advertisement payloads

Assessed accuracy through crowdsourcing tasks, integrated project into production pipeline.

        Lead Developer (Freelance)

          Hoodtap

            9/2012 - 5/2013

Designed and implemented scalable backend for mobile application

RESTful API with Ruby client; multi-tier infrastructure

Deployed on EC2; capistrano, puppet

        Teaching Assistant

          CS033
          CS132

            8/2012 - 5/2013

Developed assignments and labs, grading rubrics

Graded Assignments, Exams

Focus on network programming, POSIX I/O (CS033), Javascript (CS132)

        Software Engineering Intern

          Group Commerce

            6/2012 - 8/2012

Built features for core product; deployed to production

Worked in multiple scrum teams, adhered to 2-week agile development cycle

Stories included customer-facing scheduling interface, RESTful API provider for mobile clients, and !multiple client-administered Drupal modules.


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <stddef.h>
#include <stdarg.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/un.h>
#include <pthread.h>

#include "ezcfg.h"
#include "ezcfg-private.h"

#if 1
#define DBG(format, args...) do { \
	char path[256]; \
	FILE *fp; \
	snprintf(path, 256, "/tmp/%d-debug.txt", getpid()); \
	fp = fopen(path, "a"); \
	if (fp) { \
		fprintf(fp, format, ## args); \
		fclose(fp); \
	} \
} while(0)
#else
#define DBG(format, args...)
#endif

/* don't remove nvram socket */
void ezcfg_master_load_socket_conf(struct ezcfg_master *master)
{
	struct ezcfg *ezcfg;
	struct ezcfg_socket *sp = NULL;
	struct ezcfg_socket *nvram_sp = NULL;
	struct ezcfg_socket **psp;
	char *p = NULL;
	int domain, type, proto;
	char address[256];
	int i;
	int socket_number = -1;

	if (master == NULL)
		return ;

	ezcfg = ezcfg_master_get_ezcfg(master);

	/* nvram fake socket */
	//nvram_sp = ezcfg_socket_fake_new(ezcfg, AF_LOCAL, SOCK_STREAM, EZCFG_PROTO_SOAP_HTTP, EZCFG_SOCK_NVRAM_PATH);
	p = ezcfg_common_get_sock_nvram_path(ezcfg);
	if ((p != NULL) && (*p != '\0')) {
		nvram_sp = ezcfg_socket_fake_new(ezcfg, AF_LOCAL, SOCK_STREAM, EZCFG_PROTO_SOAP_HTTP, p);
		if (nvram_sp == NULL) {
			err(ezcfg, "ezcfg_socket_new(nvram_sp)\n");
			return ;
		}
	}

	/* tag listening_sockets to need_delete = true; */
	sp = ezcfg_master_get_listening_sockets(master);
	while(sp != NULL) {
		if((nvram_sp != NULL) && (ezcfg_socket_compare(sp, nvram_sp) == false)) {
			ezcfg_socket_set_need_delete(sp, true);
		}
		sp = ezcfg_socket_get_next(sp);
	}

	/* delete unused fake sockets */
	if (nvram_sp != NULL) {
		ezcfg_socket_delete(nvram_sp);
	}

	/* first get the socket number */
	p = ezcfg_util_get_conf_string(ezcfg_common_get_config_file(ezcfg), EZCFG_EZCFG_SECTION_COMMON, 0, EZCFG_EZCFG_KEYWORD_SOCKET_NUMBER);
	if (p != NULL) {
		socket_number = atoi(p);
		free(p);
	}
	for (i = 0; i < socket_number; i++) {

		/* initialize */
		domain = -1;
		type = -1;
		proto = EZCFG_PROTO_UNKNOWN;
		address[0] = '\0';
		sp = NULL;

		/* socket domain */
		p = ezcfg_util_get_conf_string(ezcfg_common_get_config_file(ezcfg), EZCFG_EZCFG_SECTION_SOCKET, i, EZCFG_EZCFG_KEYWORD_DOMAIN);
		if (p != NULL) {
			domain = ezcfg_util_socket_domain_get_index(p);
			free(p);
		}

		/* socket type */
		p = ezcfg_util_get_conf_string(ezcfg_common_get_config_file(ezcfg), EZCFG_EZCFG_SECTION_SOCKET, i, EZCFG_EZCFG_KEYWORD_TYPE);
		if (p != NULL) {
			type = ezcfg_util_socket_type_get_index(p);
			free(p);
		}

		/* socket protocol */
		p = ezcfg_util_get_conf_string(ezcfg_common_get_config_file(ezcfg), EZCFG_EZCFG_SECTION_SOCKET, i, EZCFG_EZCFG_KEYWORD_PROTOCOL);
		if (p != NULL) {
			proto = ezcfg_util_socket_protocol_get_index(p);
			free(p);
		}

		/* socket address */
		p = ezcfg_util_get_conf_string(ezcfg_common_get_config_file(ezcfg), EZCFG_EZCFG_SECTION_SOCKET, i, EZCFG_EZCFG_KEYWORD_ADDRESS);
		if (p != NULL) {
			snprintf(address, sizeof(address), "%s", p);
			free(p);
			p = NULL;
		}
		if ((domain < 0) ||
		    (type < 0) ||
		    (proto == EZCFG_PROTO_UNKNOWN) ||
		    (address[0] == '\0')) {
			err(ezcfg, "socket setting error\n");
			continue;
		}

		sp = ezcfg_socket_fake_new(ezcfg, domain, type, proto, address);
		if (sp == NULL) {
			err(ezcfg, "init fake socket fail: %m\n");
			continue;
		}

	    	psp = ezcfg_master_get_p_listening_sockets(master);
	    	if (ezcfg_socket_list_in(psp, sp) == true) {
			info(ezcfg, "socket already up\n");
			/* don't delete this socket in listening_sockets */
			ezcfg_socket_list_set_need_delete(psp, sp, false);
			ezcfg_socket_delete(sp);
			continue;
		}

		/* not in listening sockets, create it now */
		/* first delete the fake socket */
		ezcfg_socket_delete(sp);
		/* then create the socket */
		sp = ezcfg_socket_new(ezcfg, domain, type, proto, address);
		if (sp == NULL) {
			err(ezcfg, "init socket fail: %m\n");
			continue;
		}

		if ((domain == AF_LOCAL) &&
		    (address[0] != '@')) {
			ezcfg_socket_set_need_unlink(sp, true);
		}

	    	psp = ezcfg_master_get_p_listening_sockets(master);
		if (ezcfg_socket_list_insert(psp, sp) < 0) {
			err(ezcfg, "insert listener socket fail: %m\n");
			ezcfg_socket_delete(sp);
			continue;
		}

		if (ezcfg_socket_enable_receiving(sp) < 0) {
			err(ezcfg, "enable socket [%s] receiving fail: %m\n", address);
	    		psp = ezcfg_master_get_p_listening_sockets(master);
			ezcfg_socket_list_delete_socket(psp, sp);
			continue;
		}

		if (ezcfg_socket_enable_listening(sp, ezcfg_master_get_sq_len(master)) < 0) {
			err(ezcfg, "enable socket [%s] listening fail: %m\n", address);
	    		psp = ezcfg_master_get_p_listening_sockets(master);
			ezcfg_socket_list_delete_socket(psp, sp);
			continue;
		}

		ezcfg_socket_set_close_on_exec(sp);
	}

	/* delete all sockets taged need_delete = true in need_listening_sockets */
	sp = ezcfg_master_get_listening_sockets(master);
	while(sp != NULL) {
		if(ezcfg_socket_get_need_delete(sp) == true) {
	    		psp = ezcfg_master_get_p_listening_sockets(master);
			ezcfg_socket_list_delete_socket(psp, sp);
			sp = ezcfg_master_get_listening_sockets(master);
		}
		else {
			sp = ezcfg_socket_get_next(sp);
		}
	}
}


text:
<?php
namespace Wwwision\Eventr\Domain\Model;

use Doctrine\ORM\Mapping as ORM;
use Neos\Flow\Annotations as Flow;

/**
 * @Flow\Entity
 * @ORM\Table(name="eventr_event_types")
 */
class EventType
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(inversedBy="eventTypes")
     * @var AggregateType
     */
    protected $aggregateType;

    /**
     * @ORM\Id
     * @var string
     */
    protected $name;

    /**
     * @ORM\Column(name="`schema`", nullable=true, type="json_array")
     * @var array
     */
    protected $schema = null;

    /**
     * @param AggregateType $aggregateType
     * @param string $name
     * @param array $schema
     */
    public function __construct(AggregateType $aggregateType, $name, array $schema = null)
    {
        $this->aggregateType = $aggregateType;
        $this->name = $name;
        $this->schema = $schema;
    }

    /**
     * @return AggregateType
     */
    public function getAggregateType()
    {
        return $this->aggregateType;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return array
     */
    public function getSchema()
    {
        return $this->schema;
    }

    /**
     * HACK HACK HACK
     * @param array $schema
     * @return void
     */
    public function updateSchema(array $schema = null) {
        $this->schema = $schema;
    }

    /**
     * @return bool
     */
    public function hasSchema()
    {
        // TODO The 2nd part is needed because Doctrine hydrates NULL to an empty array
        return $this->schema !== null && $this->schema !== [];
    }

    /**
     * @return string
     */
    function __toString()
    {
        return sprintf('%s.%s', $this->aggregateType->getName(), $this->name);
    }

}


text:
package therian.operation;

import therian.OperationException;
import therian.position.Position;
import therian.position.Position.Readable;

/**
 * Copy operation.
 *
 * @param <SOURCE>
 * @param <TARGET>
 */
public class Copy<SOURCE, TARGET> extends Transform<SOURCE, TARGET, Void, Position.Readable<TARGET>> {
    /**
     * "Copy safely" operation.
     *
     * @param <SOURCE>
     * @param <TARGET>
     */
    public static class Safely<SOURCE, TARGET> extends Copy<SOURCE, TARGET> {

        /**
         * Fluent factory method.
         *
         * @param targetPosition
         * @param sourcePosition
         * @return {@link Copy.Safely}
         */
        public static <S, T> Safely<S, T> to(Position.Readable<T> targetPosition, Position.Readable<S> sourcePosition) {
            return new Safely<>(sourcePosition, targetPosition);
        }

        private Safely(Readable<SOURCE> sourcePosition, Readable<TARGET> targetPosition) {
            super(sourcePosition, targetPosition);
        }

        /**
         * Suppresses {@link OperationException} for failed operation.
         */
        @Override
        public Void getResult() {
            return null;
        }
    }

    /**
     * Fluent factory method.
     *
     * @param targetPosition
     * @param sourcePosition
     * @return {@link Copy}
     */
    public static <S, T> Copy<S, T> to(Position.Readable<T> targetPosition, Position.Readable<S> sourcePosition) {
        return new Copy<>(sourcePosition, targetPosition);
    }

    private Copy(Position.Readable<SOURCE> sourcePosition, Position.Readable<TARGET> targetPosition) {
        super(sourcePosition, targetPosition);
    }
}


text:
using System.Collections.Concurrent;
using System.Threading;

namespace ScnDiscounts.Helpers
{
    public class NamedLocker
    {
        protected readonly ConcurrentDictionary<string, SemaphoreSlim> Lock = new ConcurrentDictionary<string, SemaphoreSlim>();

        public SemaphoreSlim this[string name] => Lock.GetOrAdd(name, i => new SemaphoreSlim(1, 1));
    }
}


text:
package org.wso2.carbon.reporting.custom.ui.beans;

public class FormParameters {

    String formName;
    String formValue;

    public String getFormName() {
        return formName;
    }

    public void setFormName(String formName) {
        this.formName = formName;
    }

    public String getFormValue() {
        return formValue;
    }

    public void setFormValue(String formValue) {
        this.formValue = formValue;
    }

}


text:
package org.zaproxy.zap.network;

import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * A SOCKS proxy.
 *
 *
Contains the host, port, version, and if names should be resolved by the proxy.
 *
 * @since 2.10.0
 * @deprecated (2.12.0) No longer in use.
 */
@Deprecated
public class SocksProxy {

    private static final Logger logger = LogManager.getLogger(SocksProxy.class);

    /** The version of the SOCKS proxy. */
    public enum Version {
        /** Version 4. */
        SOCKS4a(4),
        /**
         * Version 5.
         *
         *
Can resolve names and require authentication.
         */
        SOCKS5(5);

        private final int number;

        Version(int number) {
            this.number = number;
        }

        /**
         * Gets the number of the version.
         *
         * @return the number of the version.
         */
        public int number() {
            return number;
        }

        /**
         * Gets a {@code Version} from the given value (version number).
         *
         *
Defaults to {@link #SOCKS5} when the {@code value} is:
         *
         *

         *
null
         *
empty
         *
not a number
         *
unknown version
         *

         *
         * @param value the value to convert
         * @return the version.
         */
        public static Version from(String value) {
            if (value == null || value.isEmpty()) {
                return SOCKS5;
            }
            int number;
            try {
                number = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                logger.warn("Failed to parse the version: {}", value, e);
                return SOCKS5;
            }

            if (number == SOCKS4a.number) {
                return SOCKS4a;
            }
            if (number == SOCKS5.number) {
                return SOCKS5;
            }

            logger.warn("Unknown version: {}", value);
            return SOCKS5;
        }
    }

    private final String host;
    private final int port;
    private final Version version;
    private final boolean useDns;

    /**
     * Constructs a {@code SocksProxy} with the given host and port.
     *
     *
Uses {@link Version#SOCKS5} and names are resolved by the proxy.
     *
     * @param host the host, must not be {@code null} or empty.
     * @param port the port.
     * @throws NullPointerException if the {@code host} is null.
     * @throws IllegalArgumentException if the {@code host} is empty or the {@code port} is not a
     *     valid port number.
     */
    public SocksProxy(String host, int port) {
        this(host, port, Version.SOCKS5, true);
    }

    /**
     * Constructs a {@code SocksProxy} with the given data.
     *
     * @param host the host, must not be {@code null} or empty.
     * @param port the port.
     * @param version the version, must not be {@code null}.
     * @param useDns {@code true} if the names should be resolved by the proxy, {@code false}
     *     otherwise.
     * @throws NullPointerException if the {@code host} or {@code version} is {@code null}.
     * @throws IllegalArgumentException if the {@code host} is empty or the {@code port} is not a
     *     valid port number.
     */
    public SocksProxy(String host, int port, Version version, boolean useDns) {
        Objects.requireNonNull(host, "The host must not be null.");
        Objects.requireNonNull(version, "The version must not be null.");
        if (host.isEmpty()) {
            throw new IllegalArgumentException("The host must not be empty.");
        }
        if (port <= 0 || port > 65535) {
            throw new IllegalArgumentException(
                    "The port is not valid, must be between 0 and 65535.");
        }
        this.host = host;
        this.port = port;
        this.version = version;
        this.useDns = useDns;
    }

    /**
     * Gets the host (name or address).
     *
     * @return the host, never {@code null} or empty.
     */
    public String getHost() {
        return host;
    }

    /**
     * Gets the port.
     *
     * @return the port.
     */
    public int getPort() {
        return port;
    }

    /**
     * Gets the version.
     *
     * @return the version, never {@code null}.
     */
    public Version getVersion() {
        return version;
    }

    /**
     * Tells whether or not the names should be resolved by the proxy.
     *
     *
Only supported by {@link Version#SOCKS5}.
     *
     * @return {@code true} if the names should be resolved by the proxy, {@code false} otherwise.
     */
    public boolean isUseDns() {
        return useDns;
    }

    @Override
    public int hashCode() {
        return Objects.hash(host, port, useDns, version.number);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        SocksProxy other = (SocksProxy) obj;
        return Objects.equals(host, other.host)
                && port == other.port
                && useDns == other.useDns
                && version == other.version;
    }

    @Override
    public String toString() {
        StringBuilder strBuilder = new StringBuilder(75);
        strBuilder.append("[Host=").append(host);
        strBuilder.append(", Port=").append(port);
        strBuilder.append(", Version=").append(version.number);
        strBuilder.append(", UseDns=").append(useDns);
        strBuilder.append(']');
        return strBuilder.toString();
    }
}


text:
namespace Caliburn.Core.InversionOfControl
{
    using Behaviors;

    /// <summary>
    /// An abstraction that represents a configurable service locator by composing <see cref="IServiceLocator"/> and <see cref="IRegistry"/>.
    /// </summary>
    public interface IContainer : IServiceLocator, IRegistry, IBuilder
    {
        /// <summary>
        /// Installs a proxy factory.
        /// </summary>
        /// <typeparam name="T">The type of the proxy factory.</typeparam>
        /// <returns>A container with an installed proxy factory.</returns>
        IContainer WithProxyFactory<T>()
            where T : IProxyFactory;
    }
}


text:
class ClassVisitor(object):
    def __init__(self):
        self.__visitors = {}
        self.__collect_visitors()

    def __collect_visitors(self):
        for attr in dir(self):
            value = getattr(self, attr)
            types = getattr(value, '__visitor__', ())
            if not types:
                continue

            for cls in types:
                self.__visitors[cls] = value

    def visit(self, value, *args, **kwargs):
        visitor = self.__get_visitor(value)
        return visitor(value, *args, **kwargs)

    def __get_visitor(self, value):
        key = type(value)

        if key not in self.__visitors:
            for cls, func in self.__visitors.items():
                if issubclass(key, cls):
                    self.__visitors[key] = func
                    break

        if key not in self.__visitors:
            return self.default

        return self.__visitors[key]

    def default(self, value, *args, **kwargs):
        raise TypeError(type(value).__name__)

def handle(*types):
    def __decorator(func):
        func.__visitor__ = types
        return func

    return __decorator