text:
package uk.co.real_logic.aeron.common;

import uk.co.real_logic.agrona.concurrent.UnsafeBuffer;
import uk.co.real_logic.agrona.IoUtil;

import java.io.File;

import static java.lang.Boolean.getBoolean;
import static java.lang.System.getProperty;

/**
 * Location of context that is common between the client and the media driver.
 *
 * Properties
 *

 *
aeron.dir.conductor: Use value as directory name for conductor buffers.

 *
aeron.dir.data: Use value as directory name for data buffers.

 *

 */
public class CommonContext implements AutoCloseable
{
    /** Top level Aeron directory */
    public static final String AERON_DIR_PROP_NAME = "aeron.dir";

    public static final String DATA_DIR_NAME = "data";
    public static final String CONDUCTOR_DIR_NAME = "conductor";
    public static final String COUNTERS_DIR_NAME = "counters";

    /** Directory of the data buffers */
    public static final String DATA_DIR_PROP_NAME = "aeron.dir.data";
    /** Default directory for data buffers */
    public static final String DATA_DIR_PROP_DEFAULT = IoUtil.tmpDirName() + "aeron" + File.separator + DATA_DIR_NAME;

    /** Directory of the conductor buffers */
    public static final String ADMIN_DIR_PROP_NAME = "aeron.dir.conductor";
    /** Default directory for conductor buffers */
    public static final String ADMIN_DIR_PROP_DEFAULT = IoUtil.tmpDirName() + "aeron" + File.separator + CONDUCTOR_DIR_NAME;

    /** Directory for the counters */
    public static final String COUNTERS_DIR_PROP_NAME = "aeron.dir.counters";
    /** Default directory for conductor buffers */
    public static final String COUNTERS_DIR_PROP_DEFAULT = IoUtil.tmpDirName() + "aeron" + File.separator + COUNTERS_DIR_NAME;

    /** Name of the default multicast interface */
    public static final String MULTICAST_DEFAULT_INTERFACE_PROP_NAME = "aeron.multicast.default.interface";

    public static final String TO_DRIVER_FILE = "to-driver";
    public static final String TO_CLIENTS_FILE = "to-clients";

    public static final String LABELS_FILE = "labels";
    public static final String VALUES_FILE = "values";

    /** Attempt to delete directories on exit */
    public static final String DIRS_DELETE_ON_EXIT_PROP_NAME = "aeron.dir.delete.on.exit";

    private String dataDirName;
    private String adminDirName;
    private String countersDirName;
    private boolean dirsDeleteOnExit;
    private File toDriverFile;
    private File toClientsFile;
    private UnsafeBuffer counterLabelsBuffer;
    private UnsafeBuffer countersBuffer;

    public CommonContext()
    {
        final String aeronDir = getProperty(AERON_DIR_PROP_NAME);

        if (null == aeronDir)
        {
            dataDirName(getProperty(DATA_DIR_PROP_NAME, DATA_DIR_PROP_DEFAULT));
            adminDirName(getProperty(ADMIN_DIR_PROP_NAME, ADMIN_DIR_PROP_DEFAULT));
            countersDirName(getProperty(COUNTERS_DIR_PROP_NAME, COUNTERS_DIR_PROP_DEFAULT));
        }
        else
        {
            dataDirName(getProperty(DATA_DIR_PROP_NAME, aeronDir + File.separator + DATA_DIR_NAME));
            adminDirName(getProperty(ADMIN_DIR_PROP_NAME, aeronDir + File.separator + CONDUCTOR_DIR_NAME));
            countersDirName(getProperty(COUNTERS_DIR_PROP_NAME, aeronDir + File.separator + COUNTERS_DIR_NAME));
        }

        dirsDeleteOnExit(getBoolean(DIRS_DELETE_ON_EXIT_PROP_NAME));
    }

    public CommonContext conclude()
    {
        toDriverFile(new File(adminDirName(), TO_DRIVER_FILE));
        toClientsFile(new File(adminDirName(), TO_CLIENTS_FILE));

        return this;
    }

    public String dataDirName()
    {
        return dataDirName;
    }

    public CommonContext dataDirName(final String dataDirName)
    {
        this.dataDirName = dataDirName;
        return this;
    }

    public String countersDirName()
    {
        return countersDirName;
    }

    public CommonContext countersDirName(final String countersDirName)
    {
        this.countersDirName = countersDirName;
        return this;
    }

    public static File newDefaultValuesFile()
    {
        return new File(getProperty(COUNTERS_DIR_PROP_NAME, COUNTERS_DIR_PROP_DEFAULT), VALUES_FILE);
    }

    public static File newDefaultLabelsFile()
    {
        return new File(getProperty(COUNTERS_DIR_PROP_NAME, COUNTERS_DIR_PROP_DEFAULT), LABELS_FILE);
    }

    public boolean dirsDeleteOnExit()
    {
        return dirsDeleteOnExit;
    }

    public CommonContext dirsDeleteOnExit(final boolean dirsDeleteOnExit)
    {
        this.dirsDeleteOnExit = dirsDeleteOnExit;
        return this;
    }

    public File toDriverFile()
    {
        return toDriverFile;
    }

    public CommonContext toDriverFile(final File toDriverFile)
    {
        this.toDriverFile = toDriverFile;
        return this;
    }

    public File toClientsFile()
    {
        return toClientsFile;
    }

    public CommonContext toClientsFile(final File toClientsFile)
    {
        this.toClientsFile = toClientsFile;
        return this;
    }

    public CommonContext adminDirName(final String adminDirName)
    {
        this.adminDirName = adminDirName;
        return this;
    }

    public String adminDirName()
    {
        return adminDirName;
    }

    public UnsafeBuffer counterLabelsBuffer()
    {
        return counterLabelsBuffer;
    }

    public CommonContext counterLabelsBuffer(final UnsafeBuffer counterLabelsBuffer)
    {
        this.counterLabelsBuffer = counterLabelsBuffer;
        return this;
    }

    public UnsafeBuffer countersBuffer()
    {
        return countersBuffer;
    }

    public CommonContext countersBuffer(final UnsafeBuffer countersBuffer)
    {
        this.countersBuffer = countersBuffer;
        return this;
    }

    public void close()
    {
    }
}


text:
from ..geometry import Point, LineString
from ..geos import TopologicalError
from heapq import heappush, heappop

class Cell(object):
    """A `Cell`'s centroid property is a potential solution to finding the pole
    of inaccessibility for a given polygon. Rich comparison operators are used
    for sorting `Cell` objects in a priority queue based on the potential
    maximum distance of any theoretical point within a cell to a given
    polygon's exterior boundary.
    """
    def __init__(self, x, y, h, polygon):
        self.x = x
        self.y = y
        self.h = h  # half of cell size
        self.centroid = Point(x, y)  # cell centroid, potential solution

        # distance from cell centroid to polygon exterior
        self.distance = self._dist(polygon)

        # max distance to polygon exterior within a cell
        self.max_distance = self.distance + h * 1.4142135623730951  # sqrt(2)

    # rich comparison operators for sorting in minimum priority queue
    def __lt__(self, other):
        return self.max_distance > other.max_distance

    def __le__(self, other):
        return self.max_distance >= other.max_distance

    def __eq__(self, other):
        return self.max_distance == other.max_distance

    def __ne__(self, other):
        return self.max_distance != other.max_distance

    def __gt__(self, other):
        return self.max_distance < other.max_distance

    def __ge__(self, other):
        return self.max_distance <= other.max_distance

    def _dist(self, polygon):
        """Signed distance from Cell centroid to polygon outline. The returned
        value is negative if the point is outside of the polygon exterior
        boundary.
        """
        inside = polygon.contains(self.centroid)
        distance = self.centroid.distance(LineString(polygon.exterior.coords))
        if inside:
            return distance
        return -distance

def polylabel(polygon, tolerance=1.0):
    """Finds pole of inaccessibility for a given polygon. Based on
    Vladimir Agafonkin's https://github.com/mapbox/polylabel

    Parameters
    ----------
    polygon : shapely.geometry.Polygon
    tolerance : int or float, optional
                `tolerance` represents the highest resolution in units of the
                input geometry that will be considered for a solution. (default
                value is 1.0).

    Returns
    -------
    shapely.geometry.Point
        A point representing the pole of inaccessibility for the given input
        polygon.

    Raises
    ------
    shapely.geos.TopologicalError
        If the input polygon is not a valid geometry.

    Example
    -------
    >>> polygon = LineString([(0, 0), (50, 200), (100, 100), (20, 50),
    ... (-100, -20), (-150, -200)]).buffer(100)
    >>> label = polylabel(polygon, tolerance=10)
    >>> label.wkt
    'POINT (59.35615556364569 121.8391962974644)'
    """
    if not polygon.is_valid:
        raise TopologicalError('Invalid polygon')
    minx, miny, maxx, maxy = polygon.bounds
    cell_size = min(maxx - minx, maxy - miny)
    h = cell_size / 2.0
    cell_queue = []

    # First best cell approximation is one constructed from the centroid
    # of the polygon
    x, y = polygon.centroid.coords[0]
    best_cell = Cell(x, y, 0, polygon)

    # build a regular square grid covering the polygon
    x = minx
    while x < maxx:
        y = miny
        while y < maxy:
            heappush(cell_queue, Cell(x + h, y + h, h, polygon))
            y += cell_size
        x += cell_size

    # minimum priority queue
    while cell_queue:
        cell = heappop(cell_queue)

        # update the best cell if we find a better one
        if cell.distance > best_cell.distance:
            best_cell = cell

        # continue to the next iteration if we cant find a better solution
        # based on tolerance
        if cell.max_distance - best_cell.distance <= tolerance:
            continue

        # split the cell into quadrants
        h = cell.h / 2.0
        heappush(cell_queue, Cell(cell.x - h, cell.y - h, h, polygon))
        heappush(cell_queue, Cell(cell.x + h, cell.y - h, h, polygon))
        heappush(cell_queue, Cell(cell.x - h, cell.y + h, h, polygon))
        heappush(cell_queue, Cell(cell.x + h, cell.y + h, h, polygon))

    return best_cell.centroid

redpajama_set_name: RedPajamaGithub


text:
"""
For creating healpix maps from catalogs.
"""
import os
from os.path import join
import shutil
import tempfile
import subprocess
from collections import Counter
from collections import OrderedDict as odict

import fitsio
import numpy as np
import numpy.lib.recfunctions as recfuncs
import healpy as hp
from scipy.interpolate import interp1d
from scipy.optimize import brentq

