text:
<!DOCTYPE html>

    <title>"Book 5: Chapter 1" | Symbollic Logic | Lewis Carroll | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      Symbollic Logic

      by Lewis Carroll

      "Book 5: Chapter 1"

        Additional Information

            Year Published:
            1896

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Carroll, L. (1896). Symbollic Logic. New York; Macmillan & Co.

            Readability:

                Flesch–Kincaid Level:
                10.5

            Word Count:
            743

            Genre:
            Informational

            Keywords:
            math history, mathematics

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

Student Activity

            APA

            MLA

            Chicago

            Carroll, L. (1896). "Book 5: Chapter 1". Symbollic Logic (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/212/symbollic-logic/4694/book-5-chapter-1/

            Carroll, Lewis. ""Book 5: Chapter 1"." Symbollic Logic. Lit2Go Edition. 1896. Web. <http://etc.usf.edu/lit2go/212/symbollic-logic/4694/book-5-chapter-1/>. February 15, 2016.

            Lewis Carroll, ""Book 5: Chapter 1"," Symbollic Logic, Lit2Go Edition, (1896), accessed February 15, 2016, http://etc.usf.edu/lit2go/212/symbollic-logic/4694/book-5-chapter-1/.

Back

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/symbollic-logic-021-book-5-chapter-1.4694.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/symbollic-logic-021-book-5-chapter-1.4694.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	BOOK V.

	SYLLOGISMS.

	CHAPTER I.

	INTRODUCTORY

	When a Trio of Biliteral Propositions of Relation is such that

	(1) all their six Terms are Species of the same Genus,

	(2) every two of them contain between them a Pair of codivisional Classes

	(3) the three Propositions are so related that, if the first two were true, the third would be true,

	the Trio is called a ‘Syllogism’; the Genus, of which each of the six Terms is a Species, is called its ‘Universe of Discourse’, or, more briefly, its ‘Univ.’; the first two Propositions are called its ‘Premisses’, and the third its ‘Conclusion’; also the Pair of codivisional Terms in the Premisses are called its ‘Eliminands’, and the other two its ‘Retinends’.

	The Conclusion of a Syllogism is said to be ‘conseque from its Premisses: hence it is usual to prefix to it the w “Therefore” (or the Symbol .‘.).

	[Note that the ‘Eliminands’ are so called because they are eliminated, and do not appear in the Conclusion; and that the ‘Retinends’ are so called because they are retained, and do appear in the Conclusion.

	Note also that the question, whether the Conclusion is or is not consequent from the Premisses, is not affected by the actual truth or falsity of any of the Trio, but depends entirely on their relationship to each other.

	As a specimen-Sylligism, let us take the Trio

	“No x-Things are m-Things;

	No y-Things are m’-Things.

	No x-Things are y-Things.”

	which we may write thus:–

	“No x are m;

	No y are m’.

	No x are y”.

	Here the first and second contain the Pair of codivisional Classes m and m’; the first and third contain the Pair x and x; and the second and third contain the Pair y and y.

	Also the three Propositions are (as we shall see hereafter) so related that, if the first two were true, the third would also be true.

	Hence the Trio is a Syllogism; the two Propositions, “No x are m” and “No y are m’ ”, are its Premisses; the Propo- sition “No x are y” is its Conclusion; the Terms m and m’ are its Eliminands; and the Terms x and y are its Retinends.

	Hence we may write it thus:–

	“No x are m;

	No y are m’.

	.‘. No x are y”.

	As a second specimen, let us take the Trio

	“All cats understand French;

	Some chickens are cats.

	Some chickens understand French”.

	These, put into normal form, are

	“All cats are creatures understanding French;

	Some chickens are cats.

	Some chickens are creatures understandoing French”.

	Here all the six Terms are Species of the Genus “creatures.”

	Also the first and second Propositions contain the Pair of codivisional Classes “cats” and “cats”; the first and third contain the Pair “creatures understanding French” and “creatures understanding French”; and the second and third contain the Pair “chickens” and “chickens”.

	Also the three Propositions are (as we shall see at p. 64) so related that, if the first two were true, the third would be true. (The first two are, as it happens, not strictly true in our planet. But there is nothing to hinder them from being true in some other planer, say Mars or Jupiter—-in which case the third would also be true in that planet, and its inhabitants would probably engage chickens as nursery-governesses. They would thus secure a singular contingent privilege, unknown in England, namely, that they would be able, at any time when provisions ran short, to utilise the nursery-governess for the nursery-dinner!)

	Hence the Trio is a Syllogism; the Genus “creature” is its ‘Univ.’; the two Propositions, “All cats understand French” and “Some chickens are cats”, are its Premisses, the Proposition “Some chickens understand French” is its Conclusion; the Terms “cats” and “cats” are its Elimi- nands; and the Terms, “creatures understanding French” and “chickens”, are its Retinends.

	Hence we may write it thus:–

	“All cats understand French;

	Some chickens are cats;

	.‘. Some chickens understand French”]

Back

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/212/symbollic-logic/4694/book-5-chapter-1/.

Lit2Go: Symbollic Logic

"Book 5: Chapter 1"


text:
@interface DPHostMoviePlayer : DPHostMediaPlayer
- (void)closeMoviePlayerViewController;
@end

redpajama_set_name: RedPajamaGithub


text:
using System.Web;
using System.Web.Mvc;

namespace MyTecBits_Knockout_Bootstrap_MVC_Sample
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}


text:
package webcrawler.url.parser.matchers;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

import logger.Logger;
import logger.LogLevel;
import webcrawler.url.parser.matchers.ResourceMatcher;

public class CSSResourceMatcher extends ResourceMatcher {
    // public ResourceMatched match(String url, String line) {
    public ResourceMatched match(String url, String line, String [] match) {
        Pattern pattern = Pattern.compile(
            "<link [^>]*href=\"([^\"]*\\.css[^\"]*)\"[^>]*>");
        Matcher matcher = pattern.matcher(line);
        String urlMatched = new String();

        if (matcher.find()) {
            // Check if the URL has a <img> tag inside it
            urlMatched = matcher.group(1);

            if (urlMatched.startsWith("/")) {
                urlMatched = url + urlMatched;
            }
        }
        else {
            // This is not an CSS. Let the next matcher find what to do
            return this.next(url, line, match);
        }

        // If we arrived here, we got a valid URL
        match[0] = urlMatched;
        return ResourceMatched.CSS;
    }
}


text:
package com.example;

import com.microsoft.azure.spring.cloud.feature.manager.FeatureManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;

@Component
public class TestComponent {

    @Autowired
    private FeatureManager featureManager;

    public String test() throws InterruptedException, ExecutionException {
        if (featureManager.isEnabledAsync("Beta").block()) {
            return "Beta";
        }
        return "Original";
    }

}


text:
<?php
namespace MarketMeSuite\Phranken\Database\Mongo;

use MarketMeSuite\Phranken\Database\Interfaces\IDatabaseUser;

/**
 * Defines how an object should manage database connection information
 */
interface IDatabaseUserMongo extends IDatabaseUser
{
    public function getCollectionName();

    /**
     * Gets the set collection
     *
     * @param string $name
     *
     * @return string A collection name
     */
    public function setCollectionName($name);

    /**
     * Uses set information to resolve the actual collection instance
     * @return \MongoCollection The configured MongoCollection
     */
    public function getCollection();
}


text:
using NUnit.Framework;
using Rock.Core.UnitTests.KeyValueStores.Extensions;
using Rock.KeyValueStores;

// ReSharper disable once CheckNamespace
namespace GetItemsExtensionTests
{
    public class TheGetItemsExtensionMethod : KeyValueStoreExtensionsTestsBase
    {
        [Test]
        public void GetsABucketByNameThenCallsGetItemsOnTheBucket()
        {
            MockKeyValueStore.Object.GetItems("my_bucket");

            VerifyGetItems("my_bucket");
        }
    }
}


text:
#include <skiboot.h>
#include <opal.h>
#include <chip.h>
#include <sensor.h>
#include <device.h>
#include <cpu.h>
#include <occ.h>

enum sensor_attr {
	SENSOR_SAMPLE,
	SENSOR_SAMPLE_MIN,	/* OCC's min/max */
	SENSOR_SAMPLE_MAX,
	SENSOR_CSM_MIN,		/* CSM's min/max */
	SENSOR_CSM_MAX,
	SENSOR_ACCUMULATOR,
	MAX_SENSOR_ATTR,
};

#define HWMON_SENSORS_MASK	(OCC_SENSOR_TYPE_CURRENT | \
				 OCC_SENSOR_TYPE_VOLTAGE | \
				 OCC_SENSOR_TYPE_TEMPERATURE | \
				 OCC_SENSOR_TYPE_POWER)

/*
 * Standard HWMON linux interface expects the below units for the
 * environment sensors:
 * - Current		: milliampere
 * - Voltage		: millivolt
 * - Temperature	: millidegree Celsius (scaled in kernel)
 * - Power		: microWatt	      (scaled in kernel)
 * - Energy		: microJoule
 */

/*
 * OCC sensor units are obtained after scaling the sensor values.
 * https://github.com/open-power/occ/blob/master/src/occ_405/sensor/sensor_info.c
 */

static struct str_map {
	const char *occ_str;
	const char *opal_str;
} str_maps[] = {
	{"PWRSYS", "System"},
	/* Bulk power of the system: Watt */
	{"PWRFAN", "Fan"},
	/* Power consumption of the system fans: Watt */
	{"PWRIO", "IO"},
	/* Power consumption of the IO subsystem: Watt */
	{"PWRSTORE", "Storage"},
	/* Power comsumption of the storage subsystem: Watt */
	{"PWRGPU", "GPU"},
	/* Power consumption for GPUs per socket read from APSS: Watt */
	{"PWRAPSSCH", "APSS"},
	/* Power Provided by APSS channel x (where x=0…15): Watt */
	{"PWRPROC", ""},
	/* Power consumption for this Processor: Watt */
	{"PWRVDD", "Vdd"},
	/* Power consumption for this Processor's Vdd(AVSBus readings): Watt */
	{"PWRVDN", "Vdn"},
	/* Power consumption for  this Processor's Vdn (nest)
	 * Calculated from AVSBus readings: Watt */
	{"PWRMEM", "Memory"},
	/* Power consumption for Memory  for this Processor read from APSS:
	 * Watt */
	{"CURVDD", "Vdd"},
	/* Processor Vdd Current (read from AVSBus): Ampere */
	{"CURVDN", "Vdn"},
	/* Processor Vdn Current (read from AVSBus): Ampere */
	{"VOLTVDDSENSE", "Vdd Remote Sense"},
	/* Vdd Voltage at the remote sense.
	 * AVS reading adjusted for loadline: millivolt */
	{"VOLTVDNSENSE", "Vdn Remote Sense"},
	/* Vdn Voltage at the remote sense.
	 * AVS reading adjusted for loadline: millivolt */
	{"VOLTVDD", "Vdd"},
	/* Processor Vdd Voltage (read from AVSBus): millivolt */
	{"VOLTVDN", "Vdn"},
	/* Processor Vdn Voltage (read from AVSBus): millivolt */
	{"TEMPC", "Core"},
	/* Average temperature of core DTS sensors for Processor's Core y:
	 * Celsius */
	{"TEMPQ", "Quad"},
	/* Average temperature of quad (in cache) DTS sensors for
	 * Processor's Quad y: Celsius */
	{"TEMPNEST", "Nest"},
	/* Average temperature of nest DTS sensors: Celsius */
	{"TEMPPROCTHRMC", "Core"},
	/* The combined weighted core/quad temperature for processor core y:
	 * Celsius */
	{"TEMPDIMM", "DIMM"},
	/* DIMM temperature for DIMM x: Celsius */
	{"TEMPGPU", "GPU"},
	/* GPU x (0..2) board temperature: Celsius */
	/* TEMPGPUxMEM: GPU x hottest HBM temperature (individual memory
	 * temperatures are not available): Celsius */
	{"TEMPVDD", "VRM VDD"},
	/* VRM Vdd temperature: Celsius */
};

