text:
package tsg;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Map.Entry;

import kernels.NodeSetCollector;
import kernels.NodeSetCollectorMUB;
import kernels.NodeSetCollectorSimple;
import kernels.NodeSetCollectorStandard;
import backoff.BackoffModel_DivHistory;
import backoff.BackoffModel_Eisner;
import settings.Parameters;
import symbols.Symbol;
import symbols.SymbolList;
import symbols.SymbolString;
import tesniere.Box;
import tesniere.Conversion;
import tesniere.EvalTDS;
import tsg.DOP_IO_Log.TSNodeLabel_Double;
import tsg.corpora.Wsj;
import tsg.parseEval.EvalC;
import util.PrintProgressStatic;
import util.Utility;
import util.file.FileUtil;

public class DOP1_reranker {

	public static ArrayList<TSNodeLabelIndex> nextNBest(int nBest, Scanner s) throws Exception {
		ArrayList<TSNodeLabelIndex> result = new ArrayList<TSNodeLabelIndex>(nBest);
		int count = 0;
		while(s.hasNextLine() && count<nBest) {
			String line = s.nextLine();
			if (line.equals("")) return result;
			TSNodeLabelIndex tree = new TSNodeLabelIndex(line);
			result.add(tree);
			count++;
		}
		while(s.hasNextLine() && !s.nextLine().equals("")) {};
		return result;
	}

	public static HashMap<TSNodeLabel, Double> fragmentTableFreq;
	public static Hashtable<Label, double[]> rootTableFreq;

	public static void readFragmentsFile(File fragmentFile) throws Exception {
		System.out.println("Reading fragments from: " + fragmentFile.toString());
		fragmentTableFreq = new HashMap<TSNodeLabel, Double>();
		Scanner scan = FileUtil.getScanner(fragmentFile);
		int countFragments = 0;
		while(scan.hasNextLine()) {
			String line = scan.nextLine();
			if (line.equals("")) continue;
			countFragments++;
			String[] fragmentFreq = line.split("\t");
			String fragmentString = fragmentFreq[0];
			Double freq = Double.parseDouble(fragmentFreq[1]);
			fragmentString = fragmentString.replaceAll("\\\\", "");
			TSNodeLabel fragment= new TSNodeLabel(fragmentString, false);
			fragmentTableFreq.put(fragment, freq);
		}
		System.out.println("Read " + countFragments + " fragments");
		scan.close();
	}

	public static void addCFGfragments(File trainingCorpus) throws Exception {
		ArrayList<TSNodeLabel> corpus = TSNodeLabel.getTreebank(trainingCorpus);
		Hashtable<String, int[]> ruleTable = new Hashtable<String, int[]>();
		for(TSNodeLabel t : corpus) {
			t.addTop();
			ArrayList<TSNodeLabel> nodes = t.collectAllNodes();
			for(TSNodeLabel n : nodes) {
				if (n.isLexical) continue;
				String rule = n.cfgRule();
				Utility.increaseInTableInt(ruleTable, rule);
			}
		}
		System.out.println("Read " + ruleTable.size() + " CFG fragments");
		int kept = 0;
		for(Entry<String, int[]> e : ruleTable.entrySet()) {
			TSNodeLabel ruleFragment = new TSNodeLabel("( " + e.getKey() + ")", false);
			if (fragmentTableFreq.containsKey(ruleFragment)) continue;
			double freq = e.getValue()[0];
			fragmentTableFreq.put(ruleFragment,freq);
			kept++;
		}
		System.out.println("Added " + kept + " CFG fragments");

	}

	public static void getRootFreq() {
		rootTableFreq = new Hashtable<Label, double[]>();
		for(Entry<TSNodeLabel, Double> e : fragmentTableFreq.entrySet()) {
			Label rootLabel = e.getKey().label;
			double freq = e.getValue();
			Utility.increaseInTableDoubleArray(rootTableFreq, rootLabel, freq);
		}
		System.out.println("Built root freq. table: " + rootTableFreq.size() + " entries.");
	}

	public static boolean allowUnknownCFG = true;

	private static double getParseTreeProb(TSNodeLabelIndex t) {
		NodeSetCollectorSimple setCollector = new NodeSetCollectorSimple();
		HashMap<BitSet, Double> bitSetFreqTable = new HashMap<BitSet, Double>();
		for(Entry<TSNodeLabel, Double> e : fragmentTableFreq.entrySet()) {
			getCFGSetCoveringFragment(t, e.getKey(), e.getValue(), setCollector, bitSetFreqTable);
		}
		BitSet union = setCollector.uniteSubGraphs();
		ArrayList<TSNodeLabel> nonLexicalNodes = t.collectNonLexicalNodes();
		BitSet preLexNonCovered = new BitSet();
		//int lexNonCovered = 0;
		if (allowUnknownCFG) {
			for(TSNodeLabel nlN : nonLexicalNodes) {
				TSNodeLabelIndex nlNI = (TSNodeLabelIndex)nlN;
				int index = nlNI.index;
				if (!union.get(index)) {
					BitSet set = new BitSet();
					set.set(index);
					setCollector.add(set);
					bitSetFreqTable.put(set, 1d);
				}
			}
		}
		else {
			for(TSNodeLabel nlN : nonLexicalNodes) {
				TSNodeLabelIndex nlNI = (TSNodeLabelIndex)nlN;
				int index = nlNI.index;
				if (nlNI.isPreLexical()) {
					if (!union.get(index)) {
						//lexNonCovered++;
						preLexNonCovered.set(index);
					}
					continue;
				}
				if (!union.get(index)) return -1;
			}
		}
		TSNodeLabelStructure tStructure = new TSNodeLabelStructure(t);
		ProbChart pc = new ProbChart(setCollector, tStructure, preLexNonCovered, bitSetFreqTable);
		return pc.getProb();
	}

	private static void getCFGSetCoveringFragment(TSNodeLabelIndex t, TSNodeLabel fragment,
			double fragmentFreq, NodeSetCollector setCollector,
			HashMap<BitSet,Double> bitSetFreqLogTable) {
		if (t.isLexical) return;
		if (t.sameLabel(fragment)) {
			BitSet set = new BitSet();
			if (getCFGSetCoveringFragmentNonRecursive(t, fragment, set) && !set.isEmpty()) {
				setCollector.add(set);
				bitSetFreqLogTable.put(set, fragmentFreq);
			}
		}
		for(TSNodeLabel d : t.daughters) {
			TSNodeLabelIndex di = (TSNodeLabelIndex)d;
			getCFGSetCoveringFragment(di, fragment, fragmentFreq, setCollector, bitSetFreqLogTable);
		}
	}

	private static boolean getCFGSetCoveringFragmentNonRecursive(TSNodeLabelIndex t,
			TSNodeLabel fragment, BitSet set) {
		if  (t.isLexical || fragment.isTerminal()) return true;
		if (!t.sameDaughtersLabel(fragment)) return false;
		int prole = t.prole();
		for(int i=0; i<prole; i++) {
			TSNodeLabel thisDaughter = t.daughters[i];
			TSNodeLabel otherDaughter = fragment.daughters[i];
			TSNodeLabelIndex thisDaughterIndex = (TSNodeLabelIndex) thisDaughter;
			if (!getCFGSetCoveringFragmentNonRecursive(thisDaughterIndex, otherDaughter, set)) return false;
		}
		set.set(t.index);
		return true;
	}

/*	private static void getCFGSetCoveringFragment(TSNodeLabelIndex t, TSNodeLabel fragment,
			Integer fragmentFreq, NodeSetCollector setCollector, HashMap<BitSet,Integer> bitSetFreqTable) {
		if (t.isLexical) return;
		if (t.sameLabel(fragment)) {
			BitSet set = new BitSet();
			if (getCFGSetCoveringFragmentNonRecursive(t, fragment, set) && !set.isEmpty()) {
				setCollector.add(set);
				bitSetFreqTable.put(set, fragmentFreq);
			}
		}
		for(TSNodeLabel d : t.daughters) {
			TSNodeLabelIndex di = (TSNodeLabelIndex)d;
			getCFGSetCoveringFragment(di, fragment, fragmentFreq, setCollector, bitSetFreqTable);
		}
	}

	private static boolean getCFGSetCoveringFragmentNonRecursive(TSNodeLabelIndex t, TSNodeLabel fragment, BitSet set) {
		if  (t.isLexical || fragment.isTerminal()) return true;
		if (!t.sameDaughterLabel(fragment)) return false;
		int prole = t.prole();
		for(int i=0; i<prole; i++) {
			TSNodeLabel thisDaughter = t.daughters[i];
			TSNodeLabel otherDaughter = fragment.daughters[i];
			//if (!thisDaughter.sameLabel(otherDaughter)) return;
			TSNodeLabelIndex thisDaughterIndex = (TSNodeLabelIndex) thisDaughter;
			if (!getCFGSetCoveringFragmentNonRecursive(thisDaughterIndex, otherDaughter, set)) return false;
		}
		set.set(t.index);
		return true;
	}
*/

	static class ProbChart {

		NodeSetCollectorSimple setCollector;
		TSNodeLabelStructure t;
		int totalNodes;
		BitSet preLexNonCovered;
		double[] probNodes;
		NodeSetCollectorSimple[] nodesCollector;
		HashMap<BitSet, Double> bitSetFreqTable;