import ugali.utils.skymap
import ugali.utils.binning
from ugali.utils.projector import cel2gal, gal2cel
from ugali.utils.healpix import ang2pix, pix2ang, superpixel, read_map
from ugali.utils.shell import mkdir
from ugali.utils.logger import logger
from ugali.utils.config import Config
from ugali.utils.constants import MAGLIMS

class Maglims(object):
    """ Object for deriving magnitude limits from the catalog """

    def __init__(self, config):
        self.config = Config(config)
        self._setup()

    def _setup(self):
        self.nside_catalog = self.config['coords']['nside_catalog']
        self.nside_mask = self.config['coords']['nside_mask']
        self.nside_pixel = self.config['coords']['nside_pixel']

        self.filenames = self.config.getFilenames()

        self.footfile = self.config['data']['footprint']
        try:
            self.footprint = fitsio.read(self.footfile)['I'].ravel()
        except:
            logger.warn("Couldn't open %s; will pass through."%self.footfile)
            self.footprint = self.footfile

    def run(self,field=None,simple=False,force=False):
        """
        Loop through pixels containing catalog objects and calculate
        the magnitude limit. This gets a bit convoluted due to all
        the different pixel resolutions...
        """
        if field is None: fields = [1,2]
        else:             fields = [field]
        for filenames in self.filenames.compress(~self.filenames.mask['catalog']).data:
            infile = filenames['catalog']
            for f in fields:
                outfile = filenames['mask_%i'%f]
                if os.path.exists(outfile) and not force:
                    logger.info("Found %s; skipping..."%outfile)
                    continue

                pixels,maglims=self.calculate(infile,f,simple)
                logger.info("Creating %s"%outfile)
                outdir = mkdir(os.path.dirname(outfile))
                data = odict()
                data['PIXEL']=pixels
                data['MAGLIM']=maglims.astype('f4')
                ugali.utils.healpix.write_partial_map(outfile,data,
                                                      self.nside_pixel)

    def calculate(self, infile, field=1, simple=False):
        logger.info("Calculating magnitude limit from %s"%infile)

        #manglefile = self.config['mangle']['infile_%i'%field]
        #footfile = self.config['data']['footprint']
        #try:
        #    footprint = fitsio.read(footfile)['I'].ravel()
        #except:
        #    logger.warn("Couldn't open %s; will try again."%footfile)
        #    footprint = footfile

        mag_column = self.config['catalog']['mag_%i_field'%field]
        magerr_column = self.config['catalog']['mag_err_%i_field'%field]

        # For simple maglims
        release = self.config['data']['release'].lower()
        band    = self.config['catalog']['mag_%i_band'%field]
        pixel_pix_name = 'PIX%i'%self.nside_pixel

        # If the data already has a healpix pixel assignment then use it
        # Otherwise recalculate...
        try:
            data = fitsio.read(infile,columns=[pixel_pix_name])
        except ValueError as e:
            logger.info(str(e))
            columns=[self.config['catalog']['lon_field'],
                     self.config['catalog']['lat_field']]
            data = fitsio.read(infile,columns=columns)[columns]
            pix = ang2pix(self.nside_pixel,data[columns[0]],data[columns[1]])
            data = recfuncs.rec_append_fields(data,pixel_pix_name,pix)

        #mask_pixels = np.arange( hp.nside2npix(self.nside_mask), dtype='int')
        mask_maglims = np.zeros(hp.nside2npix(self.nside_mask))

        out_pixels = np.zeros(0,dtype='int')
        out_maglims = np.zeros(0)

        # Find the objects in each pixel
        pixel_pix = data[pixel_pix_name]
        mask_pix = ugali.utils.skymap.superpixel(pixel_pix,self.nside_pixel,self.nside_mask)
        count = Counter(mask_pix)
        pixels = sorted(count.keys())
        pix_digi = np.digitize(mask_pix,pixels).argsort()
        idx = 0
        min_num = 500
        signal_to_noise = 10.
        magerr_lim = 1/signal_to_noise
        for pix in pixels:
            # Calculate the magnitude limit in each pixel
            num = count[pix]
            objs = data[pix_digi[idx:idx+num]]
            idx += num
            if simple:
                # Set constant magnitude limits
                logger.debug("Simple magnitude limit for %s"%infile)
                mask_maglims[pix] = MAGLIMS[release][band]
            elif num < min_num:
                logger.info('Found <%i objects in pixel %i'%(min_num,pix))
                mask_maglims[pix] = 0
            else:
                mag = objs[mag_column]
                magerr = objs[magerr_column]
                # Estimate the magnitude limit as suggested by:
                # https://deswiki.cosmology.illinois.edu/confluence/display/DO/SVA1+Release+Document
                # (https://desweb.cosmology.illinois.edu/confluence/display/Operations/SVA1+Doc)
                maglim = np.median(mag[(magerr>0.9*magerr_lim)&(magerr<1.1*magerr_lim)])

                # Alternative method to estimate the magnitude limit by fitting median
                #mag_min, mag_max = mag.min(),mag.max()
                #mag_bins = np.arange(mag_min,mag_max,0.1) #0.1086?
                #x,y = ugali.utils.binning.binnedMedian(mag,magerr,mag_bins)
                #x,y = x[~np.isnan(y)],y[~np.isnan(y)]
                #magerr_med = interp1d(x,y)
                #mag0 = np.median(x)
                #maglim = brentq(lambda a: magerr_med(a)-magerr_lim,x.min(),x.max(),disp=False)
                # Median from just objects near magerr cut

                mask_maglims[pix] = maglim

            logger.debug("%i (n=%i): maglim=%g"%(pix,num,mask_maglims[pix]))
            subpix = ugali.utils.skymap.subpixel(pix, self.nside_mask, self.nside_pixel)
            maglims = np.zeros(len(subpix)) + mask_maglims[pix]
            out_pixels = np.append(out_pixels,subpix)
            out_maglims = np.append(out_maglims,maglims)

        # Remove empty pixels
        logger.info("Removing empty pixels")
        idx = np.nonzero(out_maglims > 0)[0]
        out_pixels  = out_pixels[idx]
        out_maglims = out_maglims[idx]

        # Remove pixels outside the footprint
        if self.footfile:
            logger.info("Checking footprint against %s"%self.footfile)
            lon,lat = pix2ang(self.nside_pixel,out_pixels)
            if self.config['coords']['coordsys'] == 'gal':
                ra,dec = gal2cel(lon,lat)
            else:
                ra,dec = lon,lat
            footprint = inFootprint(self.footprint,ra,dec)
            idx = np.nonzero(footprint)[0]
            out_pixels = out_pixels[idx]
            out_maglims = out_maglims[idx]

        logger.info("MAGLIM = %.3f +/- %.3f"%(np.mean(out_maglims),np.std(out_maglims)))
        return out_pixels,out_maglims

def inFootprint(footprint,ra,dec):
    """
    Check if set of ra,dec combinations are in footprint.
    Careful, input files must be in celestial coordinates.

    filename : Either healpix map or mangle polygon file
    ra,dec   : Celestial coordinates

    Returns:
    inside   : boolean array of coordinates in footprint
    """
    if footprint is None:
        return np.ones(len(ra),dtype=bool)

    try:
        if isinstance(footprint,str) and os.path.exists(footprint):
            filename = footprint
            #footprint = hp.read_map(filename,verbose=False)
            #footprint = fitsio.read(filename)['I'].ravel()
            footprint = read_map(filename)
        nside = hp.npix2nside(len(footprint))
        pix = ang2pix(nside,ra,dec)
        inside = (footprint[pix] > 0)
    except IOError:
        logger.warning("Failed to load healpix footprint; trying to use mangle...")
        inside = inMangle(filename,ra,dec)
    return inside

def inMangle(polyfile,ra,dec):
    coords = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
    logger.debug("Writing coordinates to %s"%coords.name)
    np.savetxt(coords, np.array( [ra,dec] ).T, fmt='%.6g' )
    coords.close()

    weights = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
    cmd = "polyid -W %s %s %s"%(polyfile,coords.name,weights.name)
    logger.debug(cmd)
    subprocess.call(cmd,shell=True)

    tmp = tempfile.NamedTemporaryFile(suffix='.txt',delete=False)
    cmd = """awk '{if($3==""){$3=0} print $1, $2, $3}' %s > %s"""%(weights.name,tmp.name)
    logger.debug(cmd)
    subprocess.call(cmd,shell=True)

    data = np.loadtxt(tmp.name,unpack=True,skiprows=1)[-1]
    for f in [coords,weights,tmp]:
        logger.debug("Removing %s"%f.name)
        os.remove(f.name)

    return data > 0

#def simple_maglims(config,dirname='simple',force=False):
#    """
#    Create simple, uniform magnitude limits based on nominal
#    survey depth.
#    """
#    DeprecationWarning("'simple_maglims' is deprecated")
#    filenames = config.getFilenames()
#    release = config['data']['release'].lower()
#    #band_1 = config['isochrone']['mag_1_field']
#    #band_2 = config['isochrone']['mag_2_field']
#    band_1 = config['catalog']['mag_1_field']
#    band_2 = config['catalog']['mag_2_field']
#    mask_1 = filenames['mask_1'].compressed()
#    mask_2 = filenames['mask_2'].compressed()
#    basedir,basename = os.path.split(config['mask']['dirname'])
#    if basename == dirname:
#        raise Exception("Input and output directory are the same.")
#    outdir = mkdir(os.path.join(basedir,dirname))
#
#    for band, infiles in [(band_1,mask_1),(band_2,mask_2)]:
#        maglim = MAGLIMS[release][band]
#        for infile in infiles:
#            basename = os.path.basename(infile)
#            outfile = join(outdir,basename)
#            logger.debug('Reading %s...'%infile)
#            f = pyfits.open(infile)
#            f[1].data['MAGLIM'][:] = maglim
#            logger.debug('Writing %s...'%outfile)
#            f.writeto(outfile,clobber=True)