static u64 occ_sensor_base;

static inline
struct occ_sensor_data_header *get_sensor_header_block(int occ_num)
{
	return (struct occ_sensor_data_header *)
		(occ_sensor_base + occ_num * OCC_SENSOR_DATA_BLOCK_SIZE);
}

static inline
struct occ_sensor_name *get_names_block(struct occ_sensor_data_header *hb)
{
	return ((struct occ_sensor_name *)((u64)hb + hb->names_offset));
}

static inline u32 sensor_handler(int occ_num, int sensor_id, int attr)
{
	return sensor_make_handler(SENSOR_OCC, occ_num, sensor_id, attr);
}

/*
 * The scaling factor for the sensors is encoded in the below format:
 * (((UINT32)mantissa << 8) | (UINT32)((UINT8) 256 + (UINT8)exp))
 * https://github.com/open-power/occ/blob/master/src/occ_405/sensor/sensor.h
 */
static void scale_sensor(struct occ_sensor_name *md, u64 *sensor)
{
	u32 factor = md->scale_factor;
	int i;
	s8 exp;

	if (md->type == OCC_SENSOR_TYPE_CURRENT)
		*sensor *= 1000; //convert to mA

	*sensor *= factor >> 8;
	exp = factor & 0xFF;

	if (exp > 0) {
		for (i = labs(exp); i > 0; i--)
			*sensor *= 10;
	} else {
		for (i = labs(exp); i > 0; i--)
			*sensor /= 10;
	}
}

static void scale_energy(struct occ_sensor_name *md, u64 *sensor)
{
	u32 factor = md->freq;
	int i;
	s8 exp;

	*sensor *= 1000000; //convert to uJ

	*sensor /= factor >> 8;
	exp = factor & 0xFF;

	if (exp > 0) {
		for (i = labs(exp); i > 0; i--)
			*sensor /= 10;
	} else {
		for (i = labs(exp); i > 0; i--)
			*sensor *= 10;
	}
}

static u64 read_sensor(struct occ_sensor_record *sensor, int attr)
{
	switch (attr) {
	case SENSOR_SAMPLE:
		return sensor->sample;
	case SENSOR_SAMPLE_MIN:
		return sensor->sample_min;
	case SENSOR_SAMPLE_MAX:
		return sensor->sample_max;
	case SENSOR_CSM_MIN:
		return sensor->csm_min;
	case SENSOR_CSM_MAX:
		return sensor->csm_max;
	case SENSOR_ACCUMULATOR:
		return sensor->accumulator;
	default:
		break;
	}

	return 0;
}

static void *select_sensor_buffer(struct occ_sensor_data_header *hb, int id)
{
	struct occ_sensor_name *md;
	u8 *ping, *pong;
	void *buffer = NULL;

	if (!hb)
		return NULL;

	md = get_names_block(hb);

	ping = (u8 *)((u64)hb + hb->reading_ping_offset);
	pong = (u8 *)((u64)hb + hb->reading_pong_offset);

	/* Check which buffer is valid  and read the data from that.
	 * Ping Pong	Action
	 *  0	0	Return with error
	 *  0	1	Read Pong
	 *  1	0	Read Ping
	 *  1	1	Read the buffer with latest timestamp
	 */

	if (*ping && *pong) {
		u64 tping, tpong;
		u64 ping_buf = (u64)ping + md[id].reading_offset;
		u64 pong_buf = (u64)pong + md[id].reading_offset;

		tping = ((struct occ_sensor_record *)ping_buf)->timestamp;
		tpong = ((struct occ_sensor_record *)pong_buf)->timestamp;

		if (tping > tpong)
			buffer = ping;
		else
			buffer = pong;
	} else if (*ping && !*pong) {
		buffer = ping;
	} else if (!*ping && *pong) {
		buffer = pong;
	} else if (!*ping && !*pong) {
		prlog(PR_DEBUG, "OCC: Both ping and pong sensor buffers are invalid\n");
		return NULL;
	}

	assert(buffer);
	buffer = (void *)((u64)buffer + md[id].reading_offset);

	return buffer;
}

int occ_sensor_read(u32 handle, u64 *data)
{
	struct occ_sensor_data_header *hb;
	struct occ_sensor_name *md;
	u16 id = sensor_get_rid(handle);
	u8 occ_num = sensor_get_frc(handle);
	u8 attr = sensor_get_attr(handle);
	void *buff;

	if (occ_num > MAX_OCCS)
		return OPAL_PARAMETER;

	if (attr > MAX_SENSOR_ATTR)
		return OPAL_PARAMETER;

	if (is_occ_reset())
		return OPAL_HARDWARE;

	hb = get_sensor_header_block(occ_num);

	if (hb->valid != 1)
		return OPAL_HARDWARE;

	if (id > hb->nr_sensors)
		return OPAL_PARAMETER;

	buff = select_sensor_buffer(hb, id);
	if (!buff)
		return OPAL_HARDWARE;

	*data = read_sensor(buff, attr);
	if (!*data)
		return OPAL_SUCCESS;

	md = get_names_block(hb);
	if (md[id].type == OCC_SENSOR_TYPE_POWER && attr == SENSOR_ACCUMULATOR)
		scale_energy(&md[id], data);
	else
		scale_sensor(&md[id], data);

	return OPAL_SUCCESS;
}

static bool occ_sensor_sanity(struct occ_sensor_data_header *hb, int chipid)
{
	if (hb->valid != 0x01) {
		prerror("OCC: Chip %d sensor data invalid\n", chipid);
		return false;
	}

	if (hb->version != 0x01) {
		prerror("OCC: Chip %d unsupported sensor header block version %d\n",
			chipid, hb->version);
		return false;
	}

	if (hb->reading_version != 0x01) {
		prerror("OCC: Chip %d unsupported sensor record format %d\n",
			chipid, hb->reading_version);
		return false;
	}

	if (hb->names_version != 0x01) {
		prerror("OCC: Chip %d unsupported sensor names format %d\n",
			chipid, hb->names_version);
		return false;
	}

	if (hb->name_length != sizeof(struct occ_sensor_name)) {
		prerror("OCC: Chip %d unsupported sensor names length %d\n",
			chipid, hb->name_length);
		return false;
	}

	if (!hb->nr_sensors) {
		prerror("OCC: Chip %d has no sensors\n", chipid);
		return false;
	}

	if (!hb->names_offset || !hb->reading_ping_offset ||
	    !hb->reading_pong_offset) {
		prerror("OCC: Chip %d Invalid sensor buffer pointers\n",
			chipid);
		return false;
	}

	return true;
}

/*
 * parse_entity: Parses OCC sensor name to return the entity number like
 *		 chipid, core-id, dimm-no, gpu-no. 'end' is used to
 *		 get the subentity strings. Returns -1 if no number is found.
 *		 TEMPC4 --> returns 4, end will be NULL
 *		 TEMPGPU2DRAM1 --> returns 2, end = "DRAM1"
 *		 PWRSYS --> returns -1, end = NULL
 */
static int parse_entity(const char *name, char **end)
{
	while (*name != '\0') {
		if (isdigit(*name))
			break;
		name++;
	}

	if (*name)
		return strtol(name, end, 10);
	else
		return -1;
}

static void add_sensor_label(struct dt_node *node, struct occ_sensor_name *md,
			     int chipid)
{
	char sname[30] = "";
	char prefix[30] = "";
	int i;

	if (md->location != OCC_SENSOR_LOC_SYSTEM)
		snprintf(prefix, sizeof(prefix), "%s %d ", "Chip", chipid);

	for (i = 0; i < ARRAY_SIZE(str_maps); i++)
		if (!strncmp(str_maps[i].occ_str, md->name,
			     strlen(str_maps[i].occ_str))) {
			char *end;
			int num = -1;

			if (md->location != OCC_SENSOR_LOC_CORE)
				num = parse_entity(md->name, &end);

			if (num != -1) {
				snprintf(sname, sizeof(sname), "%s%s %d %s",
					 prefix, str_maps[i].opal_str, num,
					 end);
			} else {
				snprintf(sname, sizeof(sname), "%s%s", prefix,
					 str_maps[i].opal_str);
			}
			dt_add_property_string(node, "label", sname);
			return;
		}

	/* Fallback to OCC literal if mapping is not found */
	if (md->location == OCC_SENSOR_LOC_SYSTEM) {
		dt_add_property_string(node, "label", md->name);
	} else {
		snprintf(sname, sizeof(sname), "%s%s", prefix, md->name);
		dt_add_property_string(node, "label", sname);
	}
}

static const char *get_sensor_type_string(enum occ_sensor_type type)
{
	switch (type) {
	case OCC_SENSOR_TYPE_POWER:
		return "power";
	case OCC_SENSOR_TYPE_TEMPERATURE:
		return "temp";
	case OCC_SENSOR_TYPE_CURRENT:
		return "curr";
	case OCC_SENSOR_TYPE_VOLTAGE:
		return "in";
	default:
		break;
	}

	return "unknown";
}

static const char *get_sensor_loc_string(enum occ_sensor_location loc)
{
	switch (loc) {
	case OCC_SENSOR_LOC_SYSTEM:
		return "sys";
	case OCC_SENSOR_LOC_PROCESSOR:
		return "proc";
	case OCC_SENSOR_LOC_MEMORY:
		return "mem";
	case OCC_SENSOR_LOC_VRM:
		return "vrm";
	case OCC_SENSOR_LOC_CORE:
		return "core";
	case OCC_SENSOR_LOC_QUAD:
		return "quad";
	case OCC_SENSOR_LOC_GPU:
		return "gpu";
	default:
		break;
	}

	return "unknown";
}

/*
 * Power sensors can be 0 valued in few platforms like Zaius, Romulus
 * which do not have APSS. At the moment there is no HDAT/DT property
 * to indicate if APSS is present. So for now skip zero valued power
 * sensors.
 */
static bool check_sensor_sample(struct occ_sensor_data_header *hb, u32 offset)
{
	struct occ_sensor_record *ping, *pong;

	ping = (struct occ_sensor_record *)((u64)hb + hb->reading_ping_offset
					     + offset);
	pong = (struct occ_sensor_record *)((u64)hb + hb->reading_pong_offset
					     + offset);
	return ping->sample || pong->sample;
}

static void add_sensor_node(const char *loc, const char *type, int i, int attr,
			    struct occ_sensor_name *md, u32 *phandle, u32 *ptype,
			    u32 pir, u32 occ_num, u32 chipid)
{
	char name[30];
	struct dt_node *node;
	u32 handler;

	snprintf(name, sizeof(name), "%s-%s", loc, type);
	handler = sensor_handler(occ_num, i, attr);
	node = dt_new_addr(sensor_node, name, handler);
	dt_add_property_string(node, "sensor-type", type);
	dt_add_property_cells(node, "sensor-data", handler);
	dt_add_property_cells(node, "reg", handler);
	dt_add_property_string(node, "occ_label", md->name);
	add_sensor_label(node, md, chipid);

	if (md->location == OCC_SENSOR_LOC_CORE)
		dt_add_property_cells(node, "ibm,pir", pir);

	*ptype = md->type;

	if (attr == SENSOR_SAMPLE) {
		handler = sensor_handler(occ_num, i, SENSOR_CSM_MAX);
		dt_add_property_cells(node, "sensor-data-max", handler);

		handler = sensor_handler(occ_num, i, SENSOR_CSM_MIN);
		dt_add_property_cells(node, "sensor-data-min", handler);
	}

	dt_add_property_string(node, "compatible", "ibm,opal-sensor");
	*phandle = node->phandle;
}