		public ProbChart(NodeSetCollectorSimple setCollector, TSNodeLabelStructure t,
				BitSet preLexNonCovered, HashMap<BitSet, Double> bitSetFreqTable) {
			this.setCollector = setCollector;
			this.t = t;
			this.preLexNonCovered = preLexNonCovered;
			totalNodes = t.length;
			probNodes = new double[totalNodes];
			Arrays.fill(probNodes, -1d);
			nodesCollector = new NodeSetCollectorSimple[totalNodes];
			this.bitSetFreqTable = bitSetFreqTable;
		}

		public double getProb() {
			// distribute the subtrees in the parent node index
			for(BitSet bs : setCollector.bitSetSet) {
				int firstIndex = bs.nextSetBit(0);
				if (nodesCollector[firstIndex]==null) {
					nodesCollector[firstIndex] = new NodeSetCollectorSimple();
				}
				nodesCollector[firstIndex].add(bs);
			}
			return getProbRecursive(0);
		}

		private double getProbRecursive(int index) {
			if (probNodes[index]!=-1) return probNodes[index];
			NodeSetCollectorSimple setCollector = nodesCollector[index];
			if (setCollector==null) return probNodes[index] = 0;
			TSNodeLabelIndex root = t.structure[index];
			double rootFreq = rootTableFreq.get(root.label)[0];
			double prob = 0;
			for(BitSet initialSubTree : setCollector.bitSetSet) {
				ArrayList<Integer> subSitesIndexes = new ArrayList<Integer>();
				collectSubSites(root, initialSubTree, subSitesIndexes);
				double partialProb = 1d;
				for(int subSiteIndex : subSitesIndexes) {
					double subSiteProb = getProbRecursive(subSiteIndex);
					if (subSiteProb==0) {
						partialProb=0;
						break;
					}
					partialProb *= subSiteProb;
				}
				if (partialProb==0) continue;
				double initialSubTreeFreq = bitSetFreqTable.get(initialSubTree);
				partialProb *= (double) initialSubTreeFreq / rootFreq;
				prob += partialProb;
			}
			return probNodes[index] = prob;
		}

		private void collectSubSites(TSNodeLabelIndex root, BitSet initialSubTree,
				ArrayList<Integer> subSitesIndexes) {
			for(TSNodeLabel d : root.daughters) {
				if (d.isLexical) return;
				TSNodeLabelIndex di = (TSNodeLabelIndex)d;
				int index = di.index;
				if (preLexNonCovered.get(index)) continue;
				if (!initialSubTree.get(index)) subSitesIndexes.add(index);
				else collectSubSites(di, initialSubTree, subSitesIndexes);
			}
		}
	}

	public static void rerank(int nBest) throws Exception {

		String fragmentFileDir = Parameters.resultsPath +
			"TSG/TSGkernels/Wsj/KenelFragments/SemTagOff_Top/all/correctCount/";
		File fragmentFile = new File(fragmentFileDir + "fragments_MUB_freq_all_correctCount.txt");
		readFragmentsFile(fragmentFile);

		File trainingCorpus = new File(Wsj.WsjOriginalCleanedSemTagsOff + "wsj-02-21.mrg");
		addCFGfragments(trainingCorpus);

		getRootFreq();

		String baseDir = Parameters.resultsPath + "TSG/DOP1_Reranker/";
		File nBestFile = new File(baseDir + "wsj-22_chiarniak_parsed1000_cleaned.mrg");
		Scanner nBestScanner = FileUtil.getScanner(nBestFile);

		File goldFile = new File(baseDir + "wsj-22_gold.mrg");
		ArrayList<TSNodeLabel> goldTreebank = TSNodeLabel.getTreebank(goldFile);

		File rerankedFile = new File(baseDir + "wsj-22_reranked_" + nBest + "best.mrg");
		File rerankedFileEvalF = new File(baseDir + "wsj-22_reranked_" + nBest + "best.evalF");
		PrintWriter pw = FileUtil.getPrintWriter(rerankedFile);

		int size = goldTreebank.size();
		int totalActivelyReranked = 0;
		int totalNonCovered = 0;

		System.out.println("Rerankin n = " + nBest);
		PrintProgressStatic.start("Sentence ");

		for(int i=0; i<size; i++) {

			PrintProgressStatic.next();
			ArrayList<TSNodeLabelIndex> nBestTrees = nextNBest(nBest, nBestScanner);
			Iterator<TSNodeLabelIndex> iter = nBestTrees.iterator();
			TSNodeLabelIndex bestReranked = iter.next();
			double bestProb = getParseTreeProb(bestReranked);

			boolean reranked = false;
			while(iter.hasNext()) {
				TSNodeLabelIndex t = iter.next();
				double prob = getParseTreeProb(t);
				if (prob>bestProb) {
					bestProb = prob;
					bestReranked = t;
					reranked = true;
				}
			}

			if (reranked) totalActivelyReranked++;
			if (bestProb == -1) {
				//System.err.println((i+1) + ": no coverage, choosing 1-best.");
				totalNonCovered++;
			}
			//else System.err.println((i+1) + ": covered!");
			pw.println(bestReranked.toString());
		}

		pw.close();
		PrintProgressStatic.end();
		float[] rerankedFScore = EvalC.staticEvalF(goldFile, rerankedFile, rerankedFileEvalF, true);
		System.out.println("Actively reranked: " + totalActivelyReranked);
		System.out.println("Non covered: " + totalNonCovered);
		System.out.println("Reranked Recall Precision FScore: " + Arrays.toString(rerankedFScore));
		//new EvalTDS(rerankedFile, goldFile).compareStructures();
	}

	public static void rerankEM(int nBest, int cycle) throws Exception {

		String baseDir = Parameters.resultsPath + "TSG/DOP_IO/"; //"TSG/DOP_IO_SMALL/";
		File fragmentFile = new File(baseDir + "kernelsMUB_CFG_freq_EM_cycle_" + cycle + ".txt");
		readFragmentsFile(fragmentFile);

		getRootFreq();

		File nBestFile = new File(baseDir + "wsj-22_chiarniak_parsed1000_cleaned.mrg");
		Scanner nBestScanner = FileUtil.getScanner(nBestFile);

		File goldFile = new File(baseDir + "wsj-22_gold.mrg");
		ArrayList<TSNodeLabel> goldTreebank = TSNodeLabel.getTreebank(goldFile);

		File rerankedFile = new File(baseDir + "wsj-22_reranked_" + nBest + "best_cycle_" + cycle + ".mrg");
		File rerankedFileEvalF = new File(baseDir + "wsj-22_reranked_" + nBest + "best_cycle_" + cycle + ".evalF");
		PrintWriter pw = FileUtil.getPrintWriter(rerankedFile);

		int size = goldTreebank.size();
		int totalActivelyReranked = 0;
		int totalNonCovered = 0;

		System.out.println("Rerankin n = " + nBest);
		PrintProgressStatic.start("Sentence ");

		for(int i=0; i<size; i++) {

			PrintProgressStatic.next();
			ArrayList<TSNodeLabelIndex> nBestTrees = nextNBest(nBest, nBestScanner);
			Iterator<TSNodeLabelIndex> iter = nBestTrees.iterator();
			TSNodeLabelIndex bestReranked = iter.next();
			double bestProb = getParseTreeProb(bestReranked);

			boolean reranked = false;
			while(iter.hasNext()) {
				TSNodeLabelIndex t = iter.next();
				double prob = getParseTreeProb(t);
				if (prob>bestProb) {
					bestProb = prob;
					bestReranked = t;
					reranked = true;
				}
			}

			if (reranked) totalActivelyReranked++;
			if (bestProb == -1) {
				//System.err.println((i+1) + ": no coverage, choosing 1-best.");
				totalNonCovered++;
			}
			//else System.err.println((i+1) + ": covered!");
			pw.println(bestReranked.toString());
		}

		pw.close();
		PrintProgressStatic.end();
		float[] rerankedFScore = EvalC.staticEvalF(goldFile, rerankedFile, rerankedFileEvalF, true);
		System.out.println("Actively reranked: " + totalActivelyReranked);
		System.out.println("Non covered: " + totalNonCovered);
		System.out.println("Reranked Recall Precision FScore: " + Arrays.toString(rerankedFScore));
		//new EvalTDS(rerankedFile, goldFile).compareStructures();
	}

	public static void main1(String[] args) throws Exception {
		//int[] nBest = new int[]{1,5,10,100,500,1000};
		int[] nBest = new int[]{5,10,100};
		for(int n : nBest) {
			rerank(n);
		}
	}

	public static void main(String[] args) throws Exception {
		allowUnknownCFG = true;
		//int[] nBest = new int[]{1,5,10,100,500,1000};
		//for(int c = 13; c<=30; c++) {
		//	rerankEM(5,c);
		//}
		//rerankEM(5,1);
		rerankEM(10,1);
		rerankEM(100,1);
	}

}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Issues</title>
    <link rel="stylesheet" href="./css/style.css">
  </head>
  <body>
    <webview id="webview" src="http://waffle.io" allowpopups></webview>
    <div id="blur"> </div>
    <webview id="popup" src="" allowpopups></webview>

    <script src="./js/index.js"> </script>
  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Brioche Scarf: 1/1 - 1/14"