def split(config,dirname='split',force=False):
    """ Take a pre-existing maglim map and divide it into
    chunks consistent with the catalog pixels. """

    config = Config(config)
    filenames = config.getFilenames()
    #healpix = filenames['pix'].compressed()

    # Check that things are ok
    basedir,basename = os.path.split(config['mask']['dirname'])
    #if basename == dirname:
    #    msg = "Input and output directory are the same."
    #    raise Exception(msg)
    outdir = mkdir(os.path.join(basedir,dirname))

    nside_catalog = config['coords']['nside_catalog']
    nside_pixel = config['coords']['nside_pixel']

    release = config['data']['release'].lower()
    band1 = config['catalog']['mag_1_band']
    band2 = config['catalog']['mag_2_band']

    # Read the magnitude limits
    maglimdir = config['maglim']['dirname']

    maglimfile_1 = join(maglimdir,config['maglim']['filename_1'])
    logger.info("Reading %s..."%maglimfile_1)
    maglim1 = read_map(maglimfile_1)

    maglimfile_2 = join(maglimdir,config['maglim']['filename_2'])
    logger.info("Reading %s..."%maglimfile_2)
    maglim2 = read_map(maglimfile_2)

    # Read the footprint
    footfile = config['data']['footprint']
    logger.info("Reading %s..."%footfile)
    footprint = read_map(footfile)

    # Output mask names
    mask1 = os.path.basename(config['mask']['basename_1'])
    mask2 = os.path.basename(config['mask']['basename_2'])

    for band,maglim,base in [(band1,maglim1,mask1),(band2,maglim2,mask2)]:
        nside_maglim = hp.npix2nside(len(maglim))
        if nside_maglim != nside_pixel:
            msg = "Mask nside different from pixel nside"
            logger.warning(msg)
            #raise Exception(msg)

        pixels = np.nonzero(maglim>0)[0]
        superpix = superpixel(pixels,nside_maglim,nside_catalog)
        healpix = np.unique(superpix)
        for hpx in healpix:
            outfile = join(outdir,base)%hpx
            if os.path.exists(outfile) and not force:
                logger.warning("Found %s; skipping..."%outfile)
                continue

            pix = pixels[superpix == hpx]
            print(hpx, len(pix))

            logger.info('Writing %s...'%outfile)
            data = odict()
            data['PIXEL']=pix
            data['MAGLIM']=maglim[pix].astype('f4')
            data['FRACDET']=footprint[pix].astype('f4')
            ugali.utils.healpix.write_partial_map(outfile,data,nside_pixel)

if __name__ == "__main__":
    from optparse import OptionParser
    usage = "Usage: %prog  [options] input"
    description = "python script"
    parser = OptionParser(usage=usage,description=description)
    (opts, args) = parser.parse_args()


text:
Linkedin Analysis tool

Analyze person's linkedin profile and get the latest information about his working skills, his
      projects, his positions and recommendations received and experience.

      <input type="text" class="form-control" placeholder="Analyze for..." [(ngModel)]="login">

        <button class="btn btn-secondary btn-success" type="button"
                data-loading-text=""
                (click)="analyze()"
                [ngClass]="{'disabled':  !login || login == '' }">
          Analyze
        </button>

Positions overview

Overview candidate's positions. Understanding this kind of information can help to clarify correct candidate
        positioning.

Skills and interests

Explore candidate skills and approves of his skills. It can be a specialist with a strong knowledge in field
        you are interested in. Also have a look at candidates interests.§

Educations and courses

Browse candidate educations and courses. Well certified specialist is more preferable than not certified. Have
        a look at all types of educations that candidate took.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class SomeClass //Don't know what the class does!
{
    const int max_count = 6;
    class InnerClass
    {
        void VariableToString(bool variable)
        {
            string variableAsString = variable.ToString();
            Console.WriteLine(variableAsString);
        }
    }
    public static void Input()
    {
        SomeClass.InnerClass installation = new SomeClass.InClass_class_123();
        installation.VariableToString(true);
    }
}


text:
package androidx.plmgrdemo;

import java.io.File;
import java.util.Collection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.pluginmgr.PlugInfo;
import androidx.pluginmgr.PluginManager;

public class MainActivity extends Activity {
	// private EditText pluginDirTxt;
	// private Button pluginLoader;
	private ListView pluglistView;
	//
	private PluginManager plugMgr;

	private static final String sdcard = Environment
			.getExternalStorageDirectory().getPath();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final EditText pluginDirTxt = (EditText) findViewById(R.id.pluginDirTxt);
		Button pluginLoader = (Button) findViewById(R.id.pluginLoader);
		pluglistView = (ListView) findViewById(R.id.pluglist);

		plugMgr = PluginManager.getInstance(this);

		String pluginSrcDir = sdcard + "/Download";
		pluginDirTxt.setText(pluginSrcDir);

		pluglistView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				plugItemClick(position);
			}
		});

		final Context context = this;
		pluginLoader.setOnClickListener(new View.OnClickListener() {
			private volatile boolean plugLoading = false;

			@Override
			public void onClick(View v) {
				final String dirText = pluginDirTxt.getText().toString().trim();
				if (TextUtils.isEmpty(dirText)) {
					Toast.makeText(context, getString(R.string.pl_dir),
							Toast.LENGTH_LONG).show();
					return;
				}
				if (plugLoading) {
					Toast.makeText(context, getString(R.string.loading),
							Toast.LENGTH_LONG).show();
					return;
				}
				String strDialogTitle = getString(R.string.dialod_loading_title);
				String strDialogBody = getString(R.string.dialod_loading_body);
				final ProgressDialog dialogLoading = ProgressDialog.show(
						context, strDialogTitle, strDialogBody, true);
				new Thread(new Runnable() {
					@Override
					public void run() {
						plugLoading = true;
						try {
							Collection<PlugInfo> plugs = plugMgr
									.loadPlugin(new File(dirText));
							setPlugins(plugs);
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							dialogLoading.dismiss();
						}
						plugLoading = false;
					}
				}).start();
			}
		});
	}

	private void plugItemClick(int position) {

		PlugInfo plug = (PlugInfo) pluglistView.getItemAtPosition(position);
		plugMgr.startMainActivity(this, plug.getPackageName());

//        LPluginBugManager.addBugListener(new LPluginBugListener() {
//            @Override
//            public void OnError(LPluginBug bug) {
//
//                Log.e("DEBUG", bug.error.getMessage());
//                android.os.Process.killProcess(bug.processId);
//                System.exit(10);
//            }
//        });
//        LPluginOpener.startPlugin(MainActivity.this, plug.getFilePath());
	}

	private void setPlugins(final Collection<PlugInfo> plugs) {
		if (plugs == null || plugs.isEmpty()) {
			return;
		}
		final ListAdapter adapter = new PlugListViewAdapter(this, plugs);
		runOnUiThread(new Runnable() {
			public void run() {
				pluglistView.setAdapter(adapter);
			}
		});
	}
}


text:
// Copyright 2017 Google LLC
//
// 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.

/**
 * @fileoverview An element that performs a status query and binds the
 * result.
 *
 * @suppress {reportUnknownTypes}
 */

let StatusElement = Polymer({
  is: 'detangle-status',

  properties: {
    /**
     * The profile we're operating in.
     *
     * @type {(string|undefined)}
     */
    thisProfile: {
      type: String,
      notify: true,
      readOnly: true,
    },

    /**
     * The networkClass as set in managed policy.
     *
     * @type {(string|undefined)}
     */
    networkClass: {
      type: String,
      notify: true,
      readOnly: true,
    },
  },

  /**
   * If we're not the singleton instance, bind to it's properties.  If we are
   * then poll the background page for status every 500ms until we get a
   * response.
   *
   * @override
   */
  ready: function() {
    const handleResponse = msg => {
      // We use setters here because the variables are read only to prevent
      // parent objects from overwriting values.
      this._setThisProfile(msg && msg.running_in);
      this._setNetworkClass(msg && msg.network_class);
    };

    const pollStatus = () => {
      if (this.thisProfile) {
        return;
      }

      // This is fairly aggressive polling, but it should only be on visible
      // pages like the popup or options page, which should only remain in this
      // state for a relatively short period.
      setTimeout(pollStatus, 500);
      chrome.runtime.sendMessage({'command': 'status'}, handleResponse);
    };

    if (!StatusElement.instance) {
      StatusElement.instance = this;
      pollStatus();
      return;
    }

    StatusElement.instance.addEventListener('this-profile-changed', () => {
      this._setThisProfile(StatusElement.instance.thisProfile);
    });
    StatusElement.instance.addEventListener('network-class-changed', () => {
      this._setNetworkClass(StatusElement.instance.networkClass);
    });
    this._setThisProfile(StatusElement.instance.thisProfile);
    this._setNetworkClass(StatusElement.instance.networkClass);
  },
});


text:
namespace Springboard365.Xrm.Plugins.Core.Test
{
    using Microsoft.Xrm.Sdk;
    using Springboard365.Xrm.Plugins.Core.Constants;
    using Springboard365.Xrm.Plugins.Core.Test.Entities;
    using Springboard365.Xrm.UnitTest.Core;

    public class UpdatePluginSpecificationFixture : SpecificationFixture<DummyUpdatePlugin>
    {
        public override void PerformTestSetup()
        {
            ServiceProvider = ServiceProviderInitializer.Setup().WithInputParameters(() => new ParameterCollection
            {
                { InputParameterType.Target, new Contact() }
            });
        }
    }
}


text:
package com.nitesh.alg.maxsubarray;

import java.util.ArrayList;

import org.junit.Before;
import org.junit.Test;

public class MaxSubArrayBruteForceTest {
	int[] arayl;
	MaxSubArrayBruteForce maxSub;

	/*
	 * private int[] generateArray(int size){ int[] p = new int[size]; return p;
	 * }
	 */

	@Before
	public void setUp() {
		// arayl = generateArray(s);
		arayl = new int[] { -2, 5, -7, 2, 10, -3, 9, -7 , -2, 9};
		maxSub = new MaxSubArrayBruteForce();
	}

	@Test
	public void test_findMaxSubArraySolution() {
		MaxSubArrayBruteForce.SubArrayResult result = maxSub
				.findMaxSubArraySolution(arayl);
		System.out.println("Low = " + result.low);
		System.out.println("High = " + result.high);
		System.out.println("MaxSum = " + result.sum);
	}

}


text:
import {
  Component, ElementRef, AfterViewInit, Renderer, ViewChild, ViewChildren, QueryList,
  ContentChildren
} from "@angular/core";
import {FormlyMessages, FormlyMessage} from "./../services/formly.messages";
import {FormlyPubSub} from "./../services/formly.event.emitter";
import { Field } from "./field";

@Component({
  selector: "formly-field-input",
  template: `

      {{templateOptions.label}}
        <input type="{{templateOptions.type}}" [ngControl]="key" class="form-control" id="{{key}}"
          placeholder="{{templateOptions.placeholder}}" [disabled]="templateOptions.disabled"
          (keyup)="inputChange($event, 'value')" (change)="inputChange($event, 'value')" [(ngModel)]="model"
          [ngClass]="{'form-control-danger': !form.controls[key].valid}" #inputElement>
        {{templateOptions.description}}
        <formly-message [control]="key"></formly-message>

    `,
  directives: [FormlyMessage],
  inputs: [ "form", "update", "templateOptions", "key", "field", "formModel", "model"],
  queries: {inputComponent: new ViewChildren("inputElement")}
})
export class FormlyFieldInput extends Field implements AfterViewInit {