bool occ_sensors_init(void)
{
	struct proc_chip *chip;
	struct dt_node *sg, *exports;
	int occ_num = 0, i;
	bool has_gpu = false;

	/* OCC inband sensors is only supported in P9 */
	if (proc_gen != proc_gen_p9)
		return false;

	/* Sensors are copied to BAR2 OCC Common Area */
	chip = next_chip(NULL);
	if (!chip->occ_common_base) {
		prerror("OCC: Unassigned OCC Common Area. No sensors found\n");
		return false;
	}

	occ_sensor_base = chip->occ_common_base + OCC_SENSOR_DATA_BLOCK_OFFSET;

	sg = dt_new(opal_node, "sensor-groups");
	if (!sg) {
		prerror("OCC: Failed to create sensor groups node\n");
		return false;
	}
	dt_add_property_string(sg, "compatible", "ibm,opal-sensor-group");
	dt_add_property_cells(sg, "#address-cells", 1);
	dt_add_property_cells(sg, "#size-cells", 0);

	if (dt_find_compatible_node(dt_root, NULL, "ibm,power9-npu"))
		has_gpu = true;

	for_each_chip(chip) {
		struct occ_sensor_data_header *hb;
		struct occ_sensor_name *md;
		u32 *phandles, *ptype, phcount = 0;

		hb = get_sensor_header_block(occ_num);
		md = get_names_block(hb);

		/* Sanity check of the Sensor Data Header Block */
		if (!occ_sensor_sanity(hb, chip->id))
			continue;

		phandles = malloc(hb->nr_sensors * sizeof(u32));
		assert(phandles);
		ptype = malloc(hb->nr_sensors * sizeof(u32));
		assert(ptype);

		for (i = 0; i < hb->nr_sensors; i++) {
			const char *type, *loc;
			struct cpu_thread *c = NULL;
			uint32_t pir = 0;

			if (md[i].structure_type != OCC_SENSOR_READING_FULL)
				continue;

			if (!(md[i].type & HWMON_SENSORS_MASK))
				continue;

			if (md[i].location == OCC_SENSOR_LOC_GPU && !has_gpu)
				continue;

			if (md[i].type == OCC_SENSOR_TYPE_POWER &&
			    !check_sensor_sample(hb, md[i].reading_offset))
				continue;

			if (md[i].location == OCC_SENSOR_LOC_CORE) {
				int num = parse_entity(md[i].name, NULL);

				for_each_available_core_in_chip(c, chip->id)
					if (pir_to_core_id(c->pir) == num)
						break;
				if (!c)
					continue;
				pir = c->pir;
			}

			type = get_sensor_type_string(md[i].type);
			loc = get_sensor_loc_string(md[i].location);

			add_sensor_node(loc, type, i, SENSOR_SAMPLE, &md[i],
					&phandles[phcount], &ptype[phcount],
					pir, occ_num, chip->id);
			phcount++;

			/* Add energy sensors */
			if (md[i].type == OCC_SENSOR_TYPE_POWER &&
			    md[i].structure_type == OCC_SENSOR_READING_FULL) {
				add_sensor_node(loc, "energy", i,
						SENSOR_ACCUMULATOR, &md[i],
						&phandles[phcount], &ptype[phcount],
						pir, occ_num, chip->id);
				phcount++;
			}

		}
		occ_num++;
		occ_add_sensor_groups(sg, phandles, ptype, phcount, chip->id);
		free(phandles);
		free(ptype);
	}

	if (!occ_num)
		return false;

	exports = dt_find_by_path(dt_root, "/ibm,opal/firmware/exports");
	if (!exports) {
		prerror("OCC: dt node /ibm,opal/firmware/exports not found\n");
		return false;
	}

	dt_add_property_u64s(exports, "occ_inband_sensors", occ_sensor_base,
			     OCC_SENSOR_DATA_BLOCK_SIZE * occ_num);

	return true;
}


text:
![Language](Zw.XmlLanguageEditor/Resources/fa-language_64_2_117aa2_none.png?raw=true)
# XmlLanguageEditor
Edit multiple XML or JSON files with a element-equals-language-id structure in parallel to each other

![Sample Screenshot](screenshot-example.png?raw=true)

Supports a simple flat file structure (XML) or simple object hierachies (JSON).

## Features

Currently supported features:
* Edit multiple XML language files side-by-side; open, save and close.
* Edit multiple JSON language files side-by-side; open, save and close.
* Optionaly hightlight invalid cells like missing values or values equal to master file.
* Supports single level XML files where the element name is the constant id.
* Supports simple object hierachy JSON files where the constant id is the path.
* Basic searching

Planned features:
* Adding new IDs/records
* Support for other XML formats


text:
package de.mrapp.android.dialog.listener;

import android.app.AlertDialog;
import android.content.DialogInterface.OnClickListener;
import android.view.View;

/**
 * A wrapper, which implements the interface
 * {@link android.view.View.OnClickListener} in order to delegate the method
 * calls to encapsulated listener of the type {@link OnClickListener}.
 *
 * @author Michael Rapp
 *
 * @since 1.0.0
 */
public class OnClickListenerWrapper extends AbstractListenerWrapper implements
		android.view.View.OnClickListener {

	/**
	 * The listener, which is encapsulated by the wrapper.
	 */
	private final OnClickListener wrappedListener;

	/**
	 * Creates a new wrapper, which implements the interface
	 * {@link android.view.View.OnClickListener} in order to delegate the method
	 * calls to encapsulated listener of the type {@link OnClickListener}.
	 *
	 * @param listener
	 *            The listener, which should be encapsulated by the wrapper, as
	 *            an instance of the type {@link OnClickListener}
	 * @param dialog
	 *            The dialog, the listener should belong to, as an instance of
	 *            the class {@link AlertDialog}
	 * @param buttonType
	 *            The type of the button or list item, the listener belongs to,
	 *            as an {@link Integer} value
	 */
	public OnClickListenerWrapper(final OnClickListener listener,
			final AlertDialog dialog, final int buttonType) {
		super(dialog, buttonType);
		this.wrappedListener = listener;
	}

	@Override
	public final void onClick(final View v) {
		if (wrappedListener != null) {
			wrappedListener.onClick(getDialog(), getButtonType());
		}

		attemptCloseDialog();
	}

}


text:
using SFA.DAS.EAS.Domain.Models.Transfers;
using SFA.DAS.EAS.Infrastructure.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SFA.DAS.EAS.Infrastructure.Extensions
{
    public static class EmployerFinancialDbContextExtensions
    {
        public static async Task<TransferAllowance> GetTransferAllowance(this EmployerFinanceDbContext db, long accountId, decimal transferAllowancePercentage)
        {
            var transferAllowance = await db.SqlQueryAsync<TransferAllowance>(
                "[employer_financial].[GetAccountTransferAllowance] @accountId = {0}, @allowancePercentage = {1}",
                accountId,
                transferAllowancePercentage).ConfigureAwait(false);

            return transferAllowance.SingleOrDefault() ?? new TransferAllowance();
        }
    }
}


text:
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.Activities.Presentation.FreeFormEditing
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Media;
    using System.Diagnostics.CodeAnalysis;

    [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "The class in used in xaml.")]
    class ConnectorLabelVisibilityConverter : IMultiValueConverter
    {

        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "The class is only used internally and not accessible externally.")]
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            Visibility connectorLabelVisibility = Visibility.Collapsed;
            string labelText = values[0] as string;
            PointCollection connectorPoints = values[1] as PointCollection;
            if (!String.IsNullOrEmpty(labelText) && connectorPoints != null)
            {
                int maxSegmentStartPoint;
                if (DesignerGeometryHelper.LongestSegmentLength(connectorPoints, out maxSegmentStartPoint) > Connector.MinConnectorSegmentLengthForLabel)
                {
                    connectorLabelVisibility = Visibility.Visible;
                }
            }
            return connectorLabelVisibility;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw FxTrace.Exception.AsError(new NotSupportedException());
        }

    }
}