modified:
categories: knitting
excerpt:
tags: []
image:
  feature: knitting/january-hero1.jpg
date: 2015-01-15T22:18:20-07:00
---

It's been 14 days since the beginning of 2015, which means I'm 14 rows into my weather scarf.

I wanted to share some progress photos and some times


text:
layout: post
title: RoughtDraft- Red Rising + Christmas Ale
excerpt: "Lone reading Red Rising and drinking?  We suggest Great Lakes Christmas Ale."
date: 2015-01-11T10:29:55-04:00
modified: 2015-01-11T10:29:55-04:00
categories: brews
tags: [lonereads,reading,books,science fiction,red rising,pierce brown,beers,great lakes, christmas ale]
image:
  feature: brew-banner.png
comments: true
share: true
---

*Red Rising* was the Goodreads Choice Awards 2014 selection for best Debut
Goodreads Author.  While reading the first half this week, we enjoyed a beer or two.

### RoughDraught Review

This week we paired a holiday brew with the first half of Red Rising.

#### Great Lakes Brewing Company - Christmas Ale

Great Lakes Christmas Ale, like *Red Rising*, is an enjoyable selection from
the best of 2014.  It's got a cinnamony gingerbready flavor, and this year's batch
is solid.  It has an overall score of 93 on its [ratebeer review](http://www.ratebeer.com/beer/great-lakes-christmas-ale/4492/).  (Why do we like ratebeer reviews over beeradvocate?
Because we did a common sense check on the scores given by [ratebeer](http://www.ratebeer.com/beer/pabst-blue-ribbon/734/) vs [Beeradvocate](http://www.beeradvocate.com/beer/profile/447/1331/),
and ratebeer makes more sense, that's why.)

<figure class='half' >
	<img src="/images/xmas-ale.JPG" alt="image">
	<figcaption>Book + beer, a refreshing pairing. </figcaption>
</figure>
Was it a good pairing?  Yes.  Why?  Christmas Ale is a really nice beer.  Past years
have been hit or miss, since the Great Lakes brewmaster allegedly ran off to Thirsty
Dog and took the original recipe with him.  Last year was a bit of a miss, but this year's
batch is a good recovery.

Also, back to Red Rising,
Christmas Ale is arguably the best thing to come out of Cleveland, Ohio, which
probably rivals Detroit as the lowRed of the USA.  And like Darrow, it's had a rough past, made
some mistakes, but has cleaned up well to rise to the best of the holiday ales this season.

#### Final Ratings

* Taste: Awesome brew, wide appeal.  **8.5**
* Book pairing: Drinking a Christmas Ale is too happy for all the death of Red Rising,
but Cleveland/Darrow makes a great underdog.  **6**


text:
module Fog
  module Identity
    class OpenStack
      class V3
        class Real
          def list_user_groups(user_id)
            request(
              :expects => [200],
              :method  => 'GET',
              :path    => "users/#{user_id}/groups"
            )
          end
        end

        class Mock
          def list_user_groups
          end
        end
      end
    end
  end
end


text:
<html>
<head>
	<script src="js/jquery.min.js"></script>
	<script src="js/background.js"></script>
</head>
<body>
</body>
</html>


text:
import collections
import os
import re

def read_config_file(updaters, opts, config_file_name):
    if os.path.isfile(config_file_name):
        _parse_config_file(updaters=updaters, opts=opts, config_file_name=config_file_name)

def _parse_config_file(updaters, opts, config_file_name):
    with open(config_file_name, 'r') as config_file:
        line_num = 0

        for line in config_file:
            line_num += 1

            ccmd = collections.namedtuple('ConfigCommand', ['cmd', 'arg', 'config_file_name', 'line_num'])
            ccmd.config_file_name = config_file_name
            ccmd.line_num = line_num

            _parse_config_file_line(line, ccmd)
            _process_cmd(updaters, opts, ccmd)

def _parse_config_file_line(line, ccmd):
    index = 0
    ccmd.cmd = ''
    ccmd.arg = ''

    # remove whitespace before command
    while not _at_eol(line, index) and re.match(r'\s', line[index]):
        index += 1

    # create command
    while not _at_eol(line, index) and re.match(r'\S', line[index]):
        ccmd.cmd += line[index]
        index += 1

    # remove whitespace between command and argument
    while not _at_eol(line, index) and re.match(r'\s', line[index]):
        index += 1

    # create argument
    while not _at_eol(line, index):
        ccmd.arg += line[index]
        index += 1

# ################## #
# Command Processors #
# ################## #

def _process_cmd(updaters, opts, ccmd):
    if _should_process_cmd(ccmd.cmd):
        updater = _get_updater_for_command(updaters, ccmd)

        if updater is None:
            raise InvalidConfigError('[{}, line {}] Invalid Configuration command: {}'.format(
                ccmd.config_file_name, ccmd.line_num, ccmd.cmd))

        updater.update_opts_for_command(opts, ccmd)

def _get_updater_for_command(updaters, ccmd):
    return next(iter([u for u in updaters if u.get_config_command().lower() == ccmd.cmd.lower()]), None)

def _should_process_cmd(cmd):
    return len(cmd) > 0 and not cmd.startswith('#')

# ################# #
# Utility Functions #
# ################# #

def _at_eol(line, index):
    return len(line) <= index or line[index] == '\n'

def _normalize_home_dir(directory):
    if directory == '~' or directory.startswith('~/') or directory.startswith('~\\'):
        directory = os.path.expanduser('~') + directory[1:]

    return directory

# ########## #
# Exceptions #
# ########## #

class InvalidConfigError(Exception):
    pass


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.CosmosDB.Models
{
    public partial class CosmosDBServiceProperties : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(InstanceSize))
            {
                writer.WritePropertyName("instanceSize");
                writer.WriteStringValue(InstanceSize.Value.ToString());
            }
            if (Optional.IsDefined(InstanceCount))
            {
                writer.WritePropertyName("instanceCount");
                writer.WriteNumberValue(InstanceCount.Value);
            }
            writer.WritePropertyName("serviceType");
            writer.WriteStringValue(ServiceType.ToString());
            foreach (var item in AdditionalProperties)
            {
                writer.WritePropertyName(item.Key);
#if NET6_0_OR_GREATER
				writer.WriteRawValue(item.Value);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(item.Value.ToString()).RootElement);
#endif
            }
            writer.WriteEndObject();
        }

        internal static CosmosDBServiceProperties DeserializeCosmosDBServiceProperties(JsonElement element)
        {
            if (element.TryGetProperty("serviceType", out JsonElement discriminator))
            {
                switch (discriminator.GetString())
                {
                    case "DataTransfer": return DataTransferServiceProperties.DeserializeDataTransferServiceProperties(element);
                    case "GraphAPICompute": return GraphApiComputeServiceProperties.DeserializeGraphApiComputeServiceProperties(element);
                    case "MaterializedViewsBuilder": return MaterializedViewsBuilderServiceProperties.DeserializeMaterializedViewsBuilderServiceProperties(element);
                    case "SqlDedicatedGateway": return SqlDedicatedGatewayServiceProperties.DeserializeSqlDedicatedGatewayServiceProperties(element);
                }
            }
            return UnknownServiceResourceProperties.DeserializeUnknownServiceResourceProperties(element);
        }
    }
}


text:
static const ossim_uint16 DATA_NULL_VALUE = 0xffff; // -32767
static const ossim_uint16 DATA_MIN_VALUE  = 0xfffe; // -32766
static const ossim_uint16 DATA_MAX_VALUE  = 0x7fff; // +32767
static const ossim_uint16 DATA_VALUE_MASK = 0x7fff; // 0111 1111 1111 1111
static const ossim_uint16 DATA_SIGN_MASK  = 0x8000; // 1000 0000 0000 0000
static const ossim_uint16 DATA_RECOGNITION_SENTINEL = 0xAA;  // 170

//***
// Offsets from start of data record (one record per longitude line):
//***
static const int BLOCK_COUNT_OFFSET = 2;
static const int LON_INDEX_OFFSET   = 4;
static const int LAT_INDEX_OFFSET   = 6;
static const int ELEV_DATA_OFFSET   = 8;
static const int RECORD_HDR_LENGTH  = 12;
static const int BYTES_PER_POINT    = 2;