  constructor(fm: FormlyMessages, ps: FormlyPubSub, renderer: Renderer) {
    super(fm, ps, renderer);
  }

  inputComponent: QueryList<ElementRef>;

  public set focus (value: boolean) {
    if (this.inputComponent.length > 0) {
      this.renderer.invokeElementMethod(this.inputComponent.first.nativeElement, "focus", []);
    }
    this._focus = value;
  }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Har = mongoose.model('Har');

/**
 * Globals
 */
var user, har;

/**
 * Unit tests
 */
describe('Har Model Unit Tests:', function() {
  beforeEach(function(done) {
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: 'username',
      password: 'password'
    });

    user.save(function() {
      har = new Har({
        name: 'Har Name',
        user: user
      });

      done();
    });
  });

  describe('Method Save', function() {
    it('should be able to save without problems', function(done) {
      this.timeout(0);
      return har.save(function(err) {
        should.not.exist(err);
        done();
      });
    });

    it('should be able to show an error when try to save without name', function(done) {
      har.name = '';

      return har.save(function(err) {
        should.exist(err);
        done();
      });
    });
  });

  afterEach(function(done) {
    Har.remove().exec(function(){
      User.remove().exec(function(){
        done();
      });
    });
  });
});


text:
require 'tmpdir'

def main
  libjpeg_ratios = []
  mozjpeg_ratios = []

  Dir.mktmpdir("compression_test") do |temp_dir|
    run_command("git ls-files content/images/").split("\n").each_with_index do |in_path, i|
      extname = File.extname(in_path)
      next if extname != ".jpg"

      name = File.basename(in_path)

      in_size, libjpeg_out_size, libjpeg_out_size_ratio =
        optimize_with_program("/usr/local/opt/libjpeg", in_path, "#{temp_dir}/libjpeg_#{name}")

      # Was probably already optimized.
      if libjpeg_out_size.nil?
        puts "skipped: #{in_path}"
        next
      end

      _in_size, mozjpeg_out_size, mozjpeg_out_size_ratio =
        optimize_with_program("/usr/local/opt/mozjpeg", in_path, "#{temp_dir}/mozjpeg_#{name}")
        # [0, 0, 0]

      if mozjpeg_out_size.nil?
        puts "skipped: #{in_path}"
        next
      end

      libjpeg_ratios << libjpeg_out_size_ratio
      mozjpeg_ratios << mozjpeg_out_size_ratio

      puts "#{in_path} #{in_size} #{libjpeg_out_size} #{libjpeg_out_size_ratio} #{mozjpeg_out_size} #{mozjpeg_out_size_ratio}"
    end
  end

  puts ""
  puts "average libjpeg compression ratio: #{libjpeg_ratios.sum / libjpeg_ratios.length}"
  puts "average mozjpeg compression ratio: #{mozjpeg_ratios.sum / mozjpeg_ratios.length}"
end

#
# ---
#

def optimize_with_program(program_path, in_path, out_path)
  run_command("#{program_path}/bin/djpeg #{in_path} | #{program_path}/bin/cjpeg -outfile #{out_path} -optimize -progressive")

  in_size = File.size(in_path)
  out_size = File.size(out_path)

  # Reject the data point unless we compressed by more than 5%. If we didn't,
  # it probably means the image was already optimized because these programs
  # tend to do a pretty good job.
  if out_size >= in_size - in_size * 0.05
    return [nil, nil, nil]
  end

  [in_size, out_size, out_size.to_f / in_size]
end

def run_command(command, abort: true)
  ret = `#{command}`
  if $? != 0
    if abort
      abort("command failed: #{command}")
    else
      return false
    end
  end
  ret.strip
end

#
# ---
#

main


text:
package de.unima.peoplesearch.extraction.qualitychecks;

import java.io.IOException;
import java.util.List;

import de.unima.peoplesearch.extraction.Pipeline;
import edu.stanford.nlp.ie.AbstractSequenceClassifier;
import edu.stanford.nlp.ie.crf.CRFClassifier;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;

public class NamedEntityCheckerGerman extends AbstractNamedEntityChecker {

	private AbstractSequenceClassifier<CoreLabel> classifier;
	public NamedEntityCheckerGerman(double threshold){
		super(threshold);

		 String serializedClassifier = "data/classifiers/hgc_175m_600.crf.ser.gz";
		 try {
			 classifier = CRFClassifier.getClassifier(serializedClassifier);
		} catch (ClassCastException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public boolean containsNERPerson(String heading) {

		int personcounter = 0;
		int size =0;
		 for (List<CoreLabel> lcl : classifier.classify(heading)) {
			 size = size  +lcl.size();
	          for (CoreLabel cl : lcl) {

	             String ne = cl.get(CoreAnnotations.AnswerAnnotation.class);
	            if(ne.equals("I-PER")){
	            	personcounter++;

	            }
	          }
	        }
		double ratio = (double) (((double) personcounter) /((double)size) );

		return  ratio  >= Pipeline.THRESHOLD;
	}

}


text:
package net.violet.platform.schedulers;

import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import net.violet.platform.api.callers.APICaller;
import net.violet.platform.datamodel.Music;
import net.violet.platform.datamodel.factories.Factories;
import net.violet.platform.dataobjects.MusicData;
import net.violet.platform.util.CCalendar;

public class SchedulingAtom {

	public static final String HOUR = "time_h";
	public static final String MINUTE = "time_m";
	public static final String DURATION = "duration";
	public static final String MEDIA = "media";

	private final int hour;
	private final int minute;
	private final Integer duration;
	private final String media;

	/**
	 * Returns true if the given object is a valid atom.
	 * @param atom the object to test
	 * @param withDuration true if the atom should contain duration information
	 * @param withMedia true if the atom should contain media information
	 * @return
	 */
	public static boolean isValid(Object atom, boolean withDuration, boolean withMedia) {
		if (!(atom instanceof Map)) {
			return false;
		}

		final Map<String, Object> theAtom = (Map<String, Object>) atom;
		final Object hourSetting = theAtom.get(SchedulingAtom.HOUR);
		final Object minuteSetting = theAtom.get(SchedulingAtom.MINUTE);

		if ((hourSetting == null) || (minuteSetting == null)) {
			return false;
		}

		try {
			final int hour = (Integer) hourSetting;
			final int minute = (Integer) minuteSetting;
			if ((hour < 0) || (hour > 23) || (minute < 0) || (minute > 59)) {
				return false;
			}

			if (withDuration && (!theAtom.containsKey(SchedulingAtom.DURATION) || ((Integer) theAtom.get(SchedulingAtom.DURATION) <= 0))) {
				return false;
			}
		} catch (final ClassCastException e) {
			return false;
		}

		if (withMedia && !theAtom.containsKey(SchedulingAtom.MEDIA)) {
			return false;
		}

		return true;
	}

	public SchedulingAtom(Map<String, Object> atomMap) {
		this((Integer) atomMap.get(SchedulingAtom.HOUR), (Integer) atomMap.get(SchedulingAtom.MINUTE), (Integer) atomMap.get(SchedulingAtom.DURATION), (String) atomMap.get(SchedulingAtom.MEDIA));
	}

	public SchedulingAtom(int hour, int minute, Integer duration, String media) {
		this.hour = hour;
		this.minute = minute;
		this.duration = duration;
		this.media = media;
	}

	public SchedulingAtom(String formattedTime, Integer duration, String media) {
		final CCalendar calendar = new CCalendar(formattedTime, TimeZone.getTimeZone("UTC"));
		this.hour = calendar.getHour();
		this.minute = calendar.getMinute();
		this.duration = duration;
		this.media = media;
	}

	/**
	 * Return true if the current atom is after the given atom object.
	 * @param atom
	 * @return
	 */
	public boolean isAfter(SchedulingAtom atom) {
		return (this.hour * 60 + this.minute) > (atom.hour * 60 + atom.minute);
	}

	public int getHour() {
		return this.hour;
	}

	public int getMinute() {
		return this.minute;
	}

	public Integer getDuration() {
		return this.duration;
	}

	public String getMedia() {
		return this.media;
	}

	public String getFormattedTime() {
		final CCalendar theCalendar = new CCalendar(true); //new CCalendar(true, TimeZone.getTimeZone("UTC"));
		theCalendar.setHour(this.hour);
		theCalendar.setMinute(this.minute);

		return theCalendar.getTimeFormated(true);
	}

	public Map<String, Object> getSchedulingAtomMap(APICaller caller) {
		final Map<String, Object> atomMap = new HashMap<String, Object>();
		atomMap.put(SchedulingAtom.HOUR, this.hour);
		atomMap.put(SchedulingAtom.MINUTE, this.minute);

		if (getDuration() != null) {
			atomMap.put(SchedulingAtom.DURATION, this.duration);
		}

		if (this.media != null) {
			final Music theMusic = Factories.MUSIC.find(Long.parseLong(this.media));
			if (theMusic != null) {
				atomMap.put(SchedulingAtom.MEDIA, MusicData.getData(theMusic).getApiId(caller));
			}
		}
		return atomMap;
	}

}


text:
export const borderColor = '#c0c0c0';
export const borderRadius = '3px';
export const formLineHeight = '2.5';
export const formPadding = '0 10px';


text:
// Copyright (c) 2015-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <httprpc.h>

#include <chainparams.h>
#include <crypto/hmac_sha256.h>
#include <httpserver.h>
#include <rpc/protocol.h>
#include <rpc/server.h>
#include <ui_interface.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/translation.h>
#include <walletinitinterface.h>

#include <algorithm>
#include <iterator>
#include <map>
#include <memory>
#include <stdio.h>
#include <set>
#include <string>

#include <boost/algorithm/string.hpp> // boost::trim

/** WWW-Authenticate to present with 401 Unauthorized response */
static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";

/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
 * re-lock the wallet.
 */
class HTTPRPCTimer : public RPCTimerBase
{
public:
    HTTPRPCTimer(struct event_base* eventBase, std::function<void()>& func, int64_t millis) :
        ev(eventBase, false, func)
    {
        struct timeval tv;
        tv.tv_sec = millis/1000;
        tv.tv_usec = (millis%1000)*1000;
        ev.trigger(&tv);
    }
private:
    HTTPEvent ev;
};

class HTTPRPCTimerInterface : public RPCTimerInterface
{
public:
    explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
    {
    }
    const char* Name() override
    {
        return "HTTP";
    }
    RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
    {
        return new HTTPRPCTimer(base, func, millis);
    }
private:
    struct event_base* base;
};

/* Pre-base64-encoded authentication token */
static std::string strRPCUserColonPass;
/* Stored RPC timer interface (for unregistration) */
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
/* RPC Auth Whitelist */
static std::map<std::string, std::set<std::string>> g_rpc_whitelist;
static bool g_rpc_whitelist_default = false;

static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
{
    // Send error reply from json-rpc error object
    int nStatus = HTTP_INTERNAL_SERVER_ERROR;
    int code = find_value(objError, "code").get_int();

    if (code == RPC_INVALID_REQUEST)
        nStatus = HTTP_BAD_REQUEST;
    else if (code == RPC_METHOD_NOT_FOUND)
        nStatus = HTTP_NOT_FOUND;

    std::string strReply = JSONRPCReply(NullUniValue, objError, id);

    req->WriteHeader("Content-Type", "application/json");
    req->WriteReply(nStatus, strReply);
}

//This function checks username and password against -rpcauth
//entries from config file.
static bool multiUserAuthorized(std::string strUserPass)
{
    if (strUserPass.find(':') == std::string::npos) {
        return false;
    }
    std::string strUser = strUserPass.substr(0, strUserPass.find(':'));
    std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);

    for (const std::string& strRPCAuth : gArgs.GetArgs("-rpcauth")) {
        //Search for multi-user login/pass "rpcauth" from config
        std::vector<std::string> vFields;
        boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
        if (vFields.size() != 3) {
            //Incorrect formatting in config file
            continue;
        }

        std::string strName = vFields[0];
        if (!TimingResistantEqual(strName, strUser)) {
            continue;
        }

        std::string strSalt = vFields[1];
        std::string strHash = vFields[2];

        static const unsigned int KEY_SIZE = 32;
        unsigned char out[KEY_SIZE];

        CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.data()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.data()), strPass.size()).Finalize(out);
        std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
        std::string strHashFromPass = HexStr(hexvec);