text:
"""The WaveBlocks Project

This file contains some global defaults, for example file names for output files.
If a :py:class:`ParameterProvider` instance is asked about a key which it does not
know about it tries to look it up here to see if a default value is available.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

# Some global parameters related to file naming
path_to_autogen_configs = "autogen_configurations"
path_to_configs = "configurations"
path_to_results = "results"

ext_resultdatafile = ".hdf5"

file_metaconfiguration = "metaconfiguration.py"
file_resultdatafile = "simulation_results" + ext_resultdatafile
file_batchconfiguration = "batchconfiguration.py"

# Left, middle and right delimiter for key->value pairs
# encoded into file names (as used by the FileTools)
kvp_ldel = "["
kvp_mdel = "="
kvp_rdel = "]"

# Defaults for some internal initializations

# For creating Hagedorn wavepackets
default_Pi = [1.0j, 1.0, 0.0, 0.0, 0.0]
default_basis_size = 8

# Defaults for some simulation configuration parameters
try_simplification = False

# Try to make eigenvectors continuous
continuous_eigenvectors = True

# Matrix exponential algorithm
matrix_exponential = "arnoldi"
arnoldi_steps = 20

# Default values about when to save the results
write_nth = 0
save_at = []


text:
@implementation SRServer (Utils)

static BOOL isE = NO;

+ (void)enableLogging{
    isE = YES;
}

+ (void)disableLogging{
    isE = NO;
}

+ (BOOL)isLoggerEnabled{
    return isE;
}

@end


text:
/**
 *
 * @fileoverview
 * Generated from: test_files/parameter_properties/parameter_properties.ts
 * @suppress {uselessCode}
 *
 */
goog.module('test_files.parameter_properties.parameter_properties');
var module = module || { id: 'test_files/parameter_properties/parameter_properties.ts' };
goog.require('tslib');
class ParamProps {
    // The @export below should not show up in the output ctor.
    /**
     * @public
     * @param {string} publicExportedP
     * @param {string} publicP
     * @param {string} protectedP
     * @param {string} privateP
     * @param {string} readonlyP
     * @param {string} publicReadonlyP
     */
    constructor(publicExportedP, publicP, protectedP, privateP, readonlyP, publicReadonlyP) {
        this.publicExportedP = publicExportedP;
        this.publicP = publicP;
        this.protectedP = protectedP;
        this.privateP = privateP;
        this.readonlyP = readonlyP;
        this.publicReadonlyP = publicReadonlyP;
    }
}
/* istanbul ignore if */
if (false) {
    /**
     * @export
     * @type {string}
     */
    ParamProps.prototype.publicExportedP;
    /**
     * @type {string}
     * @public
     */
    ParamProps.prototype.publicP;
    /**
     * @type {string}
     * @protected
     */
    ParamProps.prototype.protectedP;
    /**
     * @type {string}
     * @private
     */
    ParamProps.prototype.privateP;
    /**
     * @const {string}
     * @public
     */
    ParamProps.prototype.readonlyP;
    /**
     * @const {string}
     * @public
     */
    ParamProps.prototype.publicReadonlyP;
}


text:
from rl_coach.agents.dfp_agent import DFPAgentParameters, HandlingTargetsAfterEpisodeEnd
from rl_coach.base_parameters import VisualizationParameters, PresetValidationParameters
from rl_coach.core_types import TrainingSteps, EnvironmentEpisodes, EnvironmentSteps
from rl_coach.environments.doom_environment import DoomEnvironmentParameters
from rl_coach.graph_managers.basic_rl_graph_manager import BasicRLGraphManager
from rl_coach.graph_managers.graph_manager import ScheduleParameters
from rl_coach.schedules import LinearSchedule

####################
# Graph Scheduling #
####################

schedule_params = ScheduleParameters()
schedule_params.improve_steps = TrainingSteps(10000000000)
schedule_params.steps_between_evaluation_periods = EnvironmentEpisodes(50)
schedule_params.evaluation_steps = EnvironmentEpisodes(3)

# There is no heatup for DFP. heatup length is determined according to batch size. See below.

#########
# Agent #
#########
agent_params = DFPAgentParameters()
schedule_params.heatup_steps = EnvironmentSteps(agent_params.network_wrappers['main'].batch_size)

agent_params.network_wrappers['main'].learning_rate = 0.0001
agent_params.exploration.epsilon_schedule = LinearSchedule(0.5, 0, 10000)
agent_params.exploration.evaluation_epsilon = 0

# this works better than the default which is 64
agent_params.algorithm.num_consecutive_playing_steps = EnvironmentSteps(1)

agent_params.algorithm.use_accumulated_reward_as_measurement = True
agent_params.algorithm.goal_vector = [0, 1]  # ammo, accumulated_reward
agent_params.algorithm.handling_targets_after_episode_end = HandlingTargetsAfterEpisodeEnd.LastStep

###############
# Environment #
###############
env_params = DoomEnvironmentParameters(level='basic')

########
# Test #
########
preset_validation_params = PresetValidationParameters()
preset_validation_params.trace_max_env_steps = 2000

graph_manager = BasicRLGraphManager(agent_params=agent_params, env_params=env_params,
                                    schedule_params=schedule_params, vis_params=VisualizationParameters(),
                                    preset_validation_params=preset_validation_params)


text:
import { Pipe, PipeTransform } from '@angular/core';
import { TableRowWithMetadata } from '../../models/content';

@Pipe({ name: 'filterDeletedDatagridRow', pure: true })
export class FilterDeletedDatagridRowPipe implements PipeTransform {
  public transform(row: TableRowWithMetadata) {
    return row.isDeleted ? ['row-deleted'] : [];
  }
}


text:
package a_vcard.android.syncml.pim.vcard;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import a_vcard.android.provider.Contacts;
import a_vcard.android.syncml.pim.vcard.ContactStruct.PhoneData;

/**
 * Compose VCard string
 */
public class VCardComposer {
    final public static int VERSION_VCARD21_INT = 1;

    final public static int VERSION_VCARD30_INT = 2;

    /**
     * A new line
     */
    private String mNewline;

    /**
     * The composed string
     */
    private StringBuilder mResult;

    /**
     * The email's type
     */
    static final private HashSet<String> emailTypes = new HashSet<String>(
            Arrays.asList("CELL", "AOL", "APPLELINK", "ATTMAIL", "CIS",
                    "EWORLD", "INTERNET", "IBMMAIL", "MCIMAIL", "POWERSHARE",
                    "PRODIGY", "TLX", "X400"));

    static final private HashSet<String> phoneTypes = new HashSet<String>(
            Arrays.asList("PREF", "WORK", "HOME", "VOICE", "FAX", "MSG",
                    "CELL", "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO"));

    static final private String TAG = "VCardComposer";

    public VCardComposer() {
    }

    private static final HashMap<Integer, String> phoneTypeMap = new HashMap<Integer, String>();

    private static final HashMap<Integer, String> emailTypeMap = new HashMap<Integer, String>();

    static {
        phoneTypeMap.put(Contacts.Phones.TYPE_HOME, "HOME");
        phoneTypeMap.put(Contacts.Phones.TYPE_MOBILE, "CELL");
        phoneTypeMap.put(Contacts.Phones.TYPE_WORK, "WORK");
        // FAX_WORK not exist in vcard spec. The approximate is the combine of
        // WORK and FAX, here only map to FAX
        phoneTypeMap.put(Contacts.Phones.TYPE_FAX_WORK, "WORK;FAX");
        phoneTypeMap.put(Contacts.Phones.TYPE_FAX_HOME, "HOME;FAX");
        phoneTypeMap.put(Contacts.Phones.TYPE_PAGER, "PAGER");
        phoneTypeMap.put(Contacts.Phones.TYPE_OTHER, "X-OTHER");
        emailTypeMap.put(Contacts.ContactMethods.TYPE_HOME, "HOME");
        emailTypeMap.put(Contacts.ContactMethods.TYPE_WORK, "WORK");
    }

    /**
     * Create a vCard String.
     *
     * @param struct
     *            see more from ContactStruct class
     * @param vcardversion
     *            MUST be VERSION_VCARD21 /VERSION_VCARD30
     * @return vCard string
     * @throws VCardException
     *             struct.name is null /vcardversion not match
     */
    public String createVCard(ContactStruct struct, int vcardversion)
            throws VCardException {

        mResult = new StringBuilder();
        // check exception:
        if (struct.name == null || struct.name.trim().equals("")) {
            throw new VCardException(" struct.name MUST have value.");
        }
        if (vcardversion == VERSION_VCARD21_INT) {
            mNewline = "\r\n";
        } else if (vcardversion == VERSION_VCARD30_INT) {
            mNewline = "\n";
        } else {
            throw new VCardException(
                    " version not match VERSION_VCARD21 or VERSION_VCARD30.");
        }
        // build vcard:
        mResult.append("BEGIN:VCARD").append(mNewline);

        if (vcardversion == VERSION_VCARD21_INT) {
            mResult.append("VERSION:2.1").append(mNewline);
        } else {
            mResult.append("VERSION:3.0").append(mNewline);
        }

        if (!isNull(struct.name)) {
            appendNameStr(struct.name);
        }

        if (!isNull(struct.company)) {
            mResult.append("ORG:").append(struct.company).append(mNewline);
        }

        if (struct.notes.size() > 0 && !isNull(struct.notes.get(0))) {
            mResult.append("NOTE:").append(
                    foldingString(struct.notes.get(0), vcardversion)).append(mNewline);
        }

        if (!isNull(struct.title)) {
            mResult.append("TITLE:").append(
                    foldingString(struct.title, vcardversion)).append(mNewline);
        }

        if (struct.photoBytes != null) {
            appendPhotoStr(struct.photoBytes, struct.photoType, vcardversion);
        }

        if (struct.phoneList != null) {
            appendPhoneStr(struct.phoneList, vcardversion);
        }

        if (struct.contactmethodList != null) {
            appendContactMethodStr(struct.contactmethodList, vcardversion);
        }

        mResult.append("END:VCARD").append(mNewline);
        return mResult.toString();
    }

    /**
     * Alter str to folding supported format.
     *
     * @param str
     *            the string to be folded
     * @param version
     *            the vcard version
     * @return the folded string
     */
    private String foldingString(String str, int version) {
        if (str.endsWith("\r\n")) {
            str = str.substring(0, str.length() - 2);
        } else if (str.endsWith("\n")) {
            str = str.substring(0, str.length() - 1);
        } else {
            return null;
        }

        str = str.replaceAll("\r\n", "\n");
        if (version == VERSION_VCARD21_INT) {
            return str.replaceAll("\n", "\r\n ");
        } else if (version == VERSION_VCARD30_INT) {
            return str.replaceAll("\n", "\n ");
        } else {
            return null;
        }
    }

    /**
     * Build LOGO property. format LOGO's param and encode value as base64.
     *
     * @param bytes
     *            the binary string to be converted
     * @param type
     *            the type of the content
     * @param version
     *            the version of vcard
     */
    private void appendPhotoStr(byte[] bytes, String type, int version)
            throws VCardException {
        String value, encodingStr;
        try {
            value = foldingString(new String(Base64.encodeBase64(bytes, true)),
                    version);
        } catch (Exception e) {
            throw new VCardException(e.getMessage());
        }

        if (isNull(type) || type.toUpperCase().indexOf("JPEG") >= 0) {
            type = "JPEG";
        } else if (type.toUpperCase().indexOf("GIF") >= 0) {
            type = "GIF";
        } else if (type.toUpperCase().indexOf("BMP") >= 0) {
            type = "BMP";
        } else {
            // Handle the string like "image/tiff".
            int indexOfSlash = type.indexOf("/");
            if (indexOfSlash >= 0) {
                type = type.substring(indexOfSlash + 1).toUpperCase();
            } else {
                type = type.toUpperCase();
            }
        }

        mResult.append("LOGO;TYPE=").append(type);
        if (version == VERSION_VCARD21_INT) {
            encodingStr = ";ENCODING=BASE64:";
            value = value + mNewline;
        } else if (version == VERSION_VCARD30_INT) {
            encodingStr = ";ENCODING=b:";
        } else {
            return;
        }
        mResult.append(encodingStr).append(value).append(mNewline);
    }

    private boolean isNull(String str) {
        if (str == null || str.trim().equals("")) {
            return true;
        }
        return false;
    }

    /**
     * Build FN and N property. format N's value.
     *
     * @param name
     *            the name of the contact
     */
    private void appendNameStr(String name) {
        mResult.append("FN:").append(name).append(mNewline);
        mResult.append("N:").append(name).append(mNewline);
        /*
         * if(name.indexOf(";") > 0)
         * mResult.append("N:").append(name).append(mNewline); else
         * if(name.indexOf(" ") > 0) mResult.append("N:").append(name.replace(' ',
         * ';')). append(mNewline); else
         * mResult.append("N:").append(name).append("; ").append(mNewline);
         */
    }

    /** Loop append TEL property. */
    private void appendPhoneStr(List<ContactStruct.PhoneData> phoneList,
            int version) {
        HashMap<String, String> numMap = new HashMap<String, String>();
        String joinMark = version == VERSION_VCARD21_INT ? ";" : ",";

        for (ContactStruct.PhoneData phone : phoneList) {
            String type;
            if (!isNull(phone.data)) {
                type = getPhoneTypeStr(phone);
                if (version == VERSION_VCARD30_INT && type.indexOf(";") != -1) {
                    type = type.replace(";", ",");
                }
                if (numMap.containsKey(phone.data)) {
                    type = numMap.get(phone.data) + joinMark + type;
                }
                numMap.put(phone.data, type);
            }
        }

        for (Map.Entry<String, String> num : numMap.entrySet()) {
            if (version == VERSION_VCARD21_INT) {
                mResult.append("TEL;");
            } else { // vcard3.0
                mResult.append("TEL;TYPE=");
            }
            mResult.append(num.getValue()).append(":").append(num.getKey())
                    .append(mNewline);
        }
    }

    private String getPhoneTypeStr(PhoneData phone) {

        int phoneType = phone.type;
        String typeStr, label;

        if (phoneTypeMap.containsKey(phoneType)) {
            typeStr = phoneTypeMap.get(phoneType);
        } else if (phoneType == Contacts.Phones.TYPE_CUSTOM) {
            label = phone.label.toUpperCase();
            if (phoneTypes.contains(label) || label.startsWith("X-")) {
                typeStr = label;
            } else {
                typeStr = "X-CUSTOM-" + label;
            }
        } else {
            // TODO: need be updated with the provider's future changes
            typeStr = "VOICE"; // the default type is VOICE in spec.
        }
        return typeStr;
    }

    /** Loop append ADR / EMAIL property. */
    private void appendContactMethodStr(
            List<ContactStruct.ContactMethod> contactMList, int version) {

        HashMap<String, String> emailMap = new HashMap<String, String>();
        String joinMark = version == VERSION_VCARD21_INT ? ";" : ",";
        for (ContactStruct.ContactMethod contactMethod : contactMList) {
            // same with v2.1 and v3.0
            switch (contactMethod.kind) {
            case Contacts.KIND_EMAIL:
                String mailType = "INTERNET";
                if (!isNull(contactMethod.data)) {
                    int methodType = new Integer(contactMethod.type).intValue();
                    if (emailTypeMap.containsKey(methodType)) {
                        mailType = emailTypeMap.get(methodType);
                    } else if (emailTypes.contains(contactMethod.label
                            .toUpperCase())) {
                        mailType = contactMethod.label.toUpperCase();
                    }
                    if (emailMap.containsKey(contactMethod.data)) {
                        mailType = emailMap.get(contactMethod.data) + joinMark
                                + mailType;
                    }
                    emailMap.put(contactMethod.data, mailType);
                }
                break;
            case Contacts.KIND_POSTAL:
                if (!isNull(contactMethod.data)) {
                    mResult.append("ADR;TYPE=POSTAL:").append(
                            foldingString(contactMethod.data, version)).append(
                            mNewline);
                }
                break;
            default:
                break;
            }
        }
        for (Map.Entry<String, String> email : emailMap.entrySet()) {
            if (version == VERSION_VCARD21_INT) {
                mResult.append("EMAIL;");
            } else {
                mResult.append("EMAIL;TYPE=");
            }
            mResult.append(email.getValue()).append(":").append(email.getKey())
                    .append(mNewline);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Label Tabs</title>
    <link href="css/labelTabs.css" rel="stylesheet" type="text/css" />

    <form id="form1">
        Text Field

        <input type="text" id="textField" />

        Select an Option

        <select id="list">
            <option value="" selected></option>
            <option value="item1">Item 1</option>
            <option value="item2">Item 2 with a long name</option>
            <option value="item3">Item 3</option>
        </select>

        Text Area

        <textarea id="textbox" cols="60" rows="5" style="width:200px; height:180px;"></textarea>
    </form>


text:
The Lua platform uses Lua 5.3 and latest LuaRocks available.

## Code deployment with dependencies

We're using Luarocks to manage packages for Lua, and tsuru will expect
for a file called `tsuru-1.0-1.rockspec` for dependencies definitions.


text:
<?xml version='1.0' encoding='UTF-8'?>
<para xmlns="http://docbook.org/ns/docbook" version="5.0">

Description of meta configuration options

    <col width="50%"/>
    <col width="50%"/>

        Configuration option = Default value
        Description

        [META]

        <option>default_flavor</option> = <replaceable></replaceable>
        (StrOpt) Default flavor to use, when flavor:network is not specified at network creation.

        <option>default_l3_flavor</option> = <replaceable></replaceable>
        (StrOpt) Default L3 flavor to use, when flavor:router is not specified at router creation. Ignored if 'l3_plugin_list' is blank.

        <option>extension_map</option> = <replaceable></replaceable>
        (StrOpt) Comma separated list of method:flavor to select specific plugin for a method. This has priority over method search order based on 'plugin_list'.

        <option>l3_plugin_list</option> = <replaceable></replaceable>
        (StrOpt) Comma separated list of flavor:neutron_plugin for L3 service plugins to load. This is intended for specifying L2 plugins which support L3 functions. If you use a router service plugin, set this blank.

        <option>plugin_list</option> = <replaceable></replaceable>
        (StrOpt) Comma separated list of flavor:neutron_plugin for plugins to load. Extension method is searched in the list order and the first one is used.

        <option>rpc_flavor</option> = <replaceable></replaceable>
        (StrOpt) Specifies flavor for plugin to handle 'q-plugin' RPC requests.

        <option>supported_extension_aliases</option> = <replaceable></replaceable>
        (StrOpt) Comma separated list of supported extension aliases.

</para>


text:
package io.quarkus.dev.spi;

public interface DeploymentFailedStartHandler {

    /**
     * This method is called if the app fails to start the first time. This allows for hot deployment
     * providers to still start, and provide a way for the user to recover their app
     */
    void handleFailedInitialStart();

}


text:
var _ = require('lodash')

var calcs = require('homegrown-sailing').Calcs;
var delayedInputs = require('homegrown-sailing').Utilities.delayedInputs;

exports.load = function(server, boatData, settings) {
    console.info("calcs:loaded")

    var functions = [
        //TODO: how to ignore system tws and direction?
        delayedInputs(calcs.tws),
        delayedInputs(calcs.twa),
        delayedInputs(calcs.twd),
        delayedInputs(calcs.vmg)
    ];
    var setX = delayedInputs(calcs.set);
    var driftX = delayedInputs(calcs.drift);

    boatData.on('data', function(data) {
        var syntheticData = {};

        // call calculation functions on new data point
        _.each(functions, function(f) {
            var result = f(_.assign({}, data, syntheticData));

            if (result) {
                _.extend(syntheticData, result);
            }
        });

        //if any of the functions had results, broadcast them
        if ( _.size(syntheticData) ) {
            boatData.broadcast(syntheticData);
        }

        //calc set and drift seperately.
        var set = setX(data);
        var drift = driftX(data);
        if (set) {
            //broadcast the new bit of data. boatData will handle
            //NMEA formatting.
            boatData.broadcast(_.extend({type: 'vdr'}, set, drift));
        }
    });
};


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace StatsViewer
{
  /// <summary>
  /// The stats table shared memory segment contains this
  /// header structure.
  /// </summary>
  [StructLayout(LayoutKind.Sequential)]
  internal struct StatsFileHeader {
    public int version;
    public int size;
    public int max_counters;
    public int max_threads;
  };

  /// <summary>
  /// An entry in the StatsTable.
  /// </summary>
  class StatsTableEntry {
    public StatsTableEntry(int id, string name, StatsTable table) {
      id_ = id;
      name_ = name;
      table_ = table;
    }

    /// <summary>
    /// The unique id for this entry
    /// </summary>
    public int id { get { return id_; } }

    /// <summary>
    /// The name for this entry.
    /// </summary>
    public string name { get { return name_; } }

    /// <summary>
    /// The value of this entry now.
    /// </summary>
    public int GetValue(int filter_pid) {
      return table_.GetValue(id_, filter_pid);
    }

    private int id_;
    private string name_;
    private StatsTable table_;
  }

  // An interface for StatsCounters
  interface IStatsCounter {
    // The name of the counter
    string name { get; }
  }

  // A counter.
  class StatsCounter : IStatsCounter {
    public StatsCounter(StatsTableEntry entry) {
      entry_ = entry;
    }

    public string name {
      get {
        return entry_.name;
      }
    }

    public int GetValue(int filter_pid) {
      return entry_.GetValue(filter_pid);
    }

    private StatsTableEntry entry_;
  }

  // A timer.
  class StatsTimer : IStatsCounter {
    public StatsTimer(StatsTableEntry entry)
    {
      entry_ = entry;
    }

    public string name {
      get {
        return entry_.name;
      }
    }

    public int GetValue(int filter_pid) {
      return entry_.GetValue(filter_pid);
    }

    private StatsTableEntry entry_;
  }

  // A rate.
  class StatsCounterRate : IStatsCounter
  {
    public StatsCounterRate(StatsCounter counter, StatsTimer timer) {
      counter_ = counter;
      timer_ = timer;
    }

    public string name { get { return counter_.name; } }

    public int GetCount(int filter_pid) {
      return counter_.GetValue(filter_pid);
    }

    public int GetTime(int filter_pid) {
      return timer_.GetValue(filter_pid);
    }

    private StatsCounter counter_;
    private StatsTimer timer_;
  }

  /// <summary>
  /// This is a C# reader for the chrome stats_table.
  /// </summary>
  class StatsTable {
    internal const int kMaxThreadNameLength = 32;
    internal const int kMaxCounterNameLength = 32;

    /// <summary>
    /// Open a StatsTable
    /// </summary>
    public StatsTable() {
    }

    #region Public Properties
    /// <summary>
    /// Get access to the counters in the table.
    /// </summary>
    public StatsTableCounters Counters() {
      return new StatsTableCounters(this);
    }

    /// <summary>
    /// Get access to the processes in the table
    /// </summary>
    public ICollection Processes {
      get {
        return new StatsTableProcesses(this);
      }
    }
    #endregion

    #region Internal Properties
    //
    // The internal methods are accessible to the enumerators
    // and helper classes below.
    //

    /// <summary>
    /// Access to the table header
    /// </summary>
    internal StatsFileHeader Header {
      get { return header_; }
    }

    /// <summary>
    /// Get the offset of the ThreadName table
    /// </summary>
    internal long ThreadNamesOffset {
      get {
        return memory_.ToInt64() + Marshal.SizeOf(typeof(StatsFileHeader));
      }
    }

    /// <summary>
    /// Get the offset of the PIDs table
    /// </summary>
    internal long PidsOffset {
      get {
        long offset = ThreadNamesOffset;
        // Thread names table
        offset += AlignedSize(header_.max_threads * kMaxThreadNameLength * 2);
        // Thread TID table
        offset += AlignedSize(header_.max_threads *
          Marshal.SizeOf(typeof(int)));
        return offset;
      }
    }

    /// <summary>
    /// Get the offset of the CounterName table
    /// </summary>
    internal long CounterNamesOffset {
      get {
        long offset = PidsOffset;
        // Thread PID table
        offset += AlignedSize(header_.max_threads *
          Marshal.SizeOf(typeof(int)));
        return offset;
      }
    }

    /// <summary>
    /// Get the offset of the Data table
    /// </summary>
    internal long DataOffset {
      get {
        long offset = CounterNamesOffset;
        // Counter names table
        offset += AlignedSize(header_.max_counters *
          kMaxCounterNameLength * 2);
        return offset;
      }
    }
    #endregion

    #region Public Methods
    /// <summary>
    /// Opens the memory map
    /// </summary>
    /// <returns></returns>
    /// <param name="name">The name of the file to open</param>
    public bool Open(string name) {
      map_handle_ =
        Win32.OpenFileMapping((int)Win32.MapAccess.FILE_MAP_WRITE, false,
                              name);
      if (map_handle_ == IntPtr.Zero)
        return false;

      memory_ =
        Win32.MapViewOfFile(map_handle_, (int)Win32.MapAccess.FILE_MAP_WRITE,
                            0,0, 0);
      if (memory_ == IntPtr.Zero) {
        Win32.CloseHandle(map_handle_);
        return false;
      }

      header_ = (StatsFileHeader)Marshal.PtrToStructure(memory_, header_.GetType());
      return true;
    }

    /// <summary>
    /// Close the mapped file.
    /// </summary>
    public void Close() {
      Win32.UnmapViewOfFile(memory_);
      Win32.CloseHandle(map_handle_);
    }

    /// <summary>
    /// Zero out the stats file.
    /// </summary>
    public void Zero() {
      long offset = DataOffset;
      for (int threads = 0; threads < header_.max_threads; threads++) {
        for (int counters = 0; counters < header_.max_counters; counters++) {
          Marshal.WriteInt32((IntPtr) offset, 0);
          offset += Marshal.SizeOf(typeof(int));
        }
      }
    }

    /// <summary>
    /// Get the value for a StatsCounterEntry now.
    /// </summary>
    /// <returns></returns>
    /// <param name="filter_pid">If a specific PID is being queried, filter to this PID.  0 means use all data.</param>
    /// <param name="id">The id of the CounterEntry to get the value for.</param>
    public int GetValue(int id, int filter_pid) {
      long pid_offset = PidsOffset;
      long data_offset = DataOffset;
      data_offset += id * (Header.max_threads *
        Marshal.SizeOf(typeof(int)));
      int rv = 0;
      for (int cols = 0; cols < Header.max_threads; cols++)
      {
        int pid = Marshal.ReadInt32((IntPtr)pid_offset);
        if (filter_pid == 0 || filter_pid == pid)
        {
          rv += Marshal.ReadInt32((IntPtr)data_offset);
        }
        data_offset += Marshal.SizeOf(typeof(int));
        pid_offset += Marshal.SizeOf(typeof(int));
      }
      return rv;
    }
    #endregion

    #region Private Methods
    /// <summary>
    /// Align to 4-byte boundaries
    /// </summary>
    /// <param name="size"></param>
    /// <returns></returns>
    private long AlignedSize(long size) {
      Debug.Assert(sizeof(int) == 4);
      return size + (sizeof(int) - (size % sizeof(int))) % sizeof(int);
    }
    #endregion

    #region Private Members
    private IntPtr memory_;
    private IntPtr map_handle_;
    private StatsFileHeader header_;
    #endregion
  }

  /// <summary>
  /// Enumerable list of Counters in the StatsTable
  /// </summary>
  class StatsTableCounters : ICollection {
    /// <summary>
    /// Create the list of counters
    /// </summary>
    /// <param name="table"></param>
    /// pid</param>
    public StatsTableCounters(StatsTable table) {
      table_ = table;
      counter_hi_water_mark_ = -1;
      counters_ = new List<IStatsCounter>();
      FindCounters();
    }

    /// <summary>
    /// Scans the table for new entries.
    /// </summary>
    public void Update() {
      FindCounters();
    }

    #region IEnumerable Members
    public IEnumerator GetEnumerator() {
      return counters_.GetEnumerator();
    }
    #endregion

    #region ICollection Members
    public void CopyTo(Array array, int index) {
      throw new Exception("The method or operation is not implemented.");
    }

    public int Count {
      get {
        return counters_.Count;
      }
    }

    public bool IsSynchronized {
      get {
        throw new Exception("The method or operation is not implemented.");
      }
    }

    public object SyncRoot {
      get {
        throw new Exception("The method or operation is not implemented.");
      }
    }
    #endregion

    #region Private Methods
    /// <summary>
    /// Create a counter based on an entry
    /// </summary>
    /// <param name="id"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    private IStatsCounter NameToCounter(int id, string name)
    {
      IStatsCounter rv = null;

      // check if the name has a type encoded
      if (name.Length > 2 && name[1] == ':')
      {
        StatsTableEntry entry = new StatsTableEntry(id, name.Substring(2), table_);
        switch (name[0])
        {
          case 't':
            rv = new StatsTimer(entry);
            break;
          case 'c':
            rv = new StatsCounter(entry);
            break;
        }
      }
      else
      {
        StatsTableEntry entry = new StatsTableEntry(id, name, table_);
        rv = new StatsCounter(entry);
      }

      return rv;
    }

    // If we have two StatsTableEntries with the same name,
    // attempt to upgrade them to a higher level type.
    // Example:  A counter + a timer == a rate!
    private void UpgradeCounter(IStatsCounter old_counter, IStatsCounter counter)
    {
      if (old_counter is StatsCounter && counter is StatsTimer)
      {
        StatsCounterRate rate = new StatsCounterRate(old_counter as StatsCounter,
                                          counter as StatsTimer);
        counters_.Remove(old_counter);
        counters_.Add(rate);
      }
      else if (old_counter is StatsTimer && counter is StatsCounter)
      {
        StatsCounterRate rate = new StatsCounterRate(counter as StatsCounter,
                                         old_counter as StatsTimer);
        counters_.Remove(old_counter);
        counters_.Add(rate);
      }
    }

    /// <summary>
    /// Find the counters in the table and insert into the counters_
    /// hash table.
    /// </summary>
    private void FindCounters()
    {
      Debug.Assert(table_.Header.max_counters > 0);

      int index = counter_hi_water_mark_;

      do
      {
        // Find an entry in the table.
        index++;
        long offset = table_.CounterNamesOffset +
          (index * StatsTable.kMaxCounterNameLength * 2);
        string name = Marshal.PtrToStringUni((IntPtr)offset);
        if (name.Length == 0)
          continue;

        // Record that we've already looked at this StatsTableEntry.
        counter_hi_water_mark_ = index;

        IStatsCounter counter = NameToCounter(index, name);

        if (counter != null)
        {
          IStatsCounter old_counter = FindExistingCounter(counter.name);
          if (old_counter != null)
            UpgradeCounter(old_counter, counter);
          else
            counters_.Add(counter);
        }
      } while (index < table_.Header.max_counters - 1);
    }

    /// <summary>
    /// Find an existing counter in our table
    /// </summary>
    /// <param name="name"></param>
    private IStatsCounter FindExistingCounter(string name) {
      foreach (IStatsCounter ctr in counters_)
      {
        if (ctr.name == name)
          return ctr;
      }
      return null;
    }
    #endregion

    #region Private Members
    private StatsTable table_;
    private List<IStatsCounter> counters_;
    // Highest index of counters processed.
    private int counter_hi_water_mark_;
    #endregion
  }

  /// <summary>
  /// A collection of processes
  /// </summary>
  class StatsTableProcesses : ICollection
  {
    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="table"></param>
    public StatsTableProcesses(StatsTable table) {
      table_ = table;
      pids_ = new List<int>();
      Initialize();
    }

    #region ICollection Members
    public void CopyTo(Array array, int index) {
      throw new Exception("The method or operation is not implemented.");
    }

    public int Count {
      get {
        return pids_.Count;
      }
    }

    public bool IsSynchronized {
      get {
        throw new Exception("The method or operation is not implemented.");
      }
    }

    public object SyncRoot {
      get {
        throw new Exception("The method or operation is not implemented.");
      }
    }
    #endregion

    #region IEnumerable Members
    public IEnumerator GetEnumerator() {
      return pids_.GetEnumerator();
    }
    #endregion

    /// <summary>
    /// Initialize the pid list.
    /// </summary>
    private void Initialize() {
      long offset = table_.ThreadNamesOffset;

      for (int index = 0; index < table_.Header.max_threads; index++) {
        string thread_name = Marshal.PtrToStringUni((IntPtr)offset);
        if (thread_name.Length > 0) {
          long pidOffset = table_.PidsOffset + index *
            Marshal.SizeOf(typeof(int));
          int pid = Marshal.ReadInt32((IntPtr)pidOffset);
          if (!pids_.Contains(pid))
            pids_.Add(pid);
        }
        offset += StatsTable.kMaxThreadNameLength * 2;
      }
    }

    #region Private Members
    private StatsTable table_;
    private List<int> pids_;
    #endregion
  }
}


text:
#ifndef BACKEND_DRM_DRM_H
#define BACKEND_DRM_DRM_H

#include <EGL/egl.h>
#include <gbm.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <time.h>
#include <wayland-server-core.h>
#include <wayland-util.h>
#include <wlr/backend/drm.h>
#include <wlr/backend/session.h>
#include <wlr/render/drm_format_set.h>
#include <wlr/render/egl.h>
#include <xf86drmMode.h>
#include "iface.h"
#include "properties.h"
#include "renderer.h"

struct wlr_drm_plane {
	uint32_t type;
	uint32_t id;

	struct wlr_drm_surface surf;
	struct wlr_drm_surface mgpu_surf;

	/* Buffer to be submitted to the kernel on the next page-flip */
	struct wlr_drm_fb pending_fb;
	/* Buffer submitted to the kernel, will be presented on next vblank */
	struct wlr_drm_fb queued_fb;
	/* Buffer currently displayed on screen */
	struct wlr_drm_fb current_fb;

	uint32_t drm_format; // ARGB8888 or XRGB8888
	struct wlr_drm_format_set formats;

	// Only used by cursor
	bool cursor_enabled;
	int32_t cursor_hotspot_x, cursor_hotspot_y;

	union wlr_drm_plane_props props;
};

struct wlr_drm_crtc_state {
	bool active;
	struct wlr_drm_mode *mode;
};

struct wlr_drm_crtc {
	uint32_t id;

	bool pending_modeset;
	struct wlr_drm_crtc_state pending, current;

	// Atomic modesetting only
	uint32_t mode_id;
	uint32_t gamma_lut;

	// Legacy only
	drmModeCrtc *legacy_crtc;

	struct wlr_drm_plane *primary;
	struct wlr_drm_plane *cursor;

	/*
	 * We don't support overlay planes yet, but we keep track of them to
	 * give to DRM lease clients.
	 */
	size_t num_overlays;
	uint32_t *overlays;

	union wlr_drm_crtc_props props;
};

struct wlr_drm_backend {
	struct wlr_backend backend;

	struct wlr_drm_backend *parent;
	const struct wlr_drm_interface *iface;
	clockid_t clock;
	bool addfb2_modifiers;

	int fd;

	size_t num_crtcs;
	struct wlr_drm_crtc *crtcs;

	struct wl_display *display;
	struct wl_event_source *drm_event;

	struct wl_listener display_destroy;
	struct wl_listener session_destroy;
	struct wl_listener session_signal;
	struct wl_listener drm_invalidated;

	struct wl_list outputs;

	struct wlr_drm_renderer renderer;
	struct wlr_session *session;
};

enum wlr_drm_connector_state {
	// Connector is available but no output is plugged in
	WLR_DRM_CONN_DISCONNECTED,
	// An output just has been plugged in and is waiting for a modeset
	WLR_DRM_CONN_NEEDS_MODESET,
	WLR_DRM_CONN_CLEANUP,
	WLR_DRM_CONN_CONNECTED,
};

struct wlr_drm_mode {
	struct wlr_output_mode wlr_mode;
	drmModeModeInfo drm_mode;
};

struct wlr_drm_connector {
	struct wlr_output output;

	enum wlr_drm_connector_state state;
	struct wlr_output_mode *desired_mode;
	bool desired_enabled;
	uint32_t id;

	struct wlr_drm_crtc *crtc;
	uint32_t possible_crtc;

	union wlr_drm_connector_props props;

	int32_t cursor_x, cursor_y;

	drmModeCrtc *old_crtc;

	struct wl_list link;

	/*
	 * We've asked for a state change in the kernel, and yet to recieve a
	 * notification for its completion. Currently, the kernel only has a
	 * queue length of 1, and no way to modify your submissions after
	 * they're sent.
	 */
	bool pageflip_pending;
};

struct wlr_drm_backend *get_drm_backend_from_backend(
	struct wlr_backend *wlr_backend);
bool check_drm_features(struct wlr_drm_backend *drm);
bool init_drm_resources(struct wlr_drm_backend *drm);
void finish_drm_resources(struct wlr_drm_backend *drm);
void restore_drm_outputs(struct wlr_drm_backend *drm);
void scan_drm_connectors(struct wlr_drm_backend *state);
int handle_drm_event(int fd, uint32_t mask, void *data);
bool drm_connector_set_mode(struct wlr_drm_connector *conn,
	struct wlr_output_mode *mode);
bool drm_connector_is_cursor_visible(struct wlr_drm_connector *conn);
bool drm_connector_supports_vrr(struct wlr_drm_connector *conn);
size_t drm_crtc_get_gamma_lut_size(struct wlr_drm_backend *drm,
	struct wlr_drm_crtc *crtc);

struct wlr_drm_fb *plane_get_next_fb(struct wlr_drm_plane *plane);

#endif


text:
namespace factor {

code_heap::code_heap(cell size) {
  if (size > ((uint64_t)1 << (sizeof(cell) * 8 - 5)))
    fatal_error("Heap too large", size);
  seg = new segment(align_page(size), true);
  if (!seg)
    fatal_error("Out of memory in code_heap constructor", size);

  cell start = seg->start + getpagesize() + seh_area_size;

  allocator = new free_list_allocator<code_block>(seg->end - start, start);

  // See os-windows-x86.64.cpp for seh_area usage
  safepoint_page = seg->start;
  seh_area = (char*)seg->start + getpagesize();
}

code_heap::~code_heap() {
  delete allocator;
  allocator = NULL;
  delete seg;
  seg = NULL;
}

void code_heap::write_barrier(code_block* compiled) {
  points_to_nursery.insert(compiled);
  points_to_aging.insert(compiled);
}

void code_heap::clear_remembered_set() {
  points_to_nursery.clear();
  points_to_aging.clear();
}

bool code_heap::uninitialized_p(code_block* compiled) {
  return uninitialized_blocks.count(compiled) > 0;
}

void code_heap::free(code_block* compiled) {
  FACTOR_ASSERT(!uninitialized_p(compiled));
  points_to_nursery.erase(compiled);
  points_to_aging.erase(compiled);
  all_blocks.erase((cell)compiled);
  allocator->free(compiled);
}

void code_heap::flush_icache() { factor::flush_icache(seg->start, seg->size); }

void code_heap::set_safepoint_guard(bool locked) {
  if (!set_memory_locked(safepoint_page, getpagesize(), locked)) {
    fatal_error("Cannot (un)protect safepoint guard page", safepoint_page);
  }
}

void code_heap::sweep() {
  auto clear_free_blocks_from_all_blocks = [&](code_block* block, cell size) {
    std::set<cell>::iterator erase_from =
      all_blocks.lower_bound((cell)block);
    std::set<cell>::iterator erase_to =
      all_blocks.lower_bound((cell)block + size);
    all_blocks.erase(erase_from, erase_to);
  };
  allocator->sweep(clear_free_blocks_from_all_blocks);
#ifdef FACTOR_DEBUG
  verify_all_blocks_set();
#endif
}

void code_heap::verify_all_blocks_set() {
  auto all_blocks_set_verifier = [&](code_block* block, cell size) {
    (void)block;
    (void)size;
    FACTOR_ASSERT(all_blocks.find((cell)block) != all_blocks.end());
  };
  allocator->iterate(all_blocks_set_verifier, no_fixup());
}

code_block* code_heap::code_block_for_address(cell address) {
  std::set<cell>::const_iterator blocki = all_blocks.upper_bound(address);
  FACTOR_ASSERT(blocki != all_blocks.begin());
  --blocki;
  code_block* found_block = (code_block*)*blocki;
  FACTOR_ASSERT(found_block->entry_point() <=
                address // XXX this isn't valid during fixup. should store the
                        //     size in the map
                        //    && address - found_block->entry_point() <
                        //       found_block->size()
                );
  return found_block;
}

cell code_heap::frame_predecessor(cell frame_top) {
  cell addr = *(cell*)frame_top;
  FACTOR_ASSERT(seg->in_segment_p(addr));
  code_block* owner = code_block_for_address(addr);
  cell frame_size = owner->stack_frame_size_for_address(addr);
  return frame_top + frame_size;
}

// Recomputes the all_blocks set of code blocks
void code_heap::initialize_all_blocks_set() {
  all_blocks.clear();
  auto all_blocks_set_inserter = [&](code_block* block, cell size) {
    (void)size;
    all_blocks.insert((cell)block);
  };
  allocator->iterate(all_blocks_set_inserter, no_fixup());
#ifdef FACTOR_DEBUG
  verify_all_blocks_set();
#endif
}

// Update pointers to words referenced from all code blocks.
// Only needed after redefining an existing word.
// If generic words were redefined, inline caches need to be reset.
void factor_vm::update_code_heap_words(bool reset_inline_caches) {
  auto word_updater = [&](code_block* block, cell size) {
    (void)size;
    update_word_references(block, reset_inline_caches);
  };
  each_code_block(word_updater);
}

// Allocates memory
void factor_vm::primitive_modify_code_heap() {
  bool reset_inline_caches = to_boolean(ctx->pop());
  bool update_existing_words = to_boolean(ctx->pop());
  data_root<array> alist(ctx->pop(), this);

  cell count = array_capacity(alist.untagged());

  if (count == 0)
    return;

  for (cell i = 0; i < count; i++) {
    data_root<array> pair(array_nth(alist.untagged(), i), this);

    data_root<word> word(array_nth(pair.untagged(), 0), this);
    data_root<object> data(array_nth(pair.untagged(), 1), this);

    switch (data.type()) {
      case QUOTATION_TYPE:
        jit_compile_word(word.value(), data.value(), false);
        break;
      case ARRAY_TYPE: {
        array* compiled_data = data.as<array>().untagged();
        cell parameters = array_nth(compiled_data, 0);
        cell literals = array_nth(compiled_data, 1);
        cell relocation = array_nth(compiled_data, 2);
        cell labels = array_nth(compiled_data, 3);
        cell code = array_nth(compiled_data, 4);
        cell frame_size = untag_fixnum(array_nth(compiled_data, 5));

        code_block* compiled =
            add_code_block(CODE_BLOCK_OPTIMIZED, code, labels, word.value(),
                           relocation, parameters, literals, frame_size);

        word->entry_point = compiled->entry_point();
      } break;
      default:
        critical_error("Expected a quotation or an array", data.value());
        break;
    }
  }

  if (update_existing_words)
    update_code_heap_words(reset_inline_caches);
  else {
    // Fast path for compilation units that only define new words.
    FACTOR_FOR_EACH(code->uninitialized_blocks) {
      initialize_code_block(iter->first, iter->second);
    }
    code->uninitialized_blocks.clear();
  }
  FACTOR_ASSERT(code->uninitialized_blocks.size() == 0);
}

// Allocates memory
void factor_vm::primitive_code_room() {
  allocator_room room = code->allocator->as_allocator_room();
  ctx->push(tag<byte_array>(byte_array_from_value(&room)));
}

void factor_vm::primitive_strip_stack_traces() {
  auto stack_trace_stripper = [](code_block* block, cell size) {
    (void)size;
    block->owner = false_object;
  };
  each_code_block(stack_trace_stripper);
}

// Allocates memory
void factor_vm::primitive_code_blocks() {
  std::vector<cell> objects;
  auto code_block_accumulator = [&](code_block* block, cell size) {
    (void)size;
    objects.push_back(block->owner);
    objects.push_back(block->parameters);
    objects.push_back(block->relocation);

    objects.push_back(tag_fixnum(block->type()));
    objects.push_back(tag_fixnum(block->size()));

    // Note: the entry point is always a multiple of the heap
    // alignment (16 bytes). We cannot allocate while iterating
    // through the code heap, so it is not possible to call
    // from_unsigned_cell() here. It is OK, however, to add it as
    // if it were a fixnum, and have library code shift it to the
    // left by 4.
    cell entry_point = block->entry_point();
    FACTOR_ASSERT((entry_point & (data_alignment - 1)) == 0);
    FACTOR_ASSERT((entry_point & TAG_MASK) == FIXNUM_TYPE);
    objects.push_back(entry_point);
  };
  each_code_block(code_block_accumulator);
  ctx->push(std_vector_to_array(objects));
}

}


text:
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using LCIAToolAPI.Areas.RouteDebugger.Models;

namespace LCIAToolAPI.Areas.RouteDebugger
{
    /// <summary>
    /// Inspect handler saves route inspect data and handler error.
    ///
    /// If a request has inspect header, the handler will save all routes and route data to inspect data.
    ///
    /// If the return response is not 200. That may cause by 500 or 404, handler extract Inspect data from
    /// request property and set back the the response. The original response status is saved to the inspect
    /// data and actual return response is always 200.
    /// </summary>
    public class InspectHandler : DelegatingHandler
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.IsInspectRequest())
            {
                var config = GlobalConfiguration.Configuration;

                request.Properties[RequestHelper.RouteDataCache] =
                    new RouteDataInfo
                    {
                        RouteTemplate = request.GetRouteData().Route.RouteTemplate,
                        Data = request.GetRouteData().Values.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value.ToString())).ToArray()
                    };

                request.Properties[RequestHelper.RoutesCache] = config.Routes.Select(route =>
                    new RouteInfo
                    {
                        RouteTemplate = route.RouteTemplate,
                        Defaults = route.Defaults != null ? route.Defaults.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value.ToString())).ToArray() : null,
                        Constraints = route.Constraints != null ? route.Constraints.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value.ToString())).ToArray() : null,
                        DataTokens = route.DataTokens != null ? route.DataTokens.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value.ToString())).ToArray() : null,
                        Handler = route.Handler != null ? route.Handler.GetType().Name : null,
                        Picked = route.RouteTemplate == request.GetRouteData().Route.RouteTemplate
                    }).ToArray();

                var response = await base.SendAsync(request, cancellationToken);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var newRequest = response.RequestMessage;
                    var inspectData = new InspectData(newRequest);
                    inspectData.RealHttpStatus = response.StatusCode;
                    response = newRequest.CreateResponse<InspectData>(HttpStatusCode.OK, inspectData);
                }

                response.Headers.Add(RequestHelper.InspectHeaderName, "done");

                return response;
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }
}


text:
package com.sleepygrizzly.core;

public class Person {
	public static Person person;
	private static boolean flag = false;
	private String name;
	private Integer score = 0;

	public Person(String name, Integer score){
		this.name = name;
		this.score = score;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getScore() {
		return score;
	}

	public void setScore(Integer score) {
		this.score = score;
	}

	public static Person getPerson(){
		if (flag) return Person.person;
		Person.person = new Person("Hello", 999);
		Person.flag = true;
		return Person.person;
	}

}


text:
<?php

namespace IntuElastica\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Elastica\Client;

/**
 * Elastica client factory
 *
 * @license MIT
 * @package IntuElastica
 */
class ElasticaFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Configuration');
        $client = new Client(isset($config['elastica']) ? $config['elastica'] : array());

        return $client;
    }
}


text:
using System;
using System.Collections.ObjectModel;
using DbExtensions;

namespace Samples.CSharp.Northwind {

   [Table(Name = "Employees")]
   public class Employee {

      [Column(IsPrimaryKey = true, IsDbGenerated = true)]
      public int EmployeeID { get; set; }

      [Column]
      public string LastName { get; set; }

      [Column]
      public string FirstName { get; set; }

      [Column]
      public string Title { get; set; }

      [Column]
      public string TitleOfCourtesy { get; set; }

      [Column]
      public DateTime? BirthDate { get; set; }

      [Column]
      public DateTime? HireDate { get; set; }

      [Column]
      public string Address { get; set; }

      [Column]
      public string City { get; set; }

      [Column]
      public string Region { get; set; }

      [Column]
      public string PostalCode { get; set; }

      [Column]
      public string Country { get; set; }

      [Column]
      public string HomePhone { get; set; }

      [Column]
      public string Extension { get; set; }

      [Column]
      public byte[] Photo { get; set; }

      [Column]
      public string Notes { get; set; }

      [Column]
      public int? ReportsTo { get; set; }

      [Column]
      public string PhotoPath { get; set; }

      [Association(ThisKey = nameof(ReportsTo))]
      public Employee ReportsToEmployee { get; set; }

      [Association(OtherKey = nameof(Employee.ReportsTo))]
      public Collection<Employee> Employees { get; } = new Collection<Employee>();

      [Association(OtherKey = nameof(EmployeeTerritory.EmployeeID))]
      public Collection<EmployeeTerritory> EmployeeTerritories { get; } = new Collection<EmployeeTerritory>();

      [Association(OtherKey = nameof(Order.EmployeeID))]
      public Collection<Order> Orders { get; } = new Collection<Order>();
   }
}


text:
Desktop notification tool showing the latest crypotcurrency rates built for linux OS
using python.

**Installation from pypi**

The package is available on pypi and can be installed using
` pip install Crypto-Notifier`.

To run the package, run `cryptonotifier` on the terminal.

**Installation/setup from source**

1. Clone the repository.
2. Run `pip install -r requirements.txt`
3. `cd` into `cryptonotifier`
4. Run `python  Main.py`

**Installation from pypi**

`pip install Crypto-Notify`

**Requirements**
* python 3
* requests<=2.11.1
* beautifulsoup4
* notify2

**Screenshots**

![screenshot](https://user-images.githubusercontent.com/17358196/37451700-673a40b8-2858-11e8-845f-99dad7dbc479.png)


text:
import * as ts from "typescript";

import * as Lint from "../index";

export class Rule extends Lint.Rules.TypedRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "no-for-in-array",
        description: "Disallows iterating over an array with a for-in loop.",
        descriptionDetails: Lint.Utils.dedent`
            A for-in loop (\`for (var k in o)\`) iterates over the properties of an Object.

            While it is legal to use for-in loops with array types, it is not common.
            for-in will iterate over the indices of the array as strings, omitting any "holes" in
            the array.

            More common is to use for-of, which iterates over the values of an array.
            If you want to iterate over the indices, alternatives include:

            array.forEach((value, index) => { ... });
            for (const [index, value] of array.entries()) { ... }
            for (let i = 0; i < array.length; i++) { ... }
            `,
        optionsDescription: "Not configurable.",
        options: null,
        optionExamples: ["true"],
        requiresTypeInfo: true,
        type: "functionality",
        typescriptOnly: false,
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING = "for-in loops over arrays are forbidden. Use for-of or array.forEach instead.";

    public applyWithProgram(sourceFile: ts.SourceFile, langSvc: ts.LanguageService): Lint.RuleFailure[] {
        const noForInArrayWalker = new NoForInArrayWalker(sourceFile, this.getOptions(), langSvc.getProgram());
        return this.applyWithWalker(noForInArrayWalker);
    }
}

class NoForInArrayWalker extends Lint.ProgramAwareRuleWalker {
    public visitForInStatement(node: ts.ForInStatement) {
        const iteratee = node.expression;
        const tc = this.getTypeChecker();
        const type = tc.getTypeAtLocation(iteratee);

        /* tslint:disable:no-bitwise */
        const isArrayType = type.symbol && type.symbol.name === "Array";
        const isStringType = (type.flags & ts.TypeFlags.StringLike) !== 0;
        /* tslint:enable:no-bitwise */

        if (isArrayType || isStringType) {
            this.addFailureAtNode(node, Rule.FAILURE_STRING);
        }

        super.visitForInStatement(node);
    }
}


text:
package com.battlelancer.seriesguide.sync;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import com.battlelancer.seriesguide.SgApp;
import com.battlelancer.seriesguide.backend.HexagonTools;
import com.battlelancer.seriesguide.backend.settings.HexagonSettings;
import com.battlelancer.seriesguide.provider.SgRoomDatabase;
import com.battlelancer.seriesguide.shows.database.SgShow2Helper;
import com.battlelancer.seriesguide.shows.database.SgShow2Ids;
import com.battlelancer.seriesguide.movies.tools.MovieTools;
import com.battlelancer.seriesguide.shows.search.discover.SearchResult;
import com.battlelancer.seriesguide.util.TaskManager;
import com.uwetrottmann.androidutils.AndroidUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HexagonSync {

    private Context context;
    private HexagonTools hexagonTools;
    private MovieTools movieTools;
    private SyncProgress progress;

    HexagonSync(Context context, HexagonTools hexagonTools,
            MovieTools movieTools, SyncProgress progress) {
        this.context = context;
        this.hexagonTools = hexagonTools;
        this.movieTools = movieTools;
        this.progress = progress;
    }

    public static class HexagonResult {
        public final boolean hasAddedShows;
        public final boolean success;
        public HexagonResult(boolean hasAddedShows, boolean success) {
            this.hasAddedShows = hasAddedShows;
            this.success = success;
        }
    }

    /**
     * Syncs episodes, shows and movies with Hexagon.
     *
     * <p> Merges shows, episodes and movies after a sign-in. Consecutive syncs will only download
     * changes to shows, episodes and movies.
     */
    public HexagonResult sync() {
        Map<Integer, Long> tmdbIdsToShowIds = SgApp.getServicesComponent(context).showTools()
                .getTmdbIdsToShowIds();

        //// EPISODES
        progress.publish(SyncProgress.Step.HEXAGON_EPISODES);
        boolean syncEpisodesSuccessful = syncEpisodes(tmdbIdsToShowIds);
        if (!syncEpisodesSuccessful) {
            progress.recordError();
        }

        //// SHOWS
        progress.publish(SyncProgress.Step.HEXAGON_SHOWS);
        HexagonResult syncShowsResult = syncShows(tmdbIdsToShowIds);
        if (!syncShowsResult.success) {
            progress.recordError();
        }

        //// MOVIES
        progress.publish(SyncProgress.Step.HEXAGON_MOVIES);
        boolean syncMoviesSuccessful = syncMovies();
        if (!syncMoviesSuccessful) {
            progress.recordError();
        }

        //// LISTS
        progress.publish(SyncProgress.Step.HEXAGON_LISTS);
        boolean syncListsSuccessful = syncLists();
        if (!syncListsSuccessful) {
            progress.recordError();
        }

        boolean success = syncEpisodesSuccessful
                && syncShowsResult.success
                && syncMoviesSuccessful
                && syncListsSuccessful;

        return new HexagonResult(syncShowsResult.hasAddedShows, success);
    }

    private boolean syncEpisodes(@NonNull Map<Integer, Long> tmdbIdsToShowIds) {
        // get shows that need episode merging
        SgShow2Helper helper = SgRoomDatabase.getInstance(context).sgShow2Helper();
        List<SgShow2Ids> showsToMerge = helper.getHexagonMergeNotCompleted();

        // try merging episodes for them
        boolean mergeSuccessful = true;
        HexagonEpisodeSync episodeSync = new HexagonEpisodeSync(context, hexagonTools);
        for (SgShow2Ids show : showsToMerge) {
            // abort if connection is lost
            if (!AndroidUtils.isNetworkConnected(context)) {
                return false;
            }

            // TMDB ID is required, legacy shows with TVDB only data will no longer be synced.
            Integer showTmdbId = show.getTmdbId();
            if (showTmdbId == null || showTmdbId == 0) continue;

            boolean success = episodeSync.downloadFlags(show.getId(), showTmdbId, show.getTvdbId());
            if (!success) {
                // try again next time
                mergeSuccessful = false;
                continue;
            }

            success = episodeSync.uploadFlags(show.getId(), showTmdbId);
            if (success) {
                // set merge as completed
                helper.setHexagonMergeCompleted(show.getId());
            } else {
                mergeSuccessful = false;
            }
        }

        // download changed episodes and update properties on existing episodes
        boolean changedDownloadSuccessful = episodeSync.downloadChangedFlags(tmdbIdsToShowIds);

        return mergeSuccessful && changedDownloadSuccessful;
    }

    private HexagonResult syncShows(Map<Integer, Long> tmdbIdsToShowIds) {
        boolean hasMergedShows = HexagonSettings.hasMergedShows(context);

        // download shows and apply property changes (if merging only overwrite some properties)
        HexagonShowSync showSync = new HexagonShowSync(context, hexagonTools);
        HashMap<Integer, SearchResult> newShows = new HashMap<>();
        boolean downloadSuccessful = showSync.download(tmdbIdsToShowIds, newShows, hasMergedShows);
        if (!downloadSuccessful) {
            return new HexagonResult(false, false);
        }

        // if merge required, upload all shows to Hexagon
        if (!hasMergedShows) {
            boolean uploadSuccessful = showSync.uploadAll();
            if (!uploadSuccessful) {
                return new HexagonResult(false, false);
            }
        }

        // add new shows
        boolean addNewShows = !newShows.isEmpty();
        if (addNewShows) {
            List<SearchResult> newShowsList = new LinkedList<>(newShows.values());
            TaskManager.getInstance().performAddTask(context, newShowsList, true, !hasMergedShows);
        } else if (!hasMergedShows) {
            // set shows as merged
            HexagonSettings.setHasMergedShows(context, true);
        }

        return new HexagonResult(addNewShows, true);
    }

    private boolean syncMovies() {
        boolean hasMergedMovies = HexagonSettings.hasMergedMovies(context);

        // download movies and apply property changes, build list of new movies
        Set<Integer> newCollectionMovies = new HashSet<>();
        Set<Integer> newWatchlistMovies = new HashSet<>();
        Map<Integer, Integer> newWatchedMoviesToPlays = new HashMap<>();
        HexagonMovieSync movieSync = new HexagonMovieSync(context, hexagonTools);
        boolean downloadSuccessful = movieSync.download(
                newCollectionMovies,
                newWatchlistMovies,
                newWatchedMoviesToPlays,
                hasMergedMovies
        );
        if (!downloadSuccessful) {
            return false;
        }

        if (!hasMergedMovies) {
            boolean uploadSuccessful = movieSync.uploadAll();
            if (!uploadSuccessful) {
                return false;
            }
        }

        // add new movies with the just downloaded properties
        boolean addingSuccessful = movieTools
                .addMovies(newCollectionMovies, newWatchlistMovies, newWatchedMoviesToPlays);
        if (!hasMergedMovies) {
            // ensure all missing movies from Hexagon are added before merge is complete
            if (!addingSuccessful) {
                return false;
            }
            // set movies as merged
            PreferenceManager.getDefaultSharedPreferences(context)
                    .edit()
                    .putBoolean(HexagonSettings.KEY_MERGED_MOVIES, true)
                    .apply();
        }

        return addingSuccessful;
    }

    private boolean syncLists() {
        boolean hasMergedLists = HexagonSettings.hasMergedLists(context);

        HexagonListsSync listsSync = new HexagonListsSync(context, hexagonTools);
        if (!listsSync.download(hasMergedLists)) {
            return false;
        }

        if (hasMergedLists) {
            // on regular syncs, remove lists gone from hexagon
            if (!listsSync.pruneRemovedLists()) {
                return false;
            }
        } else {
            // upload all lists on initial data merge
            if (!listsSync.uploadAll()) {
                return false;
            }
        }

        if (!hasMergedLists) {
            // set lists as merged
            PreferenceManager.getDefaultSharedPreferences(context)
                    .edit()
                    .putBoolean(HexagonSettings.KEY_MERGED_LISTS, true)
                    .apply();
        }

        return true;
    }
}


text:
from cvxpy.atoms.affine.diag import diag
from cvxpy.reductions.dgp2dcp.atom_canonicalizers.add_canon import add_canon
from cvxpy.reductions.dgp2dcp.util import explicit_sum

def trace_canon(expr, args):
    diag_sum = explicit_sum(diag(args[0]))
    return add_canon(diag_sum, diag_sum.args)


text:
YUI.add('widget-skin', function(Y) {

/**
 * Provides skin related utlility methods.
 *
 * @module widget
 * @submodule widget-skin
 */

var BOUNDING_BOX = "boundingBox",
    CONTENT_BOX = "contentBox",
    SKIN = "skin",
    _getClassName = Y.ClassNameManager.getClassName;

/**
 * Returns the name of the skin that's currently applied to the widget.
 * This is only really useful after the widget's DOM structure is in the
 * document, either by render or by progressive enhancement.  Searches up
 * the Widget's ancestor axis for a class yui3-skin-(name), and returns the
 * (name) portion.  Otherwise, returns null.
 *
 * @method getSkinName
 * @for Widget
 * @return {String} the name of the skin, or null (yui3-skin-sam => sam)
 */

Y.Widget.prototype.getSkinName = function () {
    var root = this.get( CONTENT_BOX ) || this.get( BOUNDING_BOX ),
        search = new RegExp( '\\b' + _getClassName( SKIN ) + '-(\\S+)' ),
        match;

    if ( root ) {
        root.ancestor( function ( node ) {
            match = node.get( 'className' ).match( search );
            return match;
        } );
    }

    return ( match ) ? match[1] : null;
};

}, '3.5.0' ,{requires:['widget-base']});


text:
---
uid: SolidEdgeFrameworkSupport.GostWeldSymbols.Item(System.Object)
summary:
remarks:
---


text:
Using Rust & Python for scientific computing.

## Install Python dependencies

```bash
pip install -r python-requirements.txt
```

Then, ```cd``` to any particular project you'd like to run, and run ```cargo build```.