//**************************************************************************
// CONSTRUCTOR
//**************************************************************************
ossimDtedRecord::ossimDtedRecord(std::istream& in,
                                 ossim_int32 offset,
                                 ossim_int32 num_points)
   :
      theRecSen("170"),
      theDataBlockCount(0),
      theLonCount(0),
      theLatCount(0),
      theCheckSum(0),
      thePoints(new ossim_int32[num_points]),
      thePointsData(new ossim_uint16[num_points]),
      theComputedCheckSum(0),
      theNumPoints(num_points),
      theStartOffset(offset),
      theStopOffset(offset + RECORD_HDR_LENGTH + (num_points*BYTES_PER_POINT))
{
   // Verify we are at a cell record by checking the Recognition Sentinel.
   ossim_uint8 buf[1];
   in.seekg(theStartOffset, std::ios::beg);
   in.read((char*)buf, 1);

#if 0
   printf("\nBuf: %02X", (int)buf[0]);  // Display in HEX
#endif

   if(buf[0] != DATA_RECOGNITION_SENTINEL)
   {
      theErrorStatus = ossimErrorCodes::OSSIM_ERROR;
      ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDtedRecord::ossimDtedRecord: reading DTED's data record at: " << theStartOffset
                                          << std::endl;
      return;
   }

   // Valid data record, so let's process on.
   parse(in);

   //***
   // Note:  The validateCheckSum method works; however, our in-house
   //        dted has bad stored check sums even though the post are good.
   //        So this in temporarily shut off.
   //***
   // Verify Check Sum for uncorrupted elevation data.
   if(validateCheckSum(in) == false)
   {
      //***
      // Note:  The validateCheckSum method works; however, our in-house
      //        dted has bad stored check sums even though the posts are good.
      //        So this in temporarily shut off.
      //***
      theErrorStatus = ossimErrorCodes::OSSIM_ERROR;
      ossimNotify(ossimNotifyLevel_FATAL)
         << "FATAL ossimDtedRecord::ossimDtedRecord:"
         << "\nInvalid checksum in data record at: "
         << theStartOffset
         << "\nParsed Check Sum = " << theCheckSum
         << "\nComputed Check Sum = " << theComputedCheckSum
         << "\nDTED Elevation File is considered corrupted."
         << std::endl;
      return;
   }
}

ossimDtedRecord::~ossimDtedRecord()
{
   if (thePoints)
   {
      delete [] thePoints;
      thePoints = NULL;
   }
   if (thePointsData)
   {
      delete [] thePointsData;
      thePointsData = NULL;
   }
}

//**************************************************************************
// parse()
//**************************************************************************
void ossimDtedRecord::parse(std::istream& in)
{
   // DTED is stored in big endian byte order so swap the bytes if needed.
   bool swap_bytes = ossim::byteOrder() == OSSIM_LITTLE_ENDIAN ? true : false;

   ossim_sint16 s;

   // parse data block count
   in.seekg(theStartOffset + BLOCK_COUNT_OFFSET, std::ios::beg);
   in.read((char*)&s, 2);
   theDataBlockCount =
      (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s);

   // parse lon count
   in.seekg(theStartOffset + LON_INDEX_OFFSET, std::ios::beg);
   in.read((char*)&s, 2);
   theLonCount =
      (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s);

   // parse lat count
   in.seekg(theStartOffset + LAT_INDEX_OFFSET, std::ios::beg);
   in.read((char*)&s, 2);
   theLatCount =
      (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s);

   // Parse all elevation points.
   in.seekg(theStartOffset + ELEV_DATA_OFFSET, std::ios::beg);
   for(int i = 0; i < theNumPoints; ++i)
   {
      in.read((char*)&s, 2);
      s = (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s);
      if (s & DATA_SIGN_MASK)
      {
         s = (s & DATA_VALUE_MASK) * -1;
      }
      thePoints[i] = static_cast<ossim_int32>(s);
      thePointsData[i] = s;
   }
}

//**************************************************************************
// validateCheckSum()
//**************************************************************************
bool ossimDtedRecord::validateCheckSum(std::istream& in)
{
   // DTED is stored in big endian byte order so swap the bytes if needed.
   bool swap_bytes = ossim::byteOrder() == OSSIM_LITTLE_ENDIAN ? true : false;

   // Compute the check sum.
   in.seekg(theStartOffset, std::ios::beg);
   theComputedCheckSum = 0;
   ossim_int32 bytesToRead = (theNumPoints * 2) + ELEV_DATA_OFFSET;
   int i = 0;

   for(i = 0; i < bytesToRead; i++)
   {
      ossim_uint8 c;
      in.read((char*)&c, 1);
      theComputedCheckSum += static_cast<ossim_uint32>(c);
   }

   // Read the stored check sum and swap the byte if needed.
   in.read((char*)&theCheckSum, 4);
   if (swap_bytes)
   {
      ossimEndian swapper;
      swapper.swap(theCheckSum);
   }

   // Compare computed and parsed checksums.
   if(theCheckSum != theComputedCheckSum)
   {
      return false;
   }
   return true;
}

ossimString ossimDtedRecord::recognitionSentinel() const
{
   return theRecSen;
}

ossim_int32 ossimDtedRecord::dataBlockCount() const
{
   return theDataBlockCount;
}

ossim_int32 ossimDtedRecord::lonCount() const
{
   return theLonCount;
}

ossim_int32 ossimDtedRecord::latCount() const
{
   return theLatCount;
}

ossim_uint32 ossimDtedRecord::checkSum() const
{
   return theCheckSum;
}

ossim_uint32 ossimDtedRecord::computedCheckSum() const
{
   return theComputedCheckSum;
}

ossim_int32 ossimDtedRecord::numPoints() const
{
   return theNumPoints;
}

ossim_int32 ossimDtedRecord::getPoint(ossim_int32 i) const
{
   return thePoints[i];
}

ossim_uint16 ossimDtedRecord::getPointData(ossim_int32 i) const
{
   return thePointsData[i];
}

ossim_int32*  ossimDtedRecord::points() const
{
   return thePoints;
}

ossim_uint16* ossimDtedRecord::pointsData() const
{
   return thePointsData;
}

ossim_int32 ossimDtedRecord::startOffset() const
{
   return theStartOffset;
}

ossim_int32 ossimDtedRecord::stopOffset() const
{
   return theStopOffset;
}

//**************************************************************************
// operator <<
//**************************************************************************
std::ostream& operator<<( std::ostream& os, const ossimDtedRecord& rec)
{
   os << "\nDTED Record:"
      << "\n-------------------------------"
      << "\n Recognition Sentinel: " << rec.theRecSen
      << "\nData Block Count:      " << rec.theDataBlockCount
      << "\nLon Count:             " << rec.theLonCount
      << "\nLat Count:             " << rec.theLatCount
      << "\nNum Points:            " << rec.theNumPoints
      << "\nParsed Check Sum:      " << rec.theCheckSum
      << "\nComputed Check Sum     " << rec.theComputedCheckSum
      << "\nStart Offset:          " << rec.theStartOffset
      << "\nStop Offset:           " << rec.theStopOffset
      << std::endl;
   int i = 0;

   for(i = 0; i < rec.theNumPoints; i++)
   {
      os << "\nPoint[" << i << "]: " << rec.thePoints[i];
   }

   os << std::endl;

   return os;
}


text:
RouteTableTools
===============

A set of tools/scripts for setup a auto route table for one country. Useful for speed up your internet.


text:
cask "whalebird" do
  version "4.3.4"
  sha256 "ad6a313270cb09a4743376d4ad1fcdfa1490f2c2ace6e952906493e0eac4ad13"

  url "https://github.com/h3poteto/whalebird-desktop/releases/download/#{version}/Whalebird-#{version}-darwin-x64.dmg",
      verified: "github.com/h3poteto/whalebird-desktop/"
  appcast "https://github.com/h3poteto/whalebird-desktop/releases.atom"
  name "Whalebird"
  desc "Electron-based Mastodon and Pleroma client"
  homepage "https://whalebird.social/"

  app "Whalebird.app"
end


text:
@(
  login: LoginSession,
  admin: StoreUser,
  tran: PersistedTransaction,
  addr: Option[Address],
  metadata: Map[(Long, Long), Map[SiteItemNumericMetadataType, SiteItemNumericMetadata]]
)(
  implicit mp: MessagesProvider
)
@import java.time.format.DateTimeFormatter
<ご注文者様>
@{login.storeUser.companyName.getOrElse("")} @{login.storeUser.firstName} @{login.storeUser.lastName}様
メールアドレス: @addr.map(_.email).filter(!_.isEmpty).getOrElse(login.storeUser.email)

<店舗>
@tran.siteTable.map { site =>@site.name

<ご注文商品>
@tran.itemTable(site.id.get).map { it =>
@{it._1.name}/@Messages("item.size." + metadata(site.id.get -> it._2.itemId).get(SiteItemNumericMetadataType.SHIPPING_SIZE).map{_.metadata}.getOrElse(0))/@{it._2.quantity}点/@{"%,.0f".format(it._2.amount)}円 }
小計 @{"%,.0f".format(tran.itemTotal(site.id.get))}円
@{Messages("outer.tax.amount")} @{"%,.0f".format(tran.outerTaxTotal(site.id.get))}円
商品計 @{"%,.0f".format(tran.itemTotal(site.id.get) + tran.outerTaxTotal(site.id.get))}円

@if(addr.isDefined) {
<送料>
@tran.shippingTable(site.id.get).map { shipping => @{shipping.boxName}/@{"%,.0f".format(shipping.amount / shipping.boxCount)}円/@{shipping.boxCount}点/小計 @{"%,.0f".format(shipping.amount)}円
}
配送希望日 @{DateTimeFormatter.ofPattern(Messages("shipping.date.format")).format(tran.shippingTable(site.id.get).head.shippingDate.atZone(java.time.ZoneId.systemDefault()))}
}

}
<合計>
商品計 @{"%,.0f".format(tran.itemGrandTotal + tran.outerTaxGrandTotal)}円/個数 @{tran.itemQuantity.values.fold(0L){_+_}}点
@if(addr.isDefined) {
送料計 @{"%,.0f".format(tran.boxGrandTotal)}円/個数 @{tran.boxQuantity.values.fold(0){_+_}}点
}
合計 @{"%,.0f".format(tran.itemGrandTotal + tran.outerTaxGrandTotal + tran.boxGrandTotal)}円