        if (TimingResistantEqual(strHashFromPass, strHash)) {
            return true;
        }
    }
    return false;
}

static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
{
    if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
        return false;
    if (strAuth.substr(0, 6) != "Basic ")
        return false;
    std::string strUserPass64 = strAuth.substr(6);
    boost::trim(strUserPass64);
    std::string strUserPass = DecodeBase64(strUserPass64);

    if (strUserPass.find(':') != std::string::npos)
        strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));

    //Check if authorized under single-user field
    if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
        return true;
    }
    return multiUserAuthorized(strUserPass);
}
// SYSCOIN This is not a CORS check. Only check if OPTIONS are
// set in order to allow localhost to localhost communications
static bool checkPreflight(HTTPRequest* req)
{
    // https://www.w3.org/TR/cors/#resource-requests

    // 1. If the Origin header is not present terminate this set of steps.
    // The request is outside the scope of this specification.
    // Syscoin Keep origin so as not to have to set Access-Control-Allow-Origin
    // to *
    std::pair<bool, std::string> origin = req->GetHeader("origin");
    if (!origin.first) {
        return false;
    }

    // 2. If the value of the Origin header is not a case-sensitive match for
    // any of the values in list of origins do not set any additional headers
    // and terminate this set of steps.
    // Note: Always matching is acceptable since the list of origins can be
    // unbounded.
    // Syscoin We are only satisfying the OPTIONS request in this method in order to
    // allow localhost to localhost communications. If CORS is implemented origin
    // would be checked against an acceptable domain
    // if (origin.second != strRPCCORSDomain) {
    //     return false;
    // }

    if (req->GetRequestMethod() == HTTPRequest::OPTIONS) {
        // 6.2 Preflight Request
        // In response to a preflight request the resource indicates which
        // methods and headers (other than simple methods and simple
        // headers) it is willing to handle and whether it supports
        // credentials.
        // Resources must use the following set of steps to determine which
        // additional headers to use in the response:

        // 3. Let method be the value as result of parsing the
        // Access-Control-Request-Method header.
        // If there is no Access-Control-Request-Method header or if parsing
        // failed, do not set any additional headers and terminate this set
        // of steps. The request is outside the scope of this specification.
        std::pair<bool, std::string> method =
            req->GetHeader("access-control-request-method");
        if (!method.first) {
            return false;
        }

        // 4. Let header field-names be the values as result of parsing
        // the Access-Control-Request-Headers headers.
        // If there are no Access-Control-Request-Headers headers let header
        // field-names be the empty list.
        // If parsing failed do not set any additional headers and terminate
        // this set of steps. The request is outside the scope of this
        // specification.
        std::pair<bool, std::string> header_field_names =
            req->GetHeader("access-control-request-headers");

        // 5. If method is not a case-sensitive match for any of the
        // values in list of methods do not set any additional headers
        // and terminate this set of steps.
        // Note: Always matching is acceptable since the list of methods
        // can be unbounded.
        if (method.second != "POST") {
            return false;
        }

        // 6. If any of the header field-names is not a ASCII case-
        // insensitive match for any of the values in list of headers do not
        // set any additional headers and terminate this set of steps.
        // Note: Always matching is acceptable since the list of headers can
        // be unbounded.
        const std::string& list_of_headers = "authorization,content-type";

        // 7. If the resource supports credentials add a single
        // Access-Control-Allow-Origin header, with the value of the Origin
        // header as value, and add a single
        // Access-Control-Allow-Credentials header with the case-sensitive
        // string "true" as value.
        req->WriteHeader("Access-Control-Allow-Origin", origin.second);
        // Syscoin as we are only handling OPTIONS there is
        // no need to expose the response
        //req->WriteHeader("Access-Control-Allow-Credentials", "true");

        // 8. Optionally add a single Access-Control-Max-Age header with as
        // value the amount of seconds the user agent is allowed to cache
        // the result of the request.

        // 9. If method is a simple method this step may be skipped.
        // Add one or more Access-Control-Allow-Methods headers consisting
        // of (a subset of) the list of methods.
        // If a method is a simple method it does not need to be listed, but
        // this is not prohibited.
        // Note: Since the list of methods can be unbounded, simply
        // returning the method indicated by
        // Access-Control-Request-Method (if supported) can be enough.
        req->WriteHeader("Access-Control-Allow-Methods", method.second);

        // 10. If each of the header field-names is a simple header and none
        // is Content-Type, this step may be skipped.
        // Add one or more Access-Control-Allow-Headers headers consisting
        // of (a subset of) the list of headers.
        req->WriteHeader(
            "Access-Control-Allow-Headers",
            header_field_names.first ? header_field_names.second
                                        : list_of_headers);
        req->WriteReply(HTTP_OK);
        return true;
    }

    // 6.1 Simple Cross-Origin Request, Actual Request, and Redirects
    // In response to a simple cross-origin request or actual request the
    // resource indicates whether or not to share the response.
    // If the resource has been relocated, it indicates whether to share its
    // new URL.
    // Resources must use the following set of steps to determine which
    // additional headers to use in the response:

    // 3. If the resource supports credentials add a single
    // Access-Control-Allow-Origin header, with the value of the Origin
    // header as value, and add a single Access-Control-Allow-Credentials
    // header with the case-sensitive string "true" as value.
    req->WriteHeader("Access-Control-Allow-Origin", origin.second);
    // Syscoin as we are only handling OPTIONS there is
    // no need to expose the response
    // req->WriteHeader("Access-Control-Allow-Credentials", "true");

    // 4. If the list of exposed headers is not empty add one or more
    // Access-Control-Expose-Headers headers, with as values the header
    // field names given in the list of exposed headers.
    req->WriteHeader("Access-Control-Expose-Headers", "WWW-Authenticate");

    return false;
}
static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
{
    // SYSCOIN Check if this is a preflight request - if so set the necessary
    // headers to allow localhost to localhost communications
    if (checkPreflight(req)) {
        return true;
    }
    // JSONRPC handles only POST
    if (req->GetRequestMethod() != HTTPRequest::POST) {
        req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
        return false;
    }
    // Check authorization
    std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
    if (!authHeader.first) {
        req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
        req->WriteReply(HTTP_UNAUTHORIZED);
        return false;
    }

    JSONRPCRequest jreq;
    jreq.peerAddr = req->GetPeer().ToString();
    if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
        LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);

        /* Deter brute-forcing
           If this results in a DoS the user really
           shouldn't have their RPC port exposed. */
        UninterruptibleSleep(std::chrono::milliseconds{250});

        req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
        req->WriteReply(HTTP_UNAUTHORIZED);
        return false;
    }

    try {
        // Parse request
        UniValue valRequest;
        if (!valRequest.read(req->ReadBody()))
            throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");

        // Set the URI
        jreq.URI = req->GetURI();

        std::string strReply;
        bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
        if (!user_has_whitelist && g_rpc_whitelist_default) {
            LogPrintf("RPC User %s not allowed to call any methods\n", jreq.authUser);
            req->WriteReply(HTTP_FORBIDDEN);
            return false;

        // singleton request
        } else if (valRequest.isObject()) {
            jreq.parse(valRequest);
            if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
                LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, jreq.strMethod);
                req->WriteReply(HTTP_FORBIDDEN);
                return false;
            }
            UniValue result = tableRPC.execute(jreq);

            // Send reply
            strReply = JSONRPCReply(result, NullUniValue, jreq.id);

        // array of requests
        } else if (valRequest.isArray()) {
            if (user_has_whitelist) {
                for (unsigned int reqIdx = 0; reqIdx < valRequest.size(); reqIdx++) {
                    if (!valRequest[reqIdx].isObject()) {
                        throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
                    } else {
                        const UniValue& request = valRequest[reqIdx].get_obj();
                        // Parse method
                        std::string strMethod = find_value(request, "method").get_str();
                        if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
                            LogPrintf("RPC User %s not allowed to call method %s\n", jreq.authUser, strMethod);
                            req->WriteReply(HTTP_FORBIDDEN);
                            return false;
                        }
                    }
                }
            }
            strReply = JSONRPCExecBatch(jreq, valRequest.get_array());
        }
        else
            throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");

        req->WriteHeader("Content-Type", "application/json");
        req->WriteReply(HTTP_OK, strReply);
    } catch (const UniValue& objError) {
        JSONErrorReply(req, objError, jreq.id);
        return false;
    } catch (const std::exception& e) {
        JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
        return false;
    }
    return true;
}