@addr.map { a=><お届け先>
@a.firstName @a.lastName
@a.firstNameKana @a.lastNameKana
郵便番号:@{a.zip1}-@{a.zip2}
都道府県:@a.prefecture
住所:
@a.address1
@a.address2
@a.address3
電話番号:@a.tel1
配送希望日:@{DateTimeFormatter.ofPattern(Messages("shipping.date.format")).format(tran.shippingTable(tran.siteTable.head.id.get).head.shippingDate.atZone(java.time.ZoneId.systemDefault()))}
コメント:@a.comment
}

---
Functional Store


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {

  public function index() {
    $this->session->set_flashdata('error', "You don't have access to view this resource.");
    redirect('/error');
  }

}

/* End of file admin.php */
/* Location: ./application/controllers/admin.php */


text:
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MailTracker.Tracker.Models
{
    public class MainResult
    {
        [JsonProperty("status")]
        public int Status { get; set; }
        [JsonProperty("result")]
        public Dictionary<string, TrackResult> Result { get; set; }
    }
}


text:
package it.unibz.inf.ontop.owlapi;

import it.unibz.inf.ontop.injection.OntopSQLOWLAPIConfiguration;
import it.unibz.inf.ontop.iq.IQ;
import it.unibz.inf.ontop.iq.node.NativeNode;
import it.unibz.inf.ontop.owlapi.connection.OntopOWLConnection;
import it.unibz.inf.ontop.owlapi.connection.OntopOWLStatement;
import it.unibz.inf.ontop.owlapi.impl.SimpleOntopOWLEngine;
import it.unibz.inf.ontop.owlapi.resultset.OWLBinding;
import it.unibz.inf.ontop.owlapi.resultset.OWLBindingSet;
import it.unibz.inf.ontop.owlapi.resultset.TupleOWLResultSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.semanticweb.owlapi.io.ToStringRenderer;
import org.semanticweb.owlapi.model.OWLObject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Iterator;

import static it.unibz.inf.ontop.utils.OWLAPITestingTools.executeFromFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Reproduces bug #263
 **/

public class SubLiftTest {
    private static final String CREATE_SCRIPT = "src/test/resources/subLift/create.sql";
    private static final String DROP_SCRIPT = "src/test/resources/subLift/drop.sql";
    private static final String OWL_FILE = "src/test/resources/subLift/test.owl";
    private static final String MAPPING_FILE = "src/test/resources/subLift/test.obda";
    private static final ToStringRenderer renderer = ToStringRenderer.getInstance();

    private static final String URL = "jdbc:h2:mem:job";
    private static final String USER = "sa";
    private static final String PASSWORD = "sa";

    private Connection conn;

    @Before
    public void setUp() throws Exception {
        conn = DriverManager.getConnection(URL, USER, PASSWORD);
        executeFromFile(conn, CREATE_SCRIPT);
    }

    @After
    public void tearDown() throws Exception {
        executeFromFile(conn, DROP_SCRIPT);
        conn.close();
    }

    @Test
    public void testQuery() throws Exception {

        String query = "PREFIX : <http://www.semanticweb.org/user/ontologies/2016/8/untitled-ontology-84#>\n" +
                "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
                "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" +
                "PREFIX xml: <http://www.w3.org/XML/1998/namespace>\n" +
                "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
                "SELECT  ?instance ?predicate_object ?instanceLabel ?object ?objectLabel " +
                "WHERE " +
                "{ ?instance  ?predicate_object  ?object " +
                "OPTIONAL " +
                "{ ?instance  <http://www.w3.org/2000/01/rdf-schema#label>  ?instanceLabel}" +
                " OPTIONAL " +
                "{ ?object  <http://www.w3.org/2000/01/rdf-schema#label>  ?objectLabel} } " +
                "VALUES ?instance { <http://www.semanticweb.org/test#person1> }";

        int expectedCardinality = 3;
        String sql = execute(query, expectedCardinality);

        System.out.println("SQL Query: \n" + sql);
    }

    private String execute(String query, int expectedCardinality) throws Exception {

        OntopSQLOWLAPIConfiguration config = OntopSQLOWLAPIConfiguration.defaultBuilder()
                .nativeOntopMappingFile(MAPPING_FILE)
                .ontologyFile(OWL_FILE)
                .jdbcUrl(URL)
                .jdbcUser(USER)
                .jdbcPassword(PASSWORD)
                .enableTestMode()
                .build();
        OntopOWLEngine reasoner = new SimpleOntopOWLEngine(config);

        // Now we are ready for querying
        OntopOWLConnection conn = reasoner.getConnection();
        OntopOWLStatement st = conn.createStatement();
        String sql;

        int i = 0;
        try {
            IQ executableQuery = st.getExecutableQuery(query);
            sql = ((NativeNode) executableQuery.getTree().getChildren().get(0)).getNativeQueryString();
            TupleOWLResultSet rs = st.executeSelectQuery(query);
            while (rs.hasNext()) {
                final OWLBindingSet bindingSet = rs.next();
                Iterator<OWLBinding> it = bindingSet.iterator();
                System.out.println(i);
                while (it.hasNext()) {
                    OWLBinding b = it.next();
                    System.out.println(("\t" + b.getName() + "\t" + stringify(b.getValue())));
                }
                assertTrue(
                        !stringify(bindingSet.getBinding("object").getValue()).equals("<http://www.semanticweb.org/test#job1>") ||
                                stringify(bindingSet.getBinding("objectLabel").getValue()).equals("\"Job 1\"^^xsd:string")
                );
                assertTrue(
                        stringify(bindingSet.getBinding("predicate_object").getValue()).equals("<http://www.semanticweb.org/test#hasJob>") ||
                                bindingSet.getBindingNames().size() == 4
                );
                i++;
            }
            assertEquals(expectedCardinality, i);
        }
        finally {
            conn.close();
            reasoner.close();
        }
        return sql;
    }

    private String stringify(OWLObject owlObject) {
        return renderer.getRendering(owlObject);
    }
}


text:
package org.apache.hadoop.streaming;

import junit.framework.TestCase;
import java.io.*;

import org.apache.hadoop.fs.FileUtil;

/**
 * This class tests hadoopStreaming in MapReduce local mode by giving
 * empty input to mapper and the mapper generates nonempty output. Since map()
 * is not called at all, output thread was not getting created and the mapper
 * was hanging forever. Now this issue is solved. Similarly reducer is also
 * checked for task completion with empty input and nonempty output.
 */
public class TestStreamingEmptyInpNonemptyOut extends TestCase
{

  protected File INPUT_FILE = new File("emptyInputFile.txt");
  protected File OUTPUT_DIR = new File("out");
  protected File SCRIPT_FILE = new File("perlScript.pl");

  protected String map = "perlScript.pl";
  protected String reduce = "org.apache.hadoop.mapred.lib.IdentityReducer";
  protected String script = "#!/usr/bin/perl\nfor($count = 1500; $count >= 1; $count--) {print \"$count \";}";

  private StreamJob job;

  public TestStreamingEmptyInpNonemptyOut() throws IOException
  {
    UtilTest utilTest = new UtilTest(getClass().getName());
    utilTest.checkUserDir();
    utilTest.redirectIfAntJunit();
  }

  protected void createInputAndScript() throws IOException
  {
    DataOutputStream out = new DataOutputStream(
                           new FileOutputStream(INPUT_FILE.getAbsoluteFile()));
    out.close();

    out = new DataOutputStream(
          new FileOutputStream(SCRIPT_FILE.getAbsoluteFile()));
    out.write(script.getBytes("UTF-8"));
    out.close();
  }

  protected String[] genArgs() {
    return new String[] {
      "-input", INPUT_FILE.getAbsolutePath(),
      "-output", OUTPUT_DIR.getAbsolutePath(),
      "-mapper", map,
      "-reducer", reduce,
      //"-verbose",
      //"-jobconf", "stream.debug=set"
      "-jobconf", "mapreduce.task.files.preserve.failedtasks=true",
      "-jobconf", "stream.tmpdir="+System.getProperty("test.build.data","/tmp")
    };
  }

  public void testEmptyInputNonemptyOutput() throws IOException
  {
    try {
      try {
        OUTPUT_DIR.getAbsoluteFile().delete();
      } catch (Exception e) {
      }

      createInputAndScript();
      boolean mayExit = false;

      // During tests, the default Configuration will use a local mapred
      // So don't specify -config or -cluster.
      // First let us test if mapper doesn't hang for empty i/p and nonempty o/p
      job = new StreamJob(genArgs(), mayExit);
      job.go();
      File outFile = new File(OUTPUT_DIR, "part-00000").getAbsoluteFile();
      outFile.delete();

      // Now let us test if reducer doesn't hang for empty i/p and nonempty o/p
      map = "org.apache.hadoop.mapred.lib.IdentityMapper";
      reduce = "perlScript.pl";
      job = new StreamJob(genArgs(), mayExit);
      job.go();
      outFile = new File(OUTPUT_DIR, "part-00000").getAbsoluteFile();
      outFile.delete();
    } finally {
      try {
        INPUT_FILE.delete();
        SCRIPT_FILE.delete();
        FileUtil.fullyDelete(OUTPUT_DIR.getAbsoluteFile());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  public static void main(String[]args) throws Exception
  {
    new TestStreaming().testCommandLine();
  }

}


text:
/**
 * Core classes for using Spring REST Docs with Citrus.
 */
package com.consol.citrus.restdocs.http;


text:
{-# LANGUAGE UnicodeSyntax #-}

{-|
Module      : LinearRegression
Description : Gradient Descent
Copyright   : (c) Fabrício Olivetti, 2017
License     : GPL-3
Maintainer  : fabricio.olivetti@gmail.com

Applies gradient descent to a linear regression problem.
-}

module LogisticRegressionPar where

import System.IO
import System.Environment
import Control.Parallel.Strategies
import Data.List (foldl1')
import Data.List.Split (chunksOf)

import Vector
import Dados

-- |'parseFile' parses a space separated file
-- to a list of lists of Double
parseFile :: String -> [(Vector Double, Double)]
parseFile file = map parseLine (lines file)
  where
    parseLine l = splitN (doubled l)
    splitN  l = (1 : (init l), last l) -- add bias +1
    doubled l  = map toDouble (words l)
    toDouble  w = read w :: Double

gradDesc :: ChunksOf [(Vector Double, Double)]
         -> Double -> Int
         -> Vector Double
gradDesc xy α it = gradDesc' xy w0 α it
  where
    w0 = take n [0.01,0.01..]
    n  = length' $ fst $ head $ head xy

gradDesc' :: ChunksOf [(Vector Double, Double)]
          -> Vector Double -> Double -> Int
          -> Vector Double
gradDesc' xy w α it
  | convergiu = w
  | otherwise = gradDesc' xy w' α (it-1)
  where
    w'        = w .+. (α *. (nabla ./ n))
    nabla     = mapReduce partial (.+.) xy
    partial (xi, yi) = ( yi - (sigmoid $ dotprod w xi) ) *. xi
    convergiu = (it==0)
    n         = sum $ map length' xy

sigmoid z = 1.0 / (1.0 + exp (-z))

erro ::  ChunksOf [(Vector Double, Double)] -> Vector Double -> Double
erro xy w = soma / n
  where
    soma = sum
         $ (map (\xyi -> sum $ map erro' xyi) xy
             `using` parList rdeepseq)
    erro' (xi,yi) = (yi - (dotprod w xi))^2
    n = sum $ map length' xy

accuracy :: ChunksOf [(Vector Double, Double)] -> Vector Double -> Double
accuracy xy w = (length' correct) / n
  where

    correct = filter (id) $ concat
            $ (map mapper xy `using` parList rdeepseq)
    mapper xyi = filter (id) $ map (\(x,y) -> fhat x == y) xyi
    fhat xi  = round' $ sigmoid $ sum $ w .*. xi

    round' x = fromIntegral $ round $ x
    n = sum $ map length' xy


text:
// @Generated by gentest/gentest.rb from gentest/fixtures/YGAndroidNewsFeed.html

package com.facebook.yoga;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class YGAndroidNewsFeed {
  @Parameterized.Parameters(name = "{0}")
  public static Iterable<TestParametrization.NodeFactory> nodeFactories() {
    return TestParametrization.nodeFactories();
  }

  @Parameterized.Parameter public TestParametrization.NodeFactory mNodeFactory;

  @Test
  public void test_android_news_feed() {
    YogaConfig config = YogaConfigFactory.create();

    final YogaNode root = createNode(config);
    root.setAlignContent(YogaAlign.STRETCH);
    root.setWidth(1080f);

    final YogaNode root_child0 = createNode(config);
    root.addChildAt(root_child0, 0);

    final YogaNode root_child0_child0 = createNode(config);
    root_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0.addChildAt(root_child0_child0, 0);

    final YogaNode root_child0_child0_child0 = createNode(config);
    root_child0_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0.addChildAt(root_child0_child0_child0, 0);

    final YogaNode root_child0_child0_child0_child0 = createNode(config);
    root_child0_child0_child0_child0.setFlexDirection(YogaFlexDirection.ROW);
    root_child0_child0_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child0_child0.setAlignItems(YogaAlign.FLEX_START);
    root_child0_child0_child0_child0.setMargin(YogaEdge.START, 36f);
    root_child0_child0_child0_child0.setMargin(YogaEdge.TOP, 24f);
    root_child0_child0_child0.addChildAt(root_child0_child0_child0_child0, 0);

    final YogaNode root_child0_child0_child0_child0_child0 = createNode(config);
    root_child0_child0_child0_child0_child0.setFlexDirection(YogaFlexDirection.ROW);
    root_child0_child0_child0_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child0_child0.addChildAt(root_child0_child0_child0_child0_child0, 0);

    final YogaNode root_child0_child0_child0_child0_child0_child0 = createNode(config);
    root_child0_child0_child0_child0_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child0_child0_child0_child0.setWidth(120f);
    root_child0_child0_child0_child0_child0_child0.setHeight(120f);
    root_child0_child0_child0_child0_child0.addChildAt(root_child0_child0_child0_child0_child0_child0, 0);

    final YogaNode root_child0_child0_child0_child0_child1 = createNode(config);
    root_child0_child0_child0_child0_child1.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child0_child0_child1.setFlexShrink(1f);
    root_child0_child0_child0_child0_child1.setMargin(YogaEdge.RIGHT, 36f);
    root_child0_child0_child0_child0_child1.setPadding(YogaEdge.LEFT, 36);
    root_child0_child0_child0_child0_child1.setPadding(YogaEdge.TOP, 21);
    root_child0_child0_child0_child0_child1.setPadding(YogaEdge.RIGHT, 36);
    root_child0_child0_child0_child0_child1.setPadding(YogaEdge.BOTTOM, 18);
    root_child0_child0_child0_child0.addChildAt(root_child0_child0_child0_child0_child1, 1);

    final YogaNode root_child0_child0_child0_child0_child1_child0 = createNode(config);
    root_child0_child0_child0_child0_child1_child0.setFlexDirection(YogaFlexDirection.ROW);
    root_child0_child0_child0_child0_child1_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child0_child0_child1_child0.setFlexShrink(1f);
    root_child0_child0_child0_child0_child1.addChildAt(root_child0_child0_child0_child0_child1_child0, 0);

    final YogaNode root_child0_child0_child0_child0_child1_child1 = createNode(config);
    root_child0_child0_child0_child0_child1_child1.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child0_child0_child1_child1.setFlexShrink(1f);
    root_child0_child0_child0_child0_child1.addChildAt(root_child0_child0_child0_child0_child1_child1, 1);

    final YogaNode root_child0_child0_child1 = createNode(config);
    root_child0_child0_child1.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0.addChildAt(root_child0_child0_child1, 1);

    final YogaNode root_child0_child0_child1_child0 = createNode(config);
    root_child0_child0_child1_child0.setFlexDirection(YogaFlexDirection.ROW);
    root_child0_child0_child1_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child1_child0.setAlignItems(YogaAlign.FLEX_START);
    root_child0_child0_child1_child0.setMargin(YogaEdge.START, 174f);
    root_child0_child0_child1_child0.setMargin(YogaEdge.TOP, 24f);
    root_child0_child0_child1.addChildAt(root_child0_child0_child1_child0, 0);

    final YogaNode root_child0_child0_child1_child0_child0 = createNode(config);
    root_child0_child0_child1_child0_child0.setFlexDirection(YogaFlexDirection.ROW);
    root_child0_child0_child1_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child1_child0.addChildAt(root_child0_child0_child1_child0_child0, 0);

    final YogaNode root_child0_child0_child1_child0_child0_child0 = createNode(config);
    root_child0_child0_child1_child0_child0_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child1_child0_child0_child0.setWidth(72f);
    root_child0_child0_child1_child0_child0_child0.setHeight(72f);
    root_child0_child0_child1_child0_child0.addChildAt(root_child0_child0_child1_child0_child0_child0, 0);

    final YogaNode root_child0_child0_child1_child0_child1 = createNode(config);
    root_child0_child0_child1_child0_child1.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child1_child0_child1.setFlexShrink(1f);
    root_child0_child0_child1_child0_child1.setMargin(YogaEdge.RIGHT, 36f);
    root_child0_child0_child1_child0_child1.setPadding(YogaEdge.LEFT, 36);
    root_child0_child0_child1_child0_child1.setPadding(YogaEdge.TOP, 21);
    root_child0_child0_child1_child0_child1.setPadding(YogaEdge.RIGHT, 36);
    root_child0_child0_child1_child0_child1.setPadding(YogaEdge.BOTTOM, 18);
    root_child0_child0_child1_child0.addChildAt(root_child0_child0_child1_child0_child1, 1);

    final YogaNode root_child0_child0_child1_child0_child1_child0 = createNode(config);
    root_child0_child0_child1_child0_child1_child0.setFlexDirection(YogaFlexDirection.ROW);
    root_child0_child0_child1_child0_child1_child0.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child1_child0_child1_child0.setFlexShrink(1f);
    root_child0_child0_child1_child0_child1.addChildAt(root_child0_child0_child1_child0_child1_child0, 0);

    final YogaNode root_child0_child0_child1_child0_child1_child1 = createNode(config);
    root_child0_child0_child1_child0_child1_child1.setAlignContent(YogaAlign.STRETCH);
    root_child0_child0_child1_child0_child1_child1.setFlexShrink(1f);
    root_child0_child0_child1_child0_child1.addChildAt(root_child0_child0_child1_child0_child1_child1, 1);
    root.setDirection(YogaDirection.LTR);
    root.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);

    assertEquals(0f, root.getLayoutX(), 0.0f);
    assertEquals(0f, root.getLayoutY(), 0.0f);
    assertEquals(1080f, root.getLayoutWidth(), 0.0f);
    assertEquals(240f, root.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0.getLayoutWidth(), 0.0f);
    assertEquals(240f, root_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(240f, root_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(144f, root_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(24f, root_child0_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(1044f, root_child0_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child0_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(120f, root_child0_child0_child0_child0_child1.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child0_child0_child1.getLayoutWidth(), 0.0f);
    assertEquals(39f, root_child0_child0_child0_child0_child1.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child0_child0_child1_child0.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child0_child0_child1_child0.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child0.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child0.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child0_child0_child1_child1.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child0_child0_child1_child1.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child1.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child1.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child1.getLayoutX(), 0.0f);
    assertEquals(144f, root_child0_child0_child1.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0_child0_child1.getLayoutWidth(), 0.0f);
    assertEquals(96f, root_child0_child0_child1.getLayoutHeight(), 0.0f);

    assertEquals(174f, root_child0_child0_child1_child0.getLayoutX(), 0.0f);
    assertEquals(24f, root_child0_child0_child1_child0.getLayoutY(), 0.0f);
    assertEquals(906f, root_child0_child0_child1_child0.getLayoutWidth(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child1_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child0.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child1_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(72f, root_child0_child0_child1_child0_child1.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child1.getLayoutWidth(), 0.0f);
    assertEquals(39f, root_child0_child0_child1_child0_child1.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child1_child0_child1_child0.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child1_child0_child1_child0.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child0.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child0.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child1_child0_child1_child1.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child1_child0_child1_child1.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child1.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child1.getLayoutHeight(), 0.0f);

    root.setDirection(YogaDirection.RTL);
    root.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);

    assertEquals(0f, root.getLayoutX(), 0.0f);
    assertEquals(0f, root.getLayoutY(), 0.0f);
    assertEquals(1080f, root.getLayoutWidth(), 0.0f);
    assertEquals(240f, root.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0.getLayoutWidth(), 0.0f);
    assertEquals(240f, root_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(240f, root_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(144f, root_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(24f, root_child0_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(1044f, root_child0_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(924f, root_child0_child0_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child0_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(120f, root_child0_child0_child0_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(816f, root_child0_child0_child0_child0_child1.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child0_child0_child1.getLayoutWidth(), 0.0f);
    assertEquals(39f, root_child0_child0_child0_child0_child1.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child0_child0_child1_child0.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child0_child0_child1_child0.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child0.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child0.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child0_child0_child1_child1.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child0_child0_child1_child1.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child1.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child0_child0_child1_child1.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child1.getLayoutX(), 0.0f);
    assertEquals(144f, root_child0_child0_child1.getLayoutY(), 0.0f);
    assertEquals(1080f, root_child0_child0_child1.getLayoutWidth(), 0.0f);
    assertEquals(96f, root_child0_child0_child1.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child1_child0.getLayoutX(), 0.0f);
    assertEquals(24f, root_child0_child0_child1_child0.getLayoutY(), 0.0f);
    assertEquals(906f, root_child0_child0_child1_child0.getLayoutWidth(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0.getLayoutHeight(), 0.0f);

    assertEquals(834f, root_child0_child0_child1_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child0.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(0f, root_child0_child0_child1_child0_child0_child0.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child0_child0.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0_child0.getLayoutWidth(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child0_child0.getLayoutHeight(), 0.0f);

    assertEquals(726f, root_child0_child0_child1_child0_child1.getLayoutX(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1.getLayoutY(), 0.0f);
    assertEquals(72f, root_child0_child0_child1_child0_child1.getLayoutWidth(), 0.0f);
    assertEquals(39f, root_child0_child0_child1_child0_child1.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child1_child0_child1_child0.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child1_child0_child1_child0.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child0.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child0.getLayoutHeight(), 0.0f);

    assertEquals(36f, root_child0_child0_child1_child0_child1_child1.getLayoutX(), 0.0f);
    assertEquals(21f, root_child0_child0_child1_child0_child1_child1.getLayoutY(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child1.getLayoutWidth(), 0.0f);
    assertEquals(0f, root_child0_child0_child1_child0_child1_child1.getLayoutHeight(), 0.0f);
  }

  private YogaNode createNode(YogaConfig config) {
    return mNodeFactory.create(config);
  }
}


text:
package com.flp.ems.model.role;

public class Role {
	//INSTANCE VARIABLE
	private int roleId;
	private String roleName;
	private String roleDesc;
	private static int numId;
	//STATIC BLOCK
	static{
		numId=100+(int) (Math.random()*0.034);
	}
	//INIT BLOCK
	{
		roleId=getNumId();
	}
	//DEFAULT CONSTRUCTOR
	public Role() {

	}
	//OVERLOADED CONSTRUCTOR
	public Role(String roleName, String roleDesc) {
		super();
		this.roleName = roleName;
		this.roleDesc = roleDesc;
	}
	//TO STRING
	@Override
	public String toString() {
		return "\nRole [roleId=" + roleId + ", roleName=" + roleName
				+ ", roleDesc=" + roleDesc + "]";
	}
	//GETTERS AND SETTERS
	public int getRoleId() {
		return roleId;
	}
	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public String getRoleDesc() {
		return roleDesc;
	}
	public void setRoleDesc(String roleDesc) {
		this.roleDesc = roleDesc;
	}
	public static int getNumId() {
		return ++numId;
	}
	public static void setNumId(int numId) {
		Role.numId = numId;
	}
}//end of role class


text:
                            {{#each item.{NAME}}}

                                    <input type="text" class="meta-input key" placeholder="{{_ 'Name'}}" value="{{@key}}" />
                                    <input type="text" class="meta-input value" placeholder="{{_ 'Value'}}" value="{{this}}" />
                                    <input type="hidden" name="{NAME}[{{@key}}]" value="{{this}}">

                            {{/each}}


text:
@class AIAccount, AIListContact, AIListObject;

@protocol AIContactMenuDelegate;

@interface AIContactMenu : AIAbstractListObjectMenu <AIListObjectObserver> {
	AIListObject			*containingObject;

	id<AIContactMenuDelegate>						delegate;
	BOOL					delegateRespondsToDidSelectContact;
	BOOL					delegateRespondsToShouldIncludeContact;
	BOOL					delegateRespondsToValidateContact;
	BOOL					shouldUseDisplayName;
	BOOL					shouldDisplayGroupHeaders;
	BOOL					shouldUseUserIcon;
	BOOL					shouldSetTooltip;
	BOOL					shouldIncludeContactListMenuItem;
	BOOL					populateMenuLazily;
}

+ (id)contactMenuWithDelegate:(id<AIContactMenuDelegate>)inDelegate forContactsInObject:(AIListObject *)inContainingObject;
- (void)setContainingObject:(AIListObject *)inContainingObject;

@property (readwrite, nonatomic, assign) id<AIContactMenuDelegate> delegate;

@end

@protocol AIContactMenuDelegate <NSObject>
- (void)contactMenuDidRebuild:(AIContactMenu *)inContactMenu;
@optional
- (void)contactMenu:(AIContactMenu *)inContactMenu didSelectContact:(AIListContact *)inContact;
- (AIListContact *)contactMenu:(AIContactMenu *)inContactMenu validateContact:(AIListContact *)inContact;
- (BOOL)contactMenu:(AIContactMenu *)inContactMenu shouldIncludeContact:(AIListContact *)inContact;
- (BOOL)contactMenuShouldUseUserIcon:(AIContactMenu *)inContactMenu;
- (BOOL)contactMenuShouldSetTooltip:(AIContactMenu *)inContactMenu;
- (BOOL)contactMenuShouldIncludeContactListMenuItem:(AIContactMenu *)inContactMenu;
- (BOOL)contactMenuShouldPopulateMenuLazily:(AIContactMenu *)inContactMenu;

// Called on each rebuild:
- (BOOL)contactMenuShouldDisplayGroupHeaders:(AIContactMenu *)inContactMenu; //only applies to contained groups
- (BOOL)contactMenuShouldUseDisplayName:(AIContactMenu *)inContactMenu;
@end


text:
layout: default
---

All Hack Education Articles

(Marketing) Virtual Reality in Education: A History

Virtual reality is not new. What's being sold to schools right now as VR is perhaps not even virtual reality. Rather it's stereoscopy with a more expensive device. It's the Android strapped to your forehead. The arguments for this technology echo those made at the turn of the 20th century for using films in class....

              <time datetime="2 July 2016">2 July 2016</time>

Coding Bootcamps and the New For-Profit Higher Ed

In October 2015, the Obama Administration announced a new initiative that would allow coding bootcamps, MOOCs, and other ed-tech experiments to be eligible for federal financial aid. It's a bit odd, perhaps, that it would do this while also saying it's interested in cracking down on for-profit higher education. Here's a history to link this all together....

              <time datetime="23 November 2015">23 November 2015</time>

No, Sesame Street Was Not the First MOOC

Research arguing that Sesame Street is just as good as preschool has been making the rounds lately. One of the arguments: Sesame Street is the first MOOC. Nope. It wasn't. Indeed, Sesame Street is the opposite of what's become popularized as MOOCs. Because Sesame Street is actually based on research....

              <time datetime="21 June 2015">21 June 2015</time>

The Invented History of 'The Factory Model of Education'

The "factory model of education" is invoked to describe our current system of schooling, one that is -- like factories, I suppose -- outmoded. But the history of the "factory model," as told by Alvin Toffler and Salman Khan, is an invented one, not so much about education's past as its future....

              <time datetime="25 April 2015">25 April 2015</time>

How Steve Jobs Brought the Apple II to the Classroom

How did Apple come to dominate the education computing market in the 1980s? In part through a legislative push from Steve Jobs, who lobbied for a bill that would have made donating computers to schools a tax write-off. He failed at the federal level, but he succeeded in California....

              <time datetime="25 February 2015">25 February 2015</time>

Speak & Spell: A History

A brief history of the Speak & Spell, one of the most iconic pieces of education technology. First introduced at the Consumer Electronics Show in 1978, the Speak & Spell is a teaching machine in the behaviorist sense. Texas Instruments' development of the device involved an important technological breakthrough in speech technology....

              <time datetime="13 January 2015">13 January 2015</time>

The Myth and the Millennialism of "Disruptive Innovation"

"Disruptive innovation" is millennialist. It is apocalyptic. It is End Times. It is a story of doom and salvation. It is capitalism's great myth. I don't mean "myth" as in "lie." I mean "myth" as in "the most sacred story you tell," the one you'd never dare challenge or question....

              <time datetime="24 May 2013">24 May 2013</time>

Codecademy and the Future of (Not) Learning to Code

One of my most popular (and most controversial) blog posts. Despite all the hype and all the investment, I remain skeptical that Codecademy can actually do much other than get people to tweet that they've signed up to learn to code. Building from there with meaningless blackjack exercises? Yeah. Nope....

              <time datetime="28 October 2011">28 October 2011</time>

The Wrath Against Khan: Why Some Educators Are Questioning Khan Academy

The most popular post ever on Hack Education. Here I describe why some educators question Khan Academy and challenge the media hype that Sal Khan is "math's messiah." There are serious flaws with Khan Academy, in terms of pedagogy and content. But to suggest that gets me death threats. Nice....

              <time datetime="19 July 2011">19 July 2011</time>

Image credits: Bryan Mathers


text:
package com.meidusa.venus.validate.validator;

import java.util.HashMap;

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

import com.meidusa.venus.validate.exception.ValidationException;
import com.meidusa.venus.validate.service.ServiceExample;
import com.meidusa.venus.validate.service.domain.Account;

public class TestVisitorValidator extends BaseValidatorTest {

    @Before
    public void init() {
        try {
            this.initChain(ServiceExample.class, ServiceExample.class.getDeclaredMethod("testVisitor", Account.class));
        } catch (Exception e) {
            e.printStackTrace();
            // ignore here
        }

    }

    @Test
    public void testSuccess() {

        HashMap<String, Object> map = new HashMap<String, Object>();
        Account account = new Account();
        account.setId(111L);
        account.setUsername("aaaaaaaa");

        map.put("account", account);
        try {
            this.validate(map);
        } catch (ValidationException e) {
            Assert.fail(e.getMessage());
        }

    }

    @Test
    public void testFailure() {
        boolean success = false;
        HashMap<String, Object> map = new HashMap<String, Object>();
        Account account = new Account();
        account.setId(111L);
        account.setUsername("aaaaaaaaaaaaaaaaaa");

        map.put("account", account);
        try {
            this.validate(map);
        } catch (ValidationException e) {
            success = true;
        }
        Assert.assertTrue(success);
    }
}


text:
import { ClassXCourse } from "./class"
import {State} from "./reducers"
import {name} from "./user"

export interface Filter {
    title?: string,
    course?: number
    department?: number,
    section?: number,
    semester?: string,
    year?: number,
    teacher?: string,
    CRN?: number,
    keyword?: string,
    syllabus?: boolean,
    [field: string]: any;
}

// The ugliest thing you will ever see. Check every item in the filter and if it exists check if it matches
export function filter(filter: Filter) {
    return function(course: ClassXCourse) {
        let title_valid = filter.title === undefined || course.title.toLowerCase().indexOf(filter.title.toLowerCase()) >= 0;
        let course_valid = filter.course === undefined || course.course === filter.course;
        let department_valid = filter.department === undefined || course.department == filter.department;
        let section_valid = filter.section === undefined || course.section === filter.section;
        let semester_valid = filter.semester === undefined || course.term === filter.semester;
        let year_valid = filter.year === undefined || course.year === filter.year;
        let teacher_valid = filter.teacher === undefined || name(course.teacher).toLowerCase().indexOf(filter.teacher.toLowerCase()) >= 0;
        let CRN_valid = filter.CRN === undefined || course.CRN === filter.CRN;
        let keyword_valid = filter.keyword === undefined || course.keyword.toLowerCase().indexOf(filter.keyword.toLowerCase()) >= 0;
        let syllabus_valid = filter.syllabus === undefined || !(course.syllabus == undefined || course.syllabus == 0) === filter.syllabus;
        console.log(syllabus_valid)
        return  title_valid &&
                course_valid &&
                department_valid &&
                section_valid &&
                semester_valid &&
                year_valid &&
                teacher_valid &&
                CRN_valid &&
                keyword_valid &&
                syllabus_valid;
    }
}


text:
@interface NSString
@end
static const NSString * const kSimDeviceIOGetInterface = @"simdeviceio_get_interface";


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Friend Points from Parties</title>
		<link>http://bvs.wikidot.com/forum/t-49526/friend-points-from-parties</link>
		<description>Posts in the discussion thread "Friend Points from Parties"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 05:07:49 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-49526#post-139074</guid>
				<title>Re: Friend Points from Parties</title>
				<link>http://bvs.wikidot.com/forum/t-49526/friend-points-from-parties#post-139074</link>
				<description></description>
				<pubDate>Sat, 05 Apr 2008 17:51:35 +0000</pubDate>
				<wikidot:authorName>Lich</wikidot:authorName>				<wikidot:authorUserId>98769</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

'Research' Expedition gives 1500 friend points.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-49526#post-134248</guid>
				<title>Re: Friend Points from Parties</title>
				<link>http://bvs.wikidot.com/forum/t-49526/friend-points-from-parties#post-134248</link>
				<description></description>
				<pubDate>Sun, 30 Mar 2008 00:25:40 +0000</pubDate>
				<wikidot:authorName>Ruinic</wikidot:authorName>				<wikidot:authorUserId>99313</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

The other less expensive parties give less points (of course), but Kamaitatchi is right. A party gives a total of a certain number of points, which is distributed evenly among your allies. If you have only one ally in your team, he/she will get the full amount but if you have three ninja in your team, each of them will get a third of the total points.
 The All-Out Bash gives 10k points. I think the Karaoke gives 250 points, and I can't remember how much the 'Research' Expedition gives.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-49526#post-134052</guid>
				<title>Re: Friend Points from Parties</title>
				<link>http://bvs.wikidot.com/forum/t-49526/friend-points-from-parties#post-134052</link>
				<description></description>
				<pubDate>Sat, 29 Mar 2008 17:17:36 +0000</pubDate>
				<wikidot:authorName>Kamaitatchi</wikidot:authorName>				<wikidot:authorUserId>90780</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

I have a guess… When I took the most expensive party all three allies gained 3333 friendship points. So my guess is that the game "distributes" 10000 points amongst your allies

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-49526#post-133033</guid>
				<title>Friend Points from Parties</title>
				<link>http://bvs.wikidot.com/forum/t-49526/friend-points-from-parties#post-133033</link>
				<description></description>
				<pubDate>Fri, 28 Mar 2008 03:41:05 +0000</pubDate>
				<wikidot:authorName>Ananvil</wikidot:authorName>				<wikidot:authorUserId>83686</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Does anyone know how many you get?

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
https://exploit-exercises.com/protostar/stack0/

## Goal

To override the `modified` variable.

## Source Code

stack0.c

```
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv)
{
  volatile int modified;
  char buffer[64];

  modified = 0;
  gets(buffer);

  if(modified != 0) {
      printf("you have changed the 'modified' variable\n");
  } else {
      printf("Try again?\n");
  }
}
```

## Exploit

`gets` is like `raw_input` in python. It retrieves user input and stores it in the array pointed to by `buffer`. However, `gets` doesn't
perform any bounds checking, so entering 65 a's will actually overflow the buffer and store the final 'a' at the location of `modified`,
thus modifying `modified`.