static bool InitRPCAuthentication()
{
    if (gArgs.GetArg("-rpcpassword", "") == "")
    {
        LogPrintf("No rpcpassword set - using random cookie authentication.\n");
        if (!GenerateAuthCookie(&strRPCUserColonPass)) {
            uiInterface.ThreadSafeMessageBox(
                _("Error: A fatal internal error occurred, see debug.log for details").translated, // Same message as AbortNode
                "", CClientUIInterface::MSG_ERROR);
            return false;
        }
    } else {
        LogPrintf("Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share/rpcauth for rpcauth auth generation.\n");
        strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
    }
    if (gArgs.GetArg("-rpcauth","") != "")
    {
        LogPrintf("Using rpcauth authentication.\n");
    }

    g_rpc_whitelist_default = gArgs.GetBoolArg("-rpcwhitelistdefault", gArgs.IsArgSet("-rpcwhitelist"));
    for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
        auto pos = strRPCWhitelist.find(':');
        std::string strUser = strRPCWhitelist.substr(0, pos);
        bool intersect = g_rpc_whitelist.count(strUser);
        std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
        if (pos != std::string::npos) {
            std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
            std::set<std::string> new_whitelist;
            boost::split(new_whitelist, strWhitelist, boost::is_any_of(", "));
            if (intersect) {
                std::set<std::string> tmp_whitelist;
                std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
                       whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
                new_whitelist = std::move(tmp_whitelist);
            }
            whitelist = std::move(new_whitelist);
        }
    }

    return true;
}

bool StartHTTPRPC()
{
    LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
    if (!InitRPCAuthentication())
        return false;

    RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
    if (g_wallet_init_interface.HasWalletSupport()) {
        RegisterHTTPHandler("/wallet/", false, HTTPReq_JSONRPC);
    }
    struct event_base* eventBase = EventBase();
    assert(eventBase);
    httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(eventBase);
    RPCSetTimerInterface(httpRPCTimerInterface.get());
    return true;
}

void InterruptHTTPRPC()
{
    LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
}

void StopHTTPRPC()
{
    LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
    UnregisterHTTPHandler("/", true);
    if (g_wallet_init_interface.HasWalletSupport()) {
        UnregisterHTTPHandler("/wallet/", false);
    }
    if (httpRPCTimerInterface) {
        RPCUnsetTimerInterface(httpRPCTimerInterface.get());
        httpRPCTimerInterface.reset();
    }
}


text:
\documentclass{../../hw_class}
\begin{document}
\makeheader{HW \#4.3}{12/11/17}{``George Will: Another Case for Term Limits" -- George Wills}

\textbf{Thesis}: Grant-In-Aids are becoming overly large and overly inefficient. Former politician James Buckley believes this is because Congressmen are more concerned with getting re-elected than using funds well, thus proposing term limits to eliminate that concern and (hopefully) get politicians to focus on constituent services.

\begin{itemize}
\item 2010: $\$430K$ awarded to Plymouth, Conn. to widen sidewalks as part of anti-obesity campaign.
\begin{itemize}
\item Buckley Family: this is nonsense.
\item Author James Buckley's response: write a book that ``would substantially improve American governance."
\end{itemize}
\item James: senator, undersecretary of state, judge on U.S. Court of Appeals, D.C.
\begin{itemize}
\item He wants to end federal grants to state and local governments, which has financially exploded in recent years.
\item Buckley: Congress shouldn't be dealing with petty state grants -- that's the court's job. (By the Constitution)
\item Issue: Is the term `general welfare' (the point of issue) a valid point of restriction?
\end{itemize}
\item Grand-In-Aids are limited only by Congress's self control, and if recipients choose to reject aid.
\begin{itemize}
\item Issue 1: those aids account for 17\% of the federal budget.
\item Issue 2: those aids come with strings attached -- i.e. they're bound for certain purposes only.
\item Issue 3: states inevitably use aids incorrectly. (or at least inefficiently)
\end{itemize}
\item Big Issue: Politicians use Grant-In-Aids to buy voters come their next election. This segweys into Buckley's key advocacy: term limits.
\begin{itemize}
\item 19th Century -- most senators only served 1 - 2 terms.  Legends such as Henry Clay served merely three.
\item Buckley's belief: Senators will make use useful contributions when they have a specific term limit, as they won't be so held up on keeping their job.
\item Ben Sasse (R - Nebraska) wants to limit House and Senate members to two and four terms respectively.
\item Real Questions: will politicians be down to support limits on their terms? At least the state legislatures will.
\item Conclusion: term limits might be a way to fix Congress's careerism, a consequential barrier to actual concrete action on Congress's part,
\end{itemize}
\end{itemize}
\end{document}


text:
/*
 *
 */
package vnmr.apt;

import java.io.*;
//-->import java.nio.channels.Channels;
//-->import java.nio.channels.ClosedByInterruptException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.StringTokenizer;

import vnmr.util.Complex;
import vnmr.util.Fmt;

import static java.lang.Math.*;
//import static vnmr.apt.AptDefs.*;

/**
 * This class simulates Vnmr's swept tune function. Generates fake reflection
 * data and puts it in a FID file. Also, writes ptuneInfo in /vnmr/tmp with
 * extra "header" information for the FID. Also, reads ptuneCmds to adjust
 * sweep appropriately.
 */
public class Mtune {

    private static final Complex COMPLEX_ONE = new Complex(1, 0);
    private static final Complex COMPLEX_MINUS_ONE = new Complex(-1, 0);
    private static final Complex COMPLEX_ZERO = new Complex(0, 0);
    private static final Complex COMPLEX_50 = new Complex(50, 0);

    private static String sm_vnmrSystemDir = "/vnmr";
    private static String sm_fidpath;
    private static String sm_commandpath;
    private static String sm_infopath;
    private static String sm_cappath;
    private static String sm_motorpath;
    private static String sm_probeName = null;
    private static String sm_chanName = null;
    private static ProbeSimulator sm_probeSimulator = null;

    private static Random sm_random = new Random();

    private long m_start = 389962500; // One pad point at beginning
    private long m_stop = 410037500; // One pad point at end
    private int m_np = 804;
    private int m_power;        // Transmitter power
    private int m_gain;         // Receiver gain
    private int m_tchan;        // RF Channel

    protected static enum Termination {PROBE, OPEN, LOAD, SHORT};
    protected Termination m_termination = Termination.PROBE;
    protected static double m_offset_hz = 0;

    /** The thread that writes the data. */
    private DataWriter m_writer = null;

    /** The thread that reads the console */
    private ConsoleReader m_reader = null;

    private double m_prevTune = -1;/*DBG*/
    private double m_prevMatch = -1;/*DBG*/

    public static void main(String[] args) {
        setup(args);
    }

    // setup performs basic setup and returns an instance of Mtune
    // breaking this out facilitates unit testing.
    public static Mtune setup(String[] args) {
        int len = args.length;
        for (int i = 0; i < len; i++) {
            if (args[i].equalsIgnoreCase("-vnmrsystem") && i + 1 < len) {
                sm_vnmrSystemDir = args[++i];
            } else if (args[i].equalsIgnoreCase("-probe") && i + 1 < len) {
                sm_probeName = args[++i];
            } else if (args[i].equalsIgnoreCase("-chanFile") && i + 1 < len) {
                sm_chanName = args[++i];
            }
        }
        setGlobalPaths();
        return new Mtune();
    }

    private static void setGlobalPaths() {
        String basedir = sm_vnmrSystemDir + "/tmp";
        sm_fidpath = basedir + "/fid";
        sm_commandpath = basedir + "/ptuneCmds";
        sm_infopath = basedir + "/ptuneInfo";
        sm_cappath = basedir + "/ptuneCapPositions";
        sm_motorpath = basedir + "/ptuneMotorPositions";
        System.out.println("basedir=" + basedir);
    }

    public Mtune() {
        if (sm_probeName != null) {
            sm_probeSimulator = new ProbeSimulator(sm_probeName,
                                                   sm_vnmrSystemDir,
                                                   sm_chanName);
        }
        m_writer = new DataWriter();
        m_writer.start();
        m_reader = new ConsoleReader();
        m_reader.start();
    }

    public void quit(int ms) throws InterruptedException, IOException {
    	m_writer.quit(ms);
    	m_reader.quit(ms);
    }

    protected void readSweepParameters() {
        BufferedReader in = TuneUtilities.getReader(sm_commandpath);
        if (in != null) {
            // Got commands to read
            try {
                double center = (m_start + m_stop) / 2;
                double span = m_stop - m_start;
                String line;
                while ((line = in.readLine()) != null) {
                    try {
                        StringTokenizer toker = new StringTokenizer(line, " =");
                        String key = toker.nextToken();
                        if (key.equals("sfrq")) {
                            center = Double.parseDouble(toker.nextToken());
                            center *= 1e6; // sfrq is in MHz
                        } else if (key.equals("tunesw")) {
                            span = Double.parseDouble(toker.nextToken());
                        } else if (key.equals("np")) {
                            m_np = Integer.parseInt(toker.nextToken()) / 2;
                        } else if (key.equals("tupwr")) {
                            m_power = Integer.parseInt(toker.nextToken());
                        } else if (key.equals("gain")) {
                            m_gain = Integer.parseInt(toker.nextToken());
                        } else if (key.equals("tchan")) {
                            m_tchan = Integer.parseInt(toker.nextToken());
                        }
                    } catch (NoSuchElementException nsee) {
                    }
                }
                m_start = (long)(center - span / 2);
                m_stop = (long)(center + span / 2);
                Messages.postDebug("Mtune.readSweepParameters: start="
                                   + Fmt.f(6, m_start / 1e6)
                                   + ", stop=" + Fmt.f(6, m_stop / 1e6)
                                   + ", np=" + m_np
                                   + "\n                           "
                                   + "power=" + m_power
                                   + " gain=" + m_gain
                                   + " tchan=" + m_tchan
                                   );/*DBG*/
            } catch (IOException ioe) {
            }

            try {
                in.close();
            } catch (IOException ioe) {
            }

            // Delete command file after using it.
            new File(sm_commandpath).delete();

            try {
                Thread.sleep(2000); // Simulate slow sweep change
            } catch (InterruptedException ie) {
            }
        }
    }

    protected void writeHeaderInfo(long crc) {
        // Open a temp info file, write the info, and rename the file
        String tmppath = sm_infopath + "tmp";
        File tmpfile = new File(tmppath);
        PrintWriter out = null;
        try {
            out = new PrintWriter
                    (new BufferedWriter(new FileWriter(tmpfile)));
            //out.println("checksum " + crc);
            //out.println("gain 0");
            //out.println("power 10");
            out.println("fidpath " + sm_fidpath);
            //out.println("start " + m_start);
            //out.println("stop " + m_stop);
            //out.println("np " + m_np);
        } catch (IOException ioe) {
            Messages.postError("Mtune.writeHeaderInfo: Error writing "
                               + tmppath + ": " + ioe);
        } finally {
            out.close();
        }
        // Move the temp file to standard place
        File file = new File(sm_infopath);
        if (!tmpfile.renameTo(file)) {
            file.delete();
            if (!tmpfile.renameTo(file)) {
                Messages.postError("Unable to rename " + tmppath
                                   + " to " + sm_infopath);
            }
        }
    }

    /**
     * It may be possible for other processes to read this file while
     * it is being written, resulting in getting corrupted data. The
     * checksum may be used to detect this event.
     */
    protected long writeFidData() {
        long crc = 0;
        ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
        DataOutputStream outBuf = new DataOutputStream(outBytes);
        OutputStream out = null;

        try {
            // Write data to internal buffer
            // NB: Writing data to outBuf puts it in outBytes' buffer.
            writeFileHeader(outBuf, m_np);
            writeBlockHeader(outBuf);
            writeFidData(outBuf);

            // Calculate CRC of data file
            crc = TuneUtilities.getCrc32(outBytes.toByteArray());

            // Open the data file, and save the data
            out = new BufferedOutputStream(new FileOutputStream(sm_fidpath));
            outBytes.writeTo(out);
        } catch (IOException ioe) {
            Messages.postError("Error writing data to " + sm_fidpath
                               + ": " + ioe);
        } finally {
            try {
                out.close();
            } catch (Exception e) {}
        }

        return crc;
    }

    /**
     * @param out The DataOutputStream to write to.
     * @param npts The number of complex points in the FID.
     */
    private void writeFileHeader(DataOutputStream out, int npts)
        throws IOException {

        int nbheaders = 1;
        int nblocks = 1;
        int ntraces = 1;
        int np = npts * 2;      // Twice number of complex points
        int ebytes = 4;         // Bytes per number (element)
        int tbytes = np * ebytes; // Bytes per trace
        int bbytes = ntraces * tbytes + nbheaders * 28;
        short vers_id = 1;      // VNMR version number ???
        short status = 0x8;     // Data is Float format

        out.writeInt(nblocks);
        out.writeInt(ntraces);
        out.writeInt(np);
        out.writeInt(ebytes);
        out.writeInt(tbytes);
        out.writeInt(bbytes);
        out.writeShort(vers_id);
        out.writeShort(status);
        out.writeInt(nbheaders);
    }

    /**
     * @param out The DataOutputStream to write to.
     */
    private void writeBlockHeader(DataOutputStream out) throws IOException {

        short scale = 1;        // Not used
        short status = 0x8;     // Data is Float format
        short index = 0;
        short mode = 0;         // Not used
        int ctcount = 1;        // Number of FIDs summed in data
        float lpval = 0;        // Not used
        float rpval = 0;        // Not used
        float lvl = 0;          // Not used
        float tlt = 0;          // Not used

        out.writeShort(scale);
        out.writeShort(status);
        out.writeShort(index);
        out.writeShort(mode);
        out.writeInt(ctcount);
        out.writeFloat(lpval);
        out.writeFloat(rpval);
        out.writeFloat(lvl);
        out.writeFloat(tlt);
    }

    /**
     * Write a block of swept tune "FID" data.
     * @param out The DataOutputStream to write to.
     */
    /*
    private void writeFidData(DataOutputStream out) throws IOException {
        // Prelim version: Write 3*PI/2 worth of data w/ no resonance
        final double NOISE = 0.005;
        for (int i = 0; i < m_np; i++) {
            double theta = (3 * PI / 2) * ((double)i / (m_np - 1));
            double randy =  NOISE * sm_random.nextGaussian();
            out.writeFloat((float)(randy + cos(theta)));
            randy =  NOISE * sm_random.nextGaussian();
            out.writeFloat((float)(randy + sin(theta)));
        }
    }
    */

    /**
     * Write a block of swept tune "FID" data.
     * @param out The DataOutputStream to write to.
     */
    private void writeFidData(DataOutputStream out) throws IOException {
        final double NOISE = 0.005;

        // The gain factor in amplitude:
        double gain = pow(10, (m_power + m_gain + 50) / 20.0);
        double noise = 1e2 * NOISE / sqrt(gain); // NOISE=noise at gain=1e4
        CoilParams[] coilParams = null;
        Termination termination = m_termination;

        if (termination == Termination.PROBE){
            // Only need to calculate this if we are simulating the probe
            if (sm_probeName != null) {
                coilParams = getCurrentCoilParamsForProbe();
            } else {
                coilParams = getCurrentCoilParamsForDefaultProbe();
            }
        }

        // Calculate reflection for all freqs in range
        for (int i = 0; i < m_np; i++) {
            double f = m_start + ((double)i / (m_np - 1)) * (m_stop - m_start);
            Complex r = null;
            switch (termination) {
            default:
                // Normal case: use the simulated probe resonances
                r = calculateReflection(f, coilParams);
                break;
            case OPEN:
                r = COMPLEX_ONE;
                break;
            case SHORT:
                r = COMPLEX_MINUS_ONE;
                break;
            case LOAD:
                r = COMPLEX_ZERO;
                break;
            }

            // Increment the phase a bit w/ frequency
            // How fast to wind the reflection when far from real resonance:
            // probeDelay is round-trip time from port to coil (seconds)
            double probeDelay = 5.1e-9;
            double dtheta_dfreq = 2 * PI * probeDelay;
            double modulus = r.mod();
            double theta = r.arg();
            if (termination == Termination.PROBE) {
                theta -= dtheta_dfreq * f;
            }
            // NB: Put out FID data like Vnmr's, so sign of imag is
            // reversed as per NMR convention.
            theta = -theta;
            double x = modulus * cos(theta);
            double y = modulus * sin(theta);

            double randy = noise * sm_random.nextGaussian();
            out.writeFloat((float)((randy + x) * gain));
            randy = noise * sm_random.nextGaussian();
            out.writeFloat((float)((randy + y) * gain));
        }
    }

    /**
     * Calculate the coil parameters for the current motor positions
     * using the probe behavior specified in the ProTune channel files.
     * The motor positions are read from the "ptuneMotorPositions" file.
     * @return The coil parameters.
     */
    private CoilParams[] getCurrentCoilParamsForProbe() {
        // Read the motor positions
        int[] motorPositions = getAllMotorPositions();
        return sm_probeSimulator.getCoilParams(motorPositions);
    }

    /**
     * Calculate the coil parameters for the current capacitor positions
     * using the default probe.
     * The capacitor positions are read from the "ptuneCapPositions" file.
     * @return The coil parameters.
     */
    private CoilParams[] getCurrentCoilParamsForDefaultProbe() {
        double f0 = 400e6;      // Calc. nominal values for this frequency
        double w = 2 * PI * f0; // omega
        double lCoil = 100e-9;
        double rCoil = 0.5;
        double abs2Coil = rCoil * rCoil + w * w * lCoil * lCoil;
        double react = sqrt((50 * abs2Coil - 50 * 50 * rCoil) / rCoil);
        double cMatch = 1 / (react * w); // Nominal match capacitance
        double cTune = 1 / (w * w * lCoil); // Nominal tune capacitance

        // Check the motor positions and tweak the cap values
        double tune1 = cTune;
        double match1 = cMatch;

        CapPositions[] capPositions = getCapPositions();
        if (capPositions.length > 0) {
            tune1 *= (1 + capPositions[0].tune);
            match1 *= (1 + 5 * capPositions[0].match);
        }

        // Log values that change
        if (m_prevTune != tune1) {
            m_prevTune = tune1;
            System.out.println("tune = " + Fmt.g(5, tune1 * 1e12) + " pF");
        }
        if (m_prevMatch != match1) {
            m_prevMatch = match1;
            System.out.println("match = " + Fmt.g(5, match1 * 1e12) + " pF");
        }

        CoilParams[] cpars = {new CoilParams(lCoil, rCoil, tune1, match1)};
        return cpars;
    }

    /**
     * Calculates the tune and match capacitances needed to tune our model
     * coil to the given frequency with given coil inductance and resistence.
     * This is an approximate calculation, just to get the cap values in
     * the ballpark. The match is fairly good; the frequency can be off by
     * more than 10 MHz.
     * @param freq The frequency to tune to (Hz).
     * @param coilParams The coil parameters, with only rCoil and lCoil set.
     * @return The same CoilParams object, with cTune and cMatch set.
     * respectively (F).
     */
    public static CoilParams calculateNominalCaps(double freq,
                                                CoilParams coilParams) {
        double rCoil = coilParams.rCoil;
        double lCoil = coilParams.lCoil;
        double w = 2 * PI * freq; // omega
        double abs2Coil = rCoil * rCoil + w * w * lCoil * lCoil;
        double react = sqrt((50 * abs2Coil - 50 * 50 * rCoil) / rCoil);
        coilParams.cMatch = 1 / (react * w); // Nominal match capacitance
        coilParams.cTune = 1 / (w * w * lCoil); // Nominal tune capacitance
        return coilParams;
    }

    /**
     * Calculates the complex reflection for the given resonant coil
     * at the given frequency.
     * @param freq The frequency to calculate the reflection for (Hz).
     * @param coilParams The coil parameters to use.
     * @return The complex reflection.
     */
    public static Complex calculateReflection(double freq,
                                              CoilParams coilParams) {
        CoilParams[] paramsArray = {coilParams};
        return calculateReflection(freq, paramsArray);
    }

    /**
     * Calculates the complex reflection for the given resonant coils
     * at the given frequency.
     * Each coil gives a different resonance.
     * @param freq The frequency to calculate the reflection for (Hz).
     * @param coilParams The parameters of all the coils of interest.
     * @return The complex reflection.
     */
    public static Complex calculateReflection(double freq,
                                              CoilParams[] coilParams) {
        freq -= m_offset_hz;
        Complex r = COMPLEX_ONE;
        for (CoilParams params : coilParams) {
            double w = 2 * PI * freq; // omega; circular freq
            Complex zMatch = new Complex(0, -1 / (w * params.cMatch));
            Complex zTune = new Complex(0, -1 / (w * params.cTune));
            Complex zCoil = new Complex(params.rCoil, w * params.lCoil);
            // z = zMatch + 1 / (1/zTune + 1/zCoil)
            Complex z = zMatch.plus((zTune.inv().plus(zCoil.inv())).inv());
            Complex z0 = COMPLEX_50; // 50 Ohm load
            // reflection = (z - z0) / (z + z0)
            r = r.times(z.minus(z0).div(z.plus(z0)));
        }
        return r;
    }

    /**
     * Get all the current motor positions from a file.
     * These positions are corrected to the virtual capacitor positions,
     * which include simulated backlash.
     * @return The list of positions, indexed by gmi.
     */
    private int[] getAllMotorPositions() {
        ArrayList<Integer> motorPositions = new ArrayList<Integer>();

        BufferedReader in = TuneUtilities.getReader(sm_motorpath);
        if (in == null) {
            Messages.postError("Failed to get motor position file: "
                               + sm_motorpath);
        } else {
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    try {
                        int position = Integer.parseInt(line);
                        motorPositions.add(position);
                    } catch (NumberFormatException nfe) {
                        motorPositions.add(0);
                    }
                }
            } catch (IOException ioe) {
            } finally {
                try {
                    in.close();
                } catch (Exception e) {}
            }
        }
        int[] rtn = new int[motorPositions.size()];
        for (int i = 0; i < motorPositions.size(); i++) {
            rtn[i] = motorPositions.get(i);
        }
        return rtn;
    }

    /**
     * This reads "capacitor positions" from a file.
     * (Legacy support for simulating a single, hard-coded resonance.)
     * @return The array of cap positions.
     */
    private CapPositions[] getCapPositions() {
        ArrayList<CapPositions> capPositions = new ArrayList<CapPositions>();

        BufferedReader in = TuneUtilities.getReader(sm_cappath);
        if (in == null) {
            Messages.postError("Failed to get cap position file: " + sm_cappath);
        } else {
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    //Messages.postDebug("Mtune: getCapPositions line=" + line);
                    try {
                        StringTokenizer toker = new StringTokenizer(line);
                        if (toker.countTokens() == 3) {
                            String key = toker.nextToken();
                            int idx = Integer.parseInt(toker.nextToken());
                            double val = Double.parseDouble(toker.nextToken());

                            // Make sure we have a place to put the value
                            while (idx >= capPositions.size()) {
                                capPositions.add(null);
                            }
                            CapPositions thesePositions = capPositions.get(idx);
                            if (thesePositions == null) {
                                thesePositions = new CapPositions();
                                capPositions.set(idx, thesePositions);
                            }

                            // Set the appropriate value
                            if (key.equals("tune")) {
                                thesePositions.tune = val;
                            } else if (key.equals("match")) {
                                thesePositions.match = val;
                            }
                        }
                    } catch (NoSuchElementException nsee) {
                        Messages.postError(nsee.toString());
                    }
                }
            } catch (IOException ioe) {
            } finally {
                try {
                    in.close();
                } catch (Exception e) {}
            }
        }
        //rtn[0].match = -0.2;
        //rtn[0].tune = -0.04;
        return capPositions.toArray(new CapPositions[0]);
    }

    /**
     * Class to hold the current values of the capacitor positions
     * in the probe.
     * (Legacy support for simulating a single, hard-coded resonance.)
     */
    static public class CapPositions {
        /**
         * Value of the tune capacitor as a fractional offset from the
         * nominal value.
         * Capacitance is (nominal * (1 + tune)) farads.
         */
        public double tune = 0;

        /**
         * Value of the match capacitor as a fractional offset from the
         * nominal value.
         * Capacitance is (nominal * (1 + match)) farads.
         */
        public double match = 0;

        /**
         * Reset the capacitor positions to their nominal values.
         */
        public void clear() {
            tune = 0;
            match = 0;
        }
    }

    /**
     * Thread to write the data after every "sweep".
     */
    public class DataWriter extends Thread {

        private boolean mm_quit = false;

        public DataWriter() {
            Messages.postDebug("Mtune.DataWriter created");
        }

        public void quit(int ms) throws InterruptedException {
            quit();
            interrupt();
            join(ms);
        }

        public void quit() {
            mm_quit = true;
        }

        public void run() {
            Messages.postDebug("Mtune.DataWriter running");
            setName("Mtune.DataWriter");

            while (!mm_quit) {
                readSweepParameters();
                long crc = writeFidData();
                writeHeaderInfo(crc);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ie) {
                }
            }
        }
    }

    /**
     * Thread to read text input from the terminal.
     * Currently used only to indicate whether to simulate the probe,
     * or a cable terminated with open/load/short.
     */
    public class ConsoleReader extends Thread {
    	private boolean mm_forceQuit = false;
        private boolean mm_quit = false;
        private BufferedReader mm_reader;

        public ConsoleReader() {
            mm_reader = new BufferedReader(new InputStreamReader(System.in));
            Messages.postDebug("Mtune.ConsoleReader created");
        }

        public void quit(int ms) throws InterruptedException, IOException {
	    mm_forceQuit = true;
            quit();
            interrupt();
            join(ms);
        }

        public void quit() {
            mm_quit = true;
        }

        public void run() {
            Messages.postDebug("Mtune.ConsoleReader running");
            setName("Mtune.ConsoleReader");
            while (!mm_quit) {
                try {
                    String line = mm_reader.readLine();
                    if (line == null || "quit".equalsIgnoreCase(line)) {
                        quit();
                    } else {
                        line = line.trim();
                        try {
                            m_offset_hz = 1e6 * Double.parseDouble(line);
                        } catch (NumberFormatException nfe) {
                        }
                        if ("open".equalsIgnoreCase(line)) {
                            m_termination = Termination.OPEN;
                        } else if ("load".equalsIgnoreCase(line)) {
                            m_termination = Termination.LOAD;
                        } else if ("short".equalsIgnoreCase(line)) {
                            m_termination = Termination.SHORT;
                        } else {
                            m_termination = Termination.PROBE;
                        }
                        if (m_offset_hz != 0) {
                            Messages.postDebug("Dip shift="
                                               + Fmt.f(2, m_offset_hz / 1e6)
                                               + " MHz");
                        }
                        Messages.postDebug("Termination=" + m_termination);
                    }
                } catch (IOException e) {
                    // ClosedByInterruptException occurs during shutdown
                    if (!mm_forceQuit)
                        e.printStackTrace();
                    quit();
                }
            }
        }
    }

    /**
     * Container class for the values used to calculate the reflection due
     * to a resonance.
     */
    static class CoilParams implements Cloneable {
        /** Coil inductance. */
        public double lCoil;
        /** Coil resistance. */
        public double rCoil;
        /** Tune capacitor value. */
        public double cTune;
        /** Match capacitor value. */
        public double cMatch;

        public CoilParams(double l, double r, double tune, double match) {
            lCoil = l;
            rCoil = r;
            cTune = tune;
            cMatch = match;
        }

        public CoilParams clone() {
            return new CoilParams(lCoil, rCoil, cTune, cMatch);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/Users/Mike/Documents/Programing%20Junk/Java/TestRandomizer/src/testrandomizer/Question.java</file>
            <file>file:/C:/Users/Mike/Documents/Programing%20Junk/Java/TestRandomizer/src/testrandomizer/TestSection.java</file>
            <file>file:/C:/Users/Mike/Documents/Programing%20Junk/Java/TestRandomizer/src/testrandomizer/TestRandObj.java</file>
            <file>file:/C:/Users/Mike/Documents/Programing%20Junk/Java/TestRandomizer/src/testrandomizer/TestRandFrame.java</file>
        </group>
    </open-files>
</project-private>


text:
var layer = L.tileLayer('https://a.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '© OpenStreetMap contributors'
});

$(function() {
    var element = $('#map');

    var iconSize = parseInt(element.attr('data-icon-size'), 10) || 16;
    var icon = L.icon({
        iconUrl: element.attr('data-icon-src'),
        iconSize: [iconSize, iconSize],
        shadowSize: [0, 0],
        iconAnchor: [iconSize / 2, iconSize / 2],
        popupAnchor: [0, 0]
    });

    var zoom = element.attr('data-zoom') || 7;
    var lat = element.attr('data-lat') || 49.8;
    var lng = element.attr('data-lng') || 15.55;

    var map = L.map('map', {'scrollWheelZoom': false})
        .setView([lat, lng], zoom)
        .addLayer(layer);

    var dataUrl = element.attr('data-src');
    $.getJSON(dataUrl, function(data) {
        L.geoJson(data, {
            pointToLayer: function (feature, coordinates) {
                return L.marker(coordinates, {icon: icon});
            },
            onEachFeature: function (feature, marker) {
                if (feature.properties) {
                    text = '
' + feature.properties.name + '
'
                    marker.bindPopup(text);
                }
            }
        }).addTo(map);
    });
});


text:
typedef void (^CSAzureUploadSessionProgressBlock) (int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);

@interface CSAzureUploadRequest : NSObject

@property (nonatomic,strong) NSString *url;
@property (nonatomic,strong) NSData *body;
@property (nonatomic,strong) NSString *mime;
@property (nonatomic,strong) NSString *disposition;
@property (nonatomic,copy) CSAzureUploadSessionProgressBlock progressHandler;

-(NSURLRequest *)buildUrlRequest;

@end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class BuyerBaseController extends MY_Controller{

  const THEMEDIR = "buyer/themes/";

  public $alias = 'home';

  function __construct(){
    parent::__construct();
    $this->load->library('doctrine');
    $this->em = $this->doctrine->em;
    $this->load->model('site');
  }

  public function loadView($page, $data = array()){
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      // header('Content-Type: application/json');
      // echo json_encode($data);
    }else{
      $domain = $this->parseDomain();
      $SITE = $this->site->getOne($domain);
      if(!$SITE){
        $this->load->view('404');
      }

      $themeDir = self::THEMEDIR . $SITE->theme->directory . "/";

      $this->buildScripts($themeDir);
      die();

      $masterPage =  $themeDir . "layout";

      $_data = $data;

      $_data['alias'] = $this->alias;

      $_data['title'] = isset($data['title'])?$data['title']:$SITE->theme->default_title;

      $_data['page'] = $themeDir . "pages/" . $page;

      $this->load->view($masterPage, $_data);
    }
    $this->em->getConnection()->close();
  }
  public function parseDomain(){
    return $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'];
  }
  public function buildScripts($themeDir){
    print_r(parse_ini_file(APPPATH."views/" . $themeDir . "scripts.php"));
    // $scripts =$this->load->view($themeDir . "scripts");
  }
  public function buildStyles($themeDir){

  }
  public function _404(){
    $this->load->view('404');
  }
}