text:
import d3 from 'd3';

const DATE_FORMAT = 'YYYY-MM-DD';
const D3_DATE_FORMAT = '%Y-%m-%d';
const D3_NUMBER_DECIMAL = ',';
const d3DateFormatter = d3.time.format(D3_DATE_FORMAT);
const d3NumberFormatter = d3.format(D3_NUMBER_DECIMAL);

const numberFormatter = {
	format: value => d3NumberFormatter(value),
};
const dateFormatter = {
	parse: string => d3DateFormatter.parse(string),
	format: timestamp => d3DateFormatter(new Date(timestamp)),
};

/**
 * Checks max interval >= the max of data values and  if the min interval < max interval
 */
function adaptSelection(selection) {
	return {
		min: selection.min,
		max: selection.max,
		excludeMax: false,
	};
}

/**
 * Check if date is correct
 */
function dateIsCorrect(value) {
	return dateFormatter.parse(value);
}

/**
 * Check if number is correct
 */
function numberIsCorrect(value) {
	return /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/.test(value.trim());
}

/**
 * Check if string has comma
 */
function hasComma(value) {
	return value.indexOf(',') > -1;
}

/**
 * Return the number of decimal digit
 */
function getNbDecimalDigit(num) {
	const match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
	return Math.max(
		0,
		// Number of digits right of decimal point.
		(match[1] ? match[1].length : 0) -
			// Adjust for scientific notation.
			(match[2] ? +match[2] : 0)
	);
}

/**
 * @ngdoc controller
 * @name talend.widget.controller:RangeSliderCtrl
 * @description The rangeSlider controller
 */
export default class RangeSliderCtrl {
	constructor() {
		this.dateFormat = DATE_FORMAT;
	}

	// -----------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------UTILS----------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------
	/**
     * @ngdoc method
     * @name isDateType
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Check if the range limits are date types
     **/
	isDateType() {
		return this.rangeLimits.type === 'date';
	}

	/**
     * @ngdoc method
     * @name adaptToInputValue
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Adapt values to input format, i.e. strings. The dates are formatted to the default format
     * @param {Object} values The values to adapt
     * @return {Object} The adapted values
     **/
	adaptToInputValue(values) {
		return {
			min: this.isDateType()
				? dateFormatter.format(values.min)
				: '' + values.min,
			max: this.isDateType()
				? dateFormatter.format(values.max)
				: '' + values.max,
		};
	}

	/**
     * @ngdoc method
     * @name adaptFromInputValue
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Adapt values from input to model format (timestamp for dates, number otherwise)
     * @param {Object} values The values to adapt
     * @return {Object} The adapted values
     **/
	adaptFromInputValue(values) {
		return {
			min: this.isDateType()
				? +dateFormatter.parse(values.min)
				: +values.min,
			max: this.isDateType()
				? +dateFormatter.parse(values.max)
				: +values.max,
		};
	}

	/**
     * @ngdoc method
     * @name getLimitsText
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Get the min and max labels
     * @return {Object} The adapted values
     **/
	getLimitsText() {
		const minText = this.isDateType()
			? dateFormatter.format(this.rangeLimits.min)
			: numberFormatter.format(this.rangeLimits.min);
		const maxText = this.isDateType()
			? dateFormatter.format(this.rangeLimits.max)
			: numberFormatter.format(this.rangeLimits.max);
		return { minText, maxText };
	}

	/**
     * @ngdoc method
     * @name adaptToInboundValues
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Adapt values to be within [min, max] interval
     * @param {Object} values The values to adapt
     * @return {Object} The adapted values
     **/
	adaptToInboundValues(values) {
		return {
			min: Math.max(this.rangeLimits.min, values.min),
			max: Math.min(this.rangeLimits.max, values.max),
		};
	}

	// -----------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------MODEL----------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------
	/**
     * @ngdoc method
     * @name initModel
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Initialize the model (last brush and input values) and configuration
     **/
	initModel() {
		const minBrush =
			typeof this.rangeLimits.minBrush !== 'undefined'
				? this.rangeLimits.minBrush
				: this.rangeLimits.min;
		const maxBrush =
			typeof this.rangeLimits.maxBrush !== 'undefined'
				? this.rangeLimits.maxBrush
				: this.rangeLimits.max;
		const minFilter =
			typeof this.rangeLimits.minFilterVal !== 'undefined'
				? this.rangeLimits.minFilterVal
				: this.rangeLimits.min;
		const maxFilter =
			typeof this.rangeLimits.maxFilterVal !== 'undefined'
				? this.rangeLimits.maxFilterVal
				: this.rangeLimits.max;

		this.nbDecimals = Math.max(
			getNbDecimalDigit(minBrush),
			getNbDecimalDigit(maxBrush)
		);

		this.lastValues = {
			// the brush values
			brush: {
				min: minBrush,
				max: maxBrush,
			},
			// the input values
			input: {
				min: minFilter,
				max: maxFilter,
			},
		};
	}

	/**
     * @ngdoc method
     * @name setLastBrushValues
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Update last brush values
     * @params {Object} values The new brush values
     **/
	setLastBrushValues(values) {
		this.lastValues.brush.min = values.min;
		this.lastValues.brush.max = values.max;
	}

	/**
     * @ngdoc method
     * @name setLastInputValues
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Update last input values
     * @params {Object} values The new input values
     **/
	setLastInputValues(values) {
		this.lastValues.input.min = values.min;
		this.lastValues.input.max = values.max;
	}

	// -----------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------BRUSH----------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------
	/**
     * @ngdoc method
     * @name updateBrush
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Update current brush values with an animation on transition
     * @params {Object} values The new brush values
     **/
	updateBrush(values) {
		const min = values.min;
		let max = values.max;
		if (min === max) {
			const exp = '1e-' + (this.nbDecimals + 2);
			max += Number(exp);
		}

		this.brushg.transition().call(this.brush.extent([min, max]));
	}

	// -----------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------INPUT----------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------
	/**
     * @ngdoc method
     * @name setInputValue
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Update current input values
     * @params {Object} values The new input values
     **/
	setInputValue(values) {
		this.minMaxModel = this.adaptToInputValue(values);
	}

	/**
     * @ngdoc method
     * @name resetInputValues
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Reset current input values to the last registered values
     **/
	resetInputValues() {
		this.hideMsgErr();
		this.setInputValue(this.lastValues.input);
	}

	/**
     * @ngdoc method
     * @name showMsgErr
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Show error messages
     **/
	showMsgErr() {
		this.invalidNumber = true;
		const minMaxStr = this.minMaxModel.min + this.minMaxModel.max;
		this.invalidNumberWithComma = hasComma(minMaxStr);
	}

	/**
     * @ngdoc method
     * @name hideMsgErr
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Hide error messages
     **/
	hideMsgErr() {
		this.invalidNumber = false;
		this.invalidNumberWithComma = false;
	}

	/**
     * @ngdoc method
     * @name inputsAreValid
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Check if inputs values are valid (date and number with wanted format)
     **/
	inputsAreValid() {
		const check = this.isDateType() ? dateIsCorrect : numberIsCorrect;
		return check(this.minMaxModel.min) && check(this.minMaxModel.max);
	}

	/**
     * @ngdoc method
     * @name validateInputs
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Check inputs and show/hide error messages
     **/
	validateInputs() {
		if (this.inputsAreValid()) {
			this.hideMsgErr();
		}
		else {
			this.showMsgErr();
		}
	}

	/**
     * @ngdoc method
     * @name handleKey
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Keydown event on inputs
     * @param {Object} event The key event
     **/
	handleKey(event) {
		switch (event.keyCode) {
		case 13:
			this.onInputChange();
			break;
		case 27:
			this.resetInputValues();
			break;
		}
	}

	// -----------------------------------------------------------------------------------------------------------------
	// -----------------------------------------------PROPAGATION-------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------
	/**
     * @ngdoc method
     * @name onChange
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Propagate new values to the parent component
     * @param {Object} values The values to propagate
     **/
	onChange(values) {
		const interval = adaptSelection(values, this.rangeLimits.max);
		this.onBrushEnd({ interval });
	}

	/**
     * @ngdoc method
     * @name onBrushChange
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description When user change brush values with the mouse,
     * we propagate it in the last registered values and to the parent component
     **/
	onBrushChange(values) {
		this.setLastBrushValues(values);
		this.setLastInputValues(values);
		this.onChange(values);
	}

	/**
     * @ngdoc method
     * @name onInputChange
     * @methodOf talend.widget.controller:RangeSliderCtrl
     * @description Whe user validate (blur or enter) an input,
     * we propagate it in the last registered values and to the parent component, and update the brush
     * If the values are invalid, they are reset to the last registered values
     **/
	onInputChange() {
		if (this.inputsAreValid()) {
			const adaptedValue = this.adaptFromInputValue(this.minMaxModel);
			if (
				adaptedValue.min === this.lastValues.input.min &&
				adaptedValue.max === this.lastValues.input.max
			) {
				return;
			}

			const adaptedBrushValues = this.adaptToInboundValues(adaptedValue);
			this.updateBrush(adaptedBrushValues);
			this.setLastBrushValues(adaptedBrushValues);
			this.setLastInputValues(adaptedValue);
			this.onChange(adaptedValue);
		}
		else {
			this.resetInputValues();
		}
	}
}


text:
using System.Windows;
using System.Windows.Input;

namespace WpfCommonds
{
    public static class EscClosableWindow
    {
        public static void SetEscClosableWindow(this Window window)
        {
            window.PreviewKeyDown += EscClosableWindow.WindowBase_PreviewKeyDown;
        }

        private static void WindowBase_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                ((Window)sender).Close();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Date: Wed, 11 Dec 1996 22:34:12 GMT
Server: NCSA/1.5
Content-type: text/html
Last-modified: Fri, 11 Oct 1996 19:15:43 GMT
Content-length: 10723

<TITLE>CS 302 Section 70 Lecture Notes - Week 9</TITLE>

<!WA0><!WA0><!WA0><!WA1><!WA1><!WA1> Lecture Notes - Week 6

Topic:

One-dimensional arrays. One-dimensional array arguments. Parallel arrays.

Text:

7.1 - 7.7, 7.9

Notes:

Arrays

Simple Variables

So far we have used simple variables to store values.
      <LISTING>
	INTEGER SCORE
	REAL PRICE
	LOGICAL ANSWER
      </LISTING>

Simple variables can only store a single value; i.e one integer, one real number or one logical value.

To store another value we must declare a new variable with a different name.
      <LISTING>
	INTEGER SCORE1, SCORE2, SCORE3
      </LISTING>

Array Variables

Arrays store several related values under a single variable name.

All values stored in an array are of the same type, called the base type.

Easier to store several values in an array than declaring separate variables for each.

Declaring Array Variables

Specify the name of the array, the base type, and the number of values to store - called the size of the array.
      <LISTING>
	basetype arrayname(arraysize)

	INTEGER SCORES(3)
	REAL PRICES(1000)
	LOGICAL ANSWRS(10)
      </LISTING>

Array variables are declared together with simple variables.
      <LISTING>
	PROGRAM FOO
	REAL COST
	INTEGER SCORES(3), SUM
      </LISTING>

Commonly use a constant (i.e. Fortran <TT>PARAMETER</TT> statement) to declare the size of an array.
      <LISTING>
	INTEGER MAXSIZ
	PARAMETER (MAXSIZ=3)
	REAL SCORES(MAXSIZ)
      </LISTING>

<TT>SCORES</TT> array variable stores three <TT>INTEGER</TT>'s under a single variable name.

Referencing Arrays

To access a particular value in an array you specify the array name and the subscript of the value (i.e. its position in the array).
      <LISTING>
	arrayname(subscript)
      </LISTING>

The first value in an array has subscript 1, the last has subscript arraysize.
      <LISTING>
	SCORES(1)  - first element
	SCORES(2)  - second element
	SCORES(3)  - last element
      </LISTING>

Array variables can be used anywhere you would use a normal simple variable.
      <LISTING>
	PRINT *, 'Your score is ', SCORES(1)
	BAR = SCORES(1)*10 + COS(SCORES(2))
	READ(1, 100, END=150) SCORES(3)
      </LISTING>

Store values in an array using the assignment statement, just like simple variables
      <LISTING>
	arrayname(subscript) = value

	SCORES(1) = 3
	SCORES(2) = SCORES(1)*6
      </LISTING>

Array Subscripts

Array subscripts can be literals, variables or expressions.  The value of the expression determines which element is accessed.
      <LISTING>
	INTEGER N, SCORES(3)

	N = 2
	SCORES(N) = SCORES(N*4-5)-SCORES(1)
      </LISTING>

Value of array subscript must be in the range 1 ... arraysize.

Array subscript is an <TT>INTEGER</TT> expression enclosed by parentheses ().

	Right:
      <LISTING>
	SCORES(N), SCORES(N*4-5)
      </LISTING>
	Wrong:
      <LISTING>
	SCORES(-13), SCORES(5), SCORES[2], SCORES(2.3)
      </LISTING>

Important: The type of the array variable, the base type, and the subscript are very different.
      <LISTING>
	REAL PRICES(1000)
	PRICES(N) = ...

	Variable        Type
	--------------------------------------------------
	PRICES          ARRAY (all of the prices together)
	PRICES(N)       REAL
	N               INTEGER
      </LISTING>

Arrays and DO Loops

Arrays are commonly processed using a <TT>DO</TT> loop.
      <LISTING>
	      INTEGER MAXSIZ, TOTAL, COUNT
	      PARAMETER (MAXSIZ=100)
	      REAL SCORES(MAXSIZ)

	C     Read in all the scores
	      DO COUNT=1, MAXSIZ
	         READ *, SCORES(COUNT)
	      END DO

	C     Add up all the scores
	      TOTAL = 0
	      DO COUNT=1, MAXSIZ
	         TOTAL = TOTAL + SCORES(COUNT)
	      END DO

	C     Print out all the scores
	      DO COUNT=1, MAXSIZ
	         PRINT *, SCORES(COUNT)
	      END DO

	      STOP
	      END
      </LISTING>
	Try doing this without arrays!

The <TT>DO</TT> loop counter <TT>COUNT</TT> is used as the array subscript to sequentially access the values one at a time.

Reading Arrays

#1: DO Loop

An array can be "filled up" by reading in the values in a <TT>DO</TT> loop.
      <LISTING>
	DO I=1, 100
	   READ *, SCORES(I)
	END DO
      </LISTING>

Values must be typed in on different lines because the <TT>READ</TT> statement is re-executed each time.

#2: Read Entire Array

Can read in the entire array at once.
      <LISTING>
	READ *, SCORES
      </LISTING>

Values may be entered on different lines or all on the same line.

#3: Implied DO Loop

Can read in any part of an array from the same line using an implied DO loop.
      <LISTING>
	READ *, (SCORES(I), I=50, 100)
      </LISTING>

Equivalent to a <TT>DO</TT> loop inside the <TT>READ</TT> statement, so everything is read off the same line.

Writing Arrays

#1: DO Loop

The values in an array can be printed on different lines using a <TT>DO</TT> loop.
      <LISTING>
	DO I=1, 100
	   PRINT *, SCORES(I)
	END DO
      </LISTING>

#2: Print Entire Array

Can print in the entire array at once on one line.
      <LISTING>
	PRINT *, SCORES
      </LISTING>

#3: Implied DO Loop

Can print in any part of an array on the same line using an implied DO loop.
      <LISTING>
	PRINT *, (SCORES(I), I=50, 100)
      </LISTING>

Implied DO Loops

Implied <TT>DO</TT> loops are loops within a <TT>READ</TT>, <TT>WRITE</TT> or <TT>PRINT</TT> statement.
      <LISTING>
	READ *, (array(count), count=start, end, inc)

	READ *, (SCORES(I), I=1, MAXSIZ, 1)
	PRINT *, (PRICES(NUM), NUM=1, 1000)
      </LISTING>

Can read/write more than one array with an implied <TT>DO</TT> loop.
      <LISTING>
	READ *, (SCORES(I),GRADES(I), I=1, 100)
      </LISTING>
	reads
      <LISTING>
	SCORES(1), GRADES(1), SCORES(2), GRADES(2) ...
      </LISTING>

Can use the end-of-file specifier with implied <TT>DO</TT> loops.
      <LISTING>
	READ(1,*,END=100) (SCORES(I), I=1, 100)
      </LISTING>

Will abort implied <TT>DO</TT> loop prematurely if run out of data.

Format Statements and Arrays

Arrays can be read/written/printed using FORMAT statements.
      <LISTING>
	     INTEGER SQRS(5)

	     DO 100 I=1, 5
	        SQRS(I) = I**2
	     END DO

	     PRINT 15, (SQRS(I), I=1, 5)
	15   FORMAT(I3, I3, I3, I3, I3)
      </LISTING>
	prints
      <LISTING>
	1  4  9 16 25
      </LISTING>

Can re-use the edit specifiers in the <TT>FORMAT</TT> statement.  But if there are more values than edit specifiers then loop back to the first specifier and start a new line.
      <LISTING>
	     PRINT 15, (MASS(I), I=1, 5)
	15   FORMAT(I3, I3)
      </LISTING>
	prints
      <LISTING>
	1  4
	9 16
	25
      </LISTING>

Use edit multipliers to avoid starting new lines.
      <LISTING>
	15   FORMAT(5I3)
      </LISTING>

Array Arguments

Arrays can be passed into and out of user-defined functions and subroutines as array arguments.

As with passing simple variables as arguments, array variables must first be declared in the main program.

Important: Pass both the array name and the array size as arguments.  Must re-declare array inside the function or subroutine.
      <LISTING>
	      PROGRAM TEST

	      INTEGER MAXSIZ
	      PARAMETER (MAXSIZ=10)
	      INTEGER SCORES(MAXSIZ)
	      ...
	      PRINT *, GETMAX(SCORES, MAXSIZ)
	      STOP
	      END

	      INTEGER FUNCTION GETMAX (LIST, SIZE)
	C     Finds the highest value in the list

	C     Declare arguments
	      INTEGER SIZE, LIST(SIZE)
	      ...
	      RETURN
	      END
      </LISTING>

Input Array Arguments

As with simple variable arguments, input array arguments should not be re-assigned.

      Right:
      <LISTING>
	MAX = LIST(1)
	IF (MAX .GT. LIST(N)) ...
      </LISTING>

      Wrong:
      <LISTING>
	LIST(N) = ...
      </LISTING>

Whole arrays can be passed in as input arguments
      <LISTING>
	PRINT *, GETMAX(SCORES, MAXSIZ)
      </LISTING>
	or individual values can be passed as input arguments, just like simple variables.
      <LISTING>
	PRINT *, FACT(SCORES(3))
      </LISTING>

Output Array Arguments

If an array is an output argument (i.e. passed back to the main program) then the array values can and must be changed.
      <LISTING>
	      ...
	      CALL ZERO(SCORES, MAXSIZ)
	      ...

	      SUBROUTINE ZERO(LIST, SIZE)
	C     Initialize an list to zero values.

	C     Declare arguments
	      INTEGER SIZE, LIST(SIZE)

	C     Declare local variables
	      INTEGER COUNT

	      DO COUNT = 1, SIZE
	         LIST(COUNT) = 0
	      END DO

	      RETURN
	      END
      </LISTING>

Whole arrays can be passed back as output arguments
      <LISTING>
	CALL ZERO(SCORES, MAXSIZ)
      </LISTING>
	or individual values can be passed as output arguments, just like simple variables.
      <LISTING>
	CALL SORT(SCORES(1), SCORES(3))
     </LISTING>

<ADDRESS>

Copyright &copy 1996 Modified from<!WA2><!WA2><!WA2>Gareth S. Bestor (<!WA3><!WA3><!WA3>bestor@cs.wisc.edu).  Last modified October 11, 1996.

</ADDRESS>


text:
package org.apache.camel.processor.jpa;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.examples.SendEmail;
import org.junit.jupiter.api.Test;

public class JpaBatchConsumerTest extends AbstractJpaTest {

    protected static final String SELECT_ALL_STRING = "select x from " + SendEmail.class.getName() + " x";

    @Test
    public void testBatchConsumer() throws Exception {
        // first create two records
        template.sendBody("jpa://" + SendEmail.class.getName(), new SendEmail("foo@beer.org"));
        template.sendBody("jpa://" + SendEmail.class.getName(), new SendEmail("bar@beer.org"));

        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(2);
        mock.message(0).exchangeProperty(Exchange.BATCH_INDEX).isEqualTo(0);
        mock.message(0).exchangeProperty(Exchange.BATCH_COMPLETE).isEqualTo(false);
        mock.message(1).exchangeProperty(Exchange.BATCH_INDEX).isEqualTo(1);
        mock.message(1).exchangeProperty(Exchange.BATCH_COMPLETE).isEqualTo(true);
        mock.expectedPropertyReceived(Exchange.BATCH_SIZE, 2);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("jpa://" + SendEmail.class.getName() + "?delay=2000").to("mock:result");
            }
        };
    }

    @Override
    protected String routeXml() {
        return "org/apache/camel/processor/jpa/springJpaRouteTest.xml";
    }

    @Override
    protected String selectAllString() {
        return SELECT_ALL_STRING;
    }
}


text:
- [Description](#description)
- [Signature](#signature)
- [How it works](#how-it-works)
- [Performance considerations](#performance-considerations)
- [Differences from m.render](#differences-from-mrender)

---

### Description

Activates a component, enabling it to autoredraw on user events

```javascript
var state = {
	count: 0,
	inc: function() {state.count++}
}

var Counter = {
	view: function() {
		return m("div", {onclick: state.inc}, state.count)
	}
}

m.mount(document.body, Counter)
```

---

### Signature

`m.mount(element, component)`

Argument    | Type                 | Required | Description
----------- | -------------------- | -------- | ---
`element`   | `Element`            | Yes      | A DOM element that will be the parent node to the subtree
`component` | `Component|null`     | Yes      | The [component](components.md) to be rendered. `null` unmounts the tree and cleans up internal state.
**returns** |                      |          | Returns nothing

[How to read signatures](signatures.md)

---

### How it works

Similar to [`m.render()`](render.md), the `m.mount()` method takes a component and mounts a corresponding DOM tree into `element`. If `element` already has a DOM tree mounted via a previous `m.mount()` call, the component is diffed against the previous vnode tree and the existing DOM tree is modified only where needed to reflect the changes. Unchanged DOM nodes are not touched at all.

#### Replace a component

Running `mount(element, OtherComponent)` where `element` is a current mount point replaces the component previously mounted with `OtherComponent`.

#### Unmount

Using `m.mount(element, null)` on an element with a previously mounted component unmounts it and cleans up Mithril internal state. This can be useful to prevent memory leaks when removing the `root` node manually from the DOM.

---

### Performance considerations

It may seem wasteful to generate a vnode tree on every redraw, but as it turns out, creating and comparing Javascript data structures is surprisingly cheap compared to reading and modifying the DOM.

Touching the DOM can be extremely expensive for a couple of reasons. Alternating reads and writes can adversely affect performance by causing several browser repaints to occur in quick succession, whereas comparing virtual dom trees allows writes to be batched into a single repaint. Also, the performance characteristics of various DOM operations vary between implementations and can be difficult to learn and optimize for all browsers. For example, in some implementations, reading `childNodes.length` has a complexity of O(n); in some, reading `parentNode` causes a repaint, etc.

In contrast, traversing a javascript data structure has a much more predictable and sane performance profile, and in addition, a vnode tree is implemented in such a way that enables modern javascript engines to apply aggressive optimizations such as hidden classes for even better performance.

---

### Differences from m.render

A component rendered via `m.mount` automatically auto-redraws in response to view events, `m.redraw()` calls or `m.request()` calls. Vnodes rendered via `m.render()` do not. Note that calls to `m.prop()` do not trigger auto-redraws.

`m.mount()` is suitable for application developers integrating Mithril widgets into existing codebases where routing is handled by another library or framework, while still enjoying Mithril's auto-redrawing facilities.

`m.render()` is suitable for library authors who wish to manually control rendering (e.g. when hooking to a third party router, or using third party data-layer libraries like Redux).


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/arc/screen_capture/arc_screen_capture_bridge.h"

#include <utility>
#include <vector>

#include "ash/components/arc/arc_browser_context_keyed_service_factory_base.h"
#include "ash/components/arc/session/arc_bridge_service.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/singleton.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "chrome/browser/ash/arc/screen_capture/arc_screen_capture_session.h"
#include "chrome/browser/media/webrtc/desktop_media_list_ash.h"
#include "content/public/browser/browser_thread.h"

namespace {
constexpr char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
constexpr char kTestImageRelease[] = "testimage";
}  // namespace

namespace arc {
namespace {

// Singleton factory for ArcScreenCaptureBridge
class ArcScreenCaptureBridgeFactory
    : public internal::ArcBrowserContextKeyedServiceFactoryBase<
          ArcScreenCaptureBridge,
          ArcScreenCaptureBridgeFactory> {
 public:
  // Factory name used by ArcBrowserContextKeyedServiceFactoryBase.
  static constexpr const char* kName = "ArcScreenCaptureBridgeFactory";

  static ArcScreenCaptureBridgeFactory* GetInstance() {
    return base::Singleton<ArcScreenCaptureBridgeFactory>::get();
  }

 private:
  friend base::DefaultSingletonTraits<ArcScreenCaptureBridgeFactory>;
  ArcScreenCaptureBridgeFactory() = default;
  ~ArcScreenCaptureBridgeFactory() override = default;
};

}  // namespace

// static
ArcScreenCaptureBridge* ArcScreenCaptureBridge::GetForBrowserContext(
    content::BrowserContext* context) {
  return ArcScreenCaptureBridgeFactory::GetForBrowserContext(context);
}

ArcScreenCaptureBridge::PendingCaptureParams::PendingCaptureParams(
    std::unique_ptr<DesktopMediaPicker> picker,
    const std::string& display_name,
    RequestPermissionCallback callback)
    : picker(std::move(picker)),
      display_name(display_name),
      callback(std::move(callback)) {}

ArcScreenCaptureBridge::PendingCaptureParams::~PendingCaptureParams() {}

ArcScreenCaptureBridge::GrantedCaptureParams::GrantedCaptureParams(
    const std::string& display_name,
    content::DesktopMediaID desktop_id,
    bool enable_notification)
    : display_name(display_name),
      desktop_id(desktop_id),
      enable_notification(enable_notification) {}

ArcScreenCaptureBridge::GrantedCaptureParams::~GrantedCaptureParams() {}

ArcScreenCaptureBridge::ArcScreenCaptureBridge(content::BrowserContext* context,
                                               ArcBridgeService* bridge_service)
    : arc_bridge_service_(bridge_service) {
  arc_bridge_service_->screen_capture()->SetHost(this);
}

ArcScreenCaptureBridge::~ArcScreenCaptureBridge() {
  arc_bridge_service_->screen_capture()->SetHost(nullptr);
}

void ArcScreenCaptureBridge::RequestPermission(
    const std::string& display_name,
    const std::string& package_name,
    RequestPermissionCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  std::unique_ptr<DesktopMediaPicker> picker = DesktopMediaPicker::Create();
  std::vector<std::unique_ptr<DesktopMediaList>> source_lists;
  source_lists.emplace_back(
      std::make_unique<DesktopMediaListAsh>(DesktopMediaList::Type::kScreen));
  const std::u16string display_name16 = base::UTF8ToUTF16(display_name);
  DesktopMediaPicker::Params picker_params;
  picker_params.context = ash::Shell::GetRootWindowForDisplayId(
      display::Screen::GetScreen()->GetPrimaryDisplay().id());
  picker_params.modality = ui::ModalType::MODAL_TYPE_SYSTEM;
  picker_params.app_name = display_name16;
  picker_params.target_name = display_name16;
  if (pending_permissions_map_.find(package_name) !=
      pending_permissions_map_.end()) {
    LOG(ERROR) << "Screen capture permissions requested while pending request "
                  "was active: "
               << package_name;
    std::move(callback).Run(false);
    return;
  }
  pending_permissions_map_.emplace(
      std::piecewise_construct, std::forward_as_tuple(package_name),
      std::forward_as_tuple(std::move(picker), display_name,
                            std::move(callback)));
  pending_permissions_map_.find(package_name)
      ->second.picker->Show(
          picker_params, std::move(source_lists),
          base::BindOnce(&ArcScreenCaptureBridge::PermissionPromptCallback,
                         base::Unretained(this), package_name));
}

void ArcScreenCaptureBridge::PermissionPromptCallback(
    const std::string& package_name,
    content::DesktopMediaID desktop_id) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  auto found = pending_permissions_map_.find(package_name);
  if (found == pending_permissions_map_.end()) {
    // This is normal if the dialog was accepted from testing.
    return;
  }
  if (desktop_id.is_null()) {
    std::move(found->second.callback).Run(false);
    pending_permissions_map_.erase(found);
    return;
  }
  // Remove any existing entry since emplace will not overwrite it.
  // This is OK since these persist forever and this may be requested again with
  // a different desktop.
  granted_permissions_map_.erase(package_name);
  granted_permissions_map_.emplace(
      package_name, GrantedCaptureParams(found->second.display_name, desktop_id,
                                         true /* enable notification */));
  std::move(found->second.callback).Run(true);
  pending_permissions_map_.erase(found);
}

void ArcScreenCaptureBridge::TestModeAcceptPermission(
    const std::string& package_name) {
  std::string track;
  if (!base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &track))
    return;
  if (track.find(kTestImageRelease) == std::string::npos)
    return;
  // We are a testimage build, so this call is allowed. To do this, invoke the
  // Mojo callback after taking it from our map. This will prevent it from
  // getting called when we forcibly close the dialog.
  auto found = pending_permissions_map_.find(package_name);
  if (found == pending_permissions_map_.end()) {
    LOG(ERROR) << "Requested to accept dialog for testing, but dialog not "
                  "being shown for "
               << package_name;
    return;
  }
  granted_permissions_map_.erase(package_name);
  granted_permissions_map_.emplace(
      package_name,
      GrantedCaptureParams(found->second.display_name,
                           content::DesktopMediaID::RegisterNativeWindow(
                               content::DesktopMediaID::TYPE_SCREEN,
                               ash::Shell::GetPrimaryRootWindow()),
                           false /* enable notification */));
  std::move(found->second.callback).Run(true);
  pending_permissions_map_.erase(found);
  // The dialog will be closed when 'found' goes out of scope and is
  // destructed and the dialog within it is destructed.

  // If we're auto-sharing the screen in test mode, we don't want to record
  // the cursor, so turn it off.
  ash::Shell::Get()->cursor_manager()->HideCursor();
}

void ArcScreenCaptureBridge::OpenSession(
    mojo::PendingRemote<mojom::ScreenCaptureSessionNotifier> notifier,
    const std::string& package_name,
    const gfx::Size& size,
    OpenSessionCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  auto found = granted_permissions_map_.find(package_name);
  if (found == granted_permissions_map_.end()) {
    LOG(ERROR) << "Attempt to open screen capture session without granted "
                  "permissions for package "
               << package_name;
    std::move(callback).Run(mojo::NullRemote());
    return;
  }

  // TODO(crbug.com/955171): Remove this temporary conversion to InterfacePtr
  // once OpenSession callback from
  // //ash/components/arc/mojom/screen_capture.mojom could take pending_remote
  // directly. Refer to crrev.com/c/1868870.
  mojo::PendingRemote<mojom::ScreenCaptureSession>
      screen_capture_session_remote(ArcScreenCaptureSession::Create(
          std::move(notifier), found->second.display_name,
          found->second.desktop_id, size, found->second.enable_notification));
  std::move(callback).Run(std::move(screen_capture_session_remote));
}

}  // namespace arc


text:
import * as b from 'bobril';

export const margin = 25;

export const contentWrapper = b.styleDef({
    width: '100%'
});

export * from './stylesPc';


text:
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.MD5PasswordHasher',
)

MOZILLIANS_API_APPNAME = 'something'
MOZILLIANS_API_BASE = 'https://shouldneveractuallybeused.net'
MOZILLIANS_API_KEY = 'supersecret'

VIDLY_API_URL = 'http://vid.ly.shouldneveractuallybeused.com/api/'

# So that we never accidentally send tweets during tests
TWITTER_CONSUMER_KEY = \
TWITTER_CONSUMER_SECRET = \
TWITTER_ACCESS_TOKEN = \
TWITTER_ACCESS_TOKEN_SECRET = "test"
TWEETER_BACKEND = None

URL_TRANSFORM_PASSWORDS = {
    'bla': 'bla',
}

BITLY_ACCESS_TOKEN = '123456789'

# don't accidentally send anything to sentry whilst running tests
RAVEN_CONFIG = {}
SENTRY_DSN = None

SITE_URL = 'http://localhost:8000'

AWS_ACCESS_KEY_ID = AWS_SECRET_ACCESS_KEY = 'something'
#S3_UPLOAD_BUCKET = 'air-mozilla-uploads'

EDGECAST_SECURE_KEY = 'soemthing'

BROWSERID_AUDIENCES = ['http://testserver']

import tempfile
MEDIA_ROOT = tempfile.mkdtemp(prefix='testmedia')

SCRAPE_CREDENTIALS = {}

LOG_SEARCHES = True

TWITTER_USERNAME = 'airmozilla'

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

VIDLY_USER_ID = 'any...'
VIDLY_USER_KEY = '...thing not empty'
EDGECAST_SECURE_KEY = 'anythingheretoo'

ALLOWED_BID = (
    'mozilla.com',
)

# Use memcached only for session storage
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

# deliberately set so tests never actually accidentally use it
AUTOCOMPETER_URL = 'https://autocompeter.example/v1'
AUTOCOMPETER_DOMAIN = ''


text:
package io.vertx.pgclient.impl.codec;

import io.vertx.sqlclient.impl.RowDesc;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class PgRowDesc extends RowDesc {

  static PgRowDesc createBinary(PgColumnDesc[] columns) {
    // Fix to use binary when possible
    return new PgRowDesc(Arrays.stream(columns)
      .map(c -> new PgColumnDesc(
        c.name,
        c.relationId,
        c.relationAttributeNo,
        c.dataType,
        c.length,
        c.typeModifier,
        c.dataType.supportsBinary ? DataFormat.BINARY : DataFormat.TEXT))
      .toArray(PgColumnDesc[]::new));
  }

  static PgRowDesc create(PgColumnDesc[] columns) {
    return new PgRowDesc(columns);
  }

  final PgColumnDesc[] columns;

  private PgRowDesc(PgColumnDesc[] columns) {
    super(Collections.unmodifiableList(Stream.of(columns)
      .map(d -> d.name)
      .collect(Collectors.toList())), Collections.unmodifiableList(Arrays.asList(columns)));
    this.columns = columns;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Controles.Resources;

namespace Controles
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnBtnSampleClicked(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button == null || button.Tag == null)
            {
                MessageBox.Show("Aucune page n'est indiquée sur ce bouton.");
                return;
            }

            Uri navigateUri;
            if (!Uri.TryCreate(button.Tag.ToString(), UriKind.RelativeOrAbsolute, out navigateUri))
            {
                MessageBox.Show("La page indiquée a un format incorrect.");
                return;
            }

            NavigationService.Navigate(navigateUri);
        }
    }
}


text:
package smoketest.web.secure;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class SampleWebSecureApplication implements WebMvcConfigurer {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("home");
		registry.addViewController("/login").setViewName("login");
	}

	public static void main(String[] args) {
		new SpringApplicationBuilder(SampleWebSecureApplication.class).run(args);
	}

}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Preview\Understand\Assistant\Task;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @property string $accountSid
 * @property string $assistantSid
 * @property string $taskSid
 * @property int $samplesCount
 * @property int $fieldsCount
 * @property string $url
 */
class TaskStatisticsInstance extends InstanceResource {
    /**
     * Initialize the TaskStatisticsInstance
     *
     * @param Version $version Version that contains the resource
     * @param mixed[] $payload The response payload
     * @param string $assistantSid The unique ID of the parent Assistant.
     * @param string $taskSid The unique ID of the Task associated with this Field.
     */
    public function __construct(Version $version, array $payload, string $assistantSid, string $taskSid) {
        parent::__construct($version);

        // Marshaled Properties
        $this->properties = [
            'accountSid' => Values::array_get($payload, 'account_sid'),
            'assistantSid' => Values::array_get($payload, 'assistant_sid'),
            'taskSid' => Values::array_get($payload, 'task_sid'),
            'samplesCount' => Values::array_get($payload, 'samples_count'),
            'fieldsCount' => Values::array_get($payload, 'fields_count'),
            'url' => Values::array_get($payload, 'url'),
        ];

        $this->solution = ['assistantSid' => $assistantSid, 'taskSid' => $taskSid, ];
    }

    /**
     * Generate an instance context for the instance, the context is capable of
     * performing various actions.  All instance actions are proxied to the context
     *
     * @return TaskStatisticsContext Context for this TaskStatisticsInstance
     */
    protected function proxy(): TaskStatisticsContext {
        if (!$this->context) {
            $this->context = new TaskStatisticsContext(
                $this->version,
                $this->solution['assistantSid'],
                $this->solution['taskSid']
            );
        }

        return $this->context;
    }

    /**
     * Fetch the TaskStatisticsInstance
     *
     * @return TaskStatisticsInstance Fetched TaskStatisticsInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch(): TaskStatisticsInstance {
        return $this->proxy()->fetch();
    }

    /**
     * Magic getter to access properties
     *
     * @param string $name Property to access
     * @return mixed The requested property
     * @throws TwilioException For unknown properties
     */
    public function __get(string $name) {
        if (\array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }

        if (\property_exists($this, '_' . $name)) {
            $method = 'get' . \ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown property: ' . $name);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        $context = [];
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Preview.Understand.TaskStatisticsInstance ' . \implode(' ', $context) . ']';
    }
}


text:
/**
 * @file factorial.h
 * @brief Meta programming for computing factorial
 */

#ifndef MODULES_COMMON_MATH_FACTORIAL_H_
#define MODULES_COMMON_MATH_FACTORIAL_H_

namespace apollo {
namespace common {
namespace math {

template <int N>
struct Factorial {
  enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> {
  enum { value = 1 };
};

}  // namespace math
}  // namespace common
}  // namespace apollo

#endif  // MODULES_COMMON_MATH_FACTORIAL_H_


text:
package org.logicng.testutils;

import org.logicng.datastructures.Assignment;
import org.logicng.formulas.Formula;
import org.logicng.formulas.Variable;
import org.logicng.solvers.MiniSat;
import org.logicng.solvers.SATSolver;

import java.util.List;
import java.util.SortedSet;

/**
 * Help methods for unit testing.
 * @version 2.3.0
 * @since 2.3.0
 */
public final class TestUtil {

    /**
     * Private empty constructor.  Class only contains static utility methods.
     */
    private TestUtil() {
        // Intentionally left empty
    }

    /**
     * Tests if the two given formulas have the same models when projected to the given set of variables.
     * @param f1   first formula
     * @param f2   second formula
     * @param vars the set of variables to which the models should be projected
     * @return {@code true} if the two formulas have the same models when projected to the given set of variables, otherwise {@code false}
     */
    public static boolean equivalentModels(final Formula f1, final Formula f2, final SortedSet<Variable> vars) {
        final SATSolver s = MiniSat.miniSat(f1.factory());
        s.add(f1);
        final List<Assignment> models1 = s.enumerateAllModels(vars);
        s.reset();
        s.add(f2);
        final List<Assignment> models2 = s.enumerateAllModels(vars);
        if (models1.size() != models2.size()) {
            return false;
        }
        for (final Assignment model : models1) {
            if (!models2.contains(model)) {
                return false;
            }
        }
        return true;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
   <mvc:resources mapping="/static/**" location="/static/" cache-period="31556926"/>
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.cqu.edu.ebmis.web.controller" />
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
            </list>
        </property>
    </bean>

    	<!-- 定义视图解析器 -->
	<bean id="velocityConfig"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<property name="resourceLoaderPath" value="/WEB-INF/views/" />
		<property name="configLocation" value="classpath:velocity.properties" />
	</bean>
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
		<property name="suffix" value=".html" />
		<property name="cache" value="false" />
		<property name="contentType" value="text/html;charset=utf-8" />
		<property name="layoutUrl" value="layout/default.vm"/>
		<property name="dateToolAttribute" value="date" /><!--日期函数名称-->
		<property name="numberToolAttribute" value="number" /><!--数字函数名称-->
	</bean>

    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>
    <context:annotation-config />
    <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

    <bean id="contentNegotiationManager"
        class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="favorPathExtension" value="false" />
        <property name="favorParameter" value="false" />
        <property name="ignoreAcceptHeader" value="false" />
        <property name="mediaTypes">
            <value>
                atom=application/atom+xml
                html=text/html
                json=application/json
                *=*/*
            </value>
        </property>
    </bean>
  <mvc:annotation-driven/>
  <mvc:default-servlet-handler/>
</beans>


text:
'use strict';

angular.module("home").controller("HomeController", ['$scope', '$http', '$location', function ($scope, $http, $location) {
  }]);


text:
package org.codehaus.jettison.badgerfish;

import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;

import org.codehaus.jettison.AbstractXMLStreamReader;
import org.codehaus.jettison.Node;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.util.FastStack;

public class BadgerFishXMLStreamReader extends AbstractXMLStreamReader {
    private static final BadgerFishConvention CONVENTION = new BadgerFishConvention();
    private FastStack nodes;
    private String currentText;

    public BadgerFishXMLStreamReader(JSONObject obj)
        throws JSONException, XMLStreamException {
        String rootName = (String) obj.keys().next();
        this.node = new Node(null, rootName, obj.getJSONObject(rootName), CONVENTION);
        this.nodes = new FastStack();
        nodes.push(node);
        event = START_DOCUMENT;
    }

    public int next() throws XMLStreamException {
        if (event == START_DOCUMENT) {
            event = START_ELEMENT;
        } else {
            if (event == END_ELEMENT && nodes.size() != 0) {
                node = (Node) nodes.peek();
            }

            if (node.getArray() != null
                && node.getArray().length() > node.getArrayIndex()) {
                Node arrayNode = node;
                int idx = arrayNode.getArrayIndex();

                try {
                    Object o = arrayNode.getArray().get(idx);
                    processKey(node.getCurrentKey(), o);
                } catch (JSONException e) {
                    throw new XMLStreamException(e);
                }

                idx++;
                arrayNode.setArrayIndex(idx);
            } else if (node.getKeys() != null && node.getKeys().hasNext()) {
                processElement();
            } else {
                if (nodes.size() != 0) {
                    event = END_ELEMENT;
                    node = (Node)nodes.pop();
                } else {
                    event = END_DOCUMENT;
                }
            }
        }

        return event;
    }

    private void processElement() throws XMLStreamException {
        try {
            String nextKey = (String) node.getKeys().next();

            Object newObj = node.getObject().get(nextKey);

            processKey(nextKey, newObj);
        } catch (JSONException e) {
            throw new XMLStreamException(e);
        }
    }

    private void processKey(String nextKey, Object newObj) throws JSONException, XMLStreamException {
        if (nextKey.equals("$")) {
            event = CHARACTERS;
            if (newObj instanceof JSONArray) {
                JSONArray arr = (JSONArray)newObj;
                StringBuilder buf = new StringBuilder();
                for (int i = 0; i < arr.length(); i++) {
                    buf.append(arr.get(i));
                }
                currentText = buf.toString();
            } else {
                currentText = newObj == null ? null : newObj.toString();
            }
            return;
        } else if (newObj instanceof JSONObject) {
            node = new Node((Node)nodes.peek(), nextKey, (JSONObject) newObj, CONVENTION);
            nodes.push(node);
            event = START_ELEMENT;
            return;
        } else if (newObj instanceof JSONArray) {
            JSONArray arr = (JSONArray) newObj;

            if (arr.length() == 0) {
                next();
                return;
            }

            // save some state information...
            node.setArray(arr);
            node.setArrayIndex(1);
            node.setCurrentKey(nextKey);

            processKey(nextKey, arr.get(0));
        }
        else {
            throw new JSONException("Element [" + nextKey + "] did not contain object, array or text content.");
        }
    }

    public void close() throws XMLStreamException {
    }

    public String getAttributeType(int arg0) {
        return null;
    }

    public String getCharacterEncodingScheme() {
        return null;
    }

    public String getElementText() throws XMLStreamException {
        return currentText;
    }

    public NamespaceContext getNamespaceContext() {
        return null;
    }

    public String getText() {
        return currentText;
    }
}


text:
\documentclass{book}
\usepackage[extension=xxx]{hyperref}
\begin{document}
A\footnote{\texttt{abc}}

\href{file://localhost/d:/test2.ps}{foo1}

\href{file://localhost/d:/test2.pdf}{foo2}

\href{d:/test2.pdf}{foo3}

\href{d:/test2.ps}{foo4}

\href{http://www-fourier.ujf-grenoble.fr:80/cgi-bin/zbfr/ZB/math-fr.html?AU=Taylor,+R&format=complete&type=html&maxdocs=10}{weird}

\href{a%b}{hello}

\end{document}


text:
package us.raudi.printdf.ui;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class PrintUI extends Application {

	public static final String WINDOW_TITLE = "PrintDF";

	UiController controller;
	@Override
	public void start(Stage primaryStage) throws Exception {
		FXMLLoader loader = new FXMLLoader(getClass().getResource("PrintUI.fxml"));
		Scene scene = new Scene(loader.load());

		controller = loader.getController();
		controller.setStage(primaryStage);

		Image img = new Image(getClass().getResource("PrintDF.png").toExternalForm());

		primaryStage.setTitle(WINDOW_TITLE);
		primaryStage.getIcons().add(img);
		primaryStage.setScene(scene);
		primaryStage.setResizable(false);
		primaryStage.show();
	}

	@Override
	public void stop(){
	    if(controller != null) {
			try {
				controller.saveSettings();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	}

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


text:
package com.twitter.graphjet.hashing;

import java.util.Collections;
import java.util.List;

import com.google.common.collect.Lists;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

import com.twitter.graphjet.stats.NullStatsReceiver;

public class ShardedBigIntArrayTest {

  @Test
  public void testSequentialReadWrites() {
    int maxNumNodes = 1 << 16;
    int shardSize = 1 << 10;
    int nullEntry = -1;
    ShardedBigIntArray shardedBigIntArray = new ShardedBigIntArray(
        maxNumNodes / 16, shardSize, nullEntry, new NullStatsReceiver());

    for (int i = 0; i < maxNumNodes; i++) {
      int entry = i * 2;
      assertEquals(nullEntry, shardedBigIntArray.getEntry(i));
      shardedBigIntArray.addEntry(entry, i);
      assertEquals(entry, shardedBigIntArray.getEntry(i));
    }

    for (int i = 0; i < maxNumNodes; i++) {
      assertEquals(nullEntry, shardedBigIntArray.getEntry(maxNumNodes + i));
    }
  }

  @Test
  public void testRandomReadWrites() {
    int maxNumNodes = 1 << 16;
    int shardSize = 1 << 10;
    int nullEntry = -1;
    List<Integer> indexList = Lists.newArrayListWithCapacity(maxNumNodes);
    ShardedBigIntArray shardedBigIntArray = new ShardedBigIntArray(
        maxNumNodes / 16, shardSize, nullEntry, new NullStatsReceiver());

    for (int i = 0; i < maxNumNodes; i++) {
      indexList.add(i);
    }

    Collections.shuffle(indexList);
    for (Integer index : indexList) {
      int entry = index * 2;
      assertEquals(nullEntry, shardedBigIntArray.getEntry(index));
      shardedBigIntArray.addEntry(entry, index);
      assertEquals(entry, shardedBigIntArray.getEntry(index));
    }

    for (int i = 0; i < maxNumNodes; i++) {
      assertEquals(i * 2, shardedBigIntArray.getEntry(i));
    }

    for (int i = 0; i < maxNumNodes; i++) {
      assertEquals(nullEntry, shardedBigIntArray.getEntry(maxNumNodes + i));
    }
  }
}


text:
layout: shared/narrow
title: "Implement the App Shell"
description: "How do I use an an app shell within a Progressive Web App?"
published_on: 2016-02-04
updated_on: 2016-02-04
translation_priority: 1
order: 2
authors:
  - petelepage
notes:
  learn-about-wsk: "Learn more about the Web Starter Kit"
  image-sprite: "Specifying each icon individually might seem less efficient compared to using an image sprite, but we'll cache those later as part of the app shell, ensuring that they're always available, without the need to make a network request."
  give-you: "We've given you the markup and styles to save you some time and make sure you're starting on a solid foundation. In the next section, you'll have an opportunity to write your own code."
---

There are multiple ways to get started with any project, and we generally
recommend using Web Starter Kit. But, in this case, to keep our project as
simple as possible and concentrate on Progressive Web Apps, we've provided you
with all of the resources you'll need.

{% include shared/toc.liquid %}

## Download the code

You can [download all of the code for this progressive web app guide](pwa-weather.zip) in a
ZIP file for easy use. Each step and all of the resources you need are
available in the ZIP.

## Create the HTML for the App Shell

To make sure that we're starting as cleanly as possible, we'll start with a
brand new `index.html` file and add the core components we discussed in
[Architect the App Shell](step-01).

Remember, the key components will consist of:

* Header with a title, and add/refresh buttons
* Container for forecast cards
* A forecast card template
* A dialog for adding new cities
* A loading indicator

{% highlight html %}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather App</title>

Weather App

    <button id="butRefresh" class="headerButton"></button>
    <button id="butAdd" class="headerButton"></button>

    <svg viewBox="0 0 32 32" width="32" height="32">
      <circle id="spinner" cx="16" cy="16" r="14" fill="none"></circle>
    </svg>

{% endhighlight %}

Notice the `main` content is `hidden` by default and the loader is visible. This
ensures that the user sees the loader immediately as the page loads, giving them
a clear indication that the content is loading.

Next, let's add the forecast card, and Add New City dialog. To save time, these
are provided in the `resources` directory, so you can simply copy and paste them
into the corresponding location.

## Add styles to the core UI components

It's now time to add the core styles. As part of our build and deployment
process, we'll want to inline these core styles into the document body, but for
now, let's put them into a separate CSS file.

In the `index.html` file, replace `<!-- Insert link to styles here -->` with:
{% highlight html %}
<link rel="stylesheet" type="text/css" href="styles/inline.css">
{% endhighlight %}

To save time, we've already created the
[stylesheet](https://weather-pwa-sample.firebaseapp.com/styles/inline.css) for
you to use. Take a few minutes to review it and customize it to make it more
your own.

{% include shared/note.liquid list=page.notes.image-sprite %}

## Test things out and make adjustments

Now is a great time to test things out, see how they look and make any
adjustments you want. Be sure to test the rendering of your forecast card by
removing the `hidden` attribute from the `main` container, and adding some fake data
to the card.

{% include shared/remember.liquid list=page.notes.give-you %}

This app is reasonably responsive right now, but it's not perfect. Try adding
additional styles that will improve the responsiveness and make it really shine
across different devices. Also, consider what you can do to make it more your
own.

## Add the key JavaScript bootstrap code

Now that we have most of the UI ready, it's time to start hooking up the code to
make everything work. Like the rest of the app shell, be conscious about what
code is necessary as part of the key experience and what can be loaded later.

In our bootstrap code, we've included:

* An `app` object that contains some of the key information necessary for the app.
* The event listeners for all of the buttons in the header (`add`/`refresh`) and in
  the add city dialog (`add`/`cancel`).
* A method to add or update forecast cards (`app.updateForecastCard`).
* A method to get the latest weather forecast data from the Firebase Public
  Weather API (`app.getForecast`).
* A method to iterate the current cards and call `app.getForecast` to get the
  latest forecast data (`app.updateForecasts`).
* Some fake data (`fakeForecast`) you can use to quickly test how things render.

Add the JavaScript code

1. Copy `step3-app.js` from the `resources` directory to your `scripts` folder
   and rename it `app.js`
1. In the `index.html` file, add a link to the newly created `app.js`.

   `<script src="/scripts/app.js"></script>`

## Test it out

Now that you've added the core HTML, styles and JavaScript, it's time to test the
app. While it may not do much yet, make sure it doesn't write errors to the
console.

To see how the fake weather data is rendered, add the line below to your `app.js`
file:
`app.updateForecastCard(fakeForecast);`

Try it


text:
Setting Up WSL
=====================

Windows 10 introduced a new feature called Windows Subsystem for Linux (WSL), which allows the installation of various linux distributions directly in Windows. This feature has mostly removed the need to use virtual machine setups.

<!-- markdown-toc start -->
**Table of Contents**

- [Preparing to install Windows Subsystem for Linux](#preparing-to-install-windows-subsystem-for-linux)
- [Installing WSL from the Microsoft Store](#installing-wsl-from-the-microsoft-store)
- [Initial Setup of WSL](#initial-setup-of-wsl)
- [Proceed to Gitian Setup for Windows](#proceed-to-gitian-setup-for-windows)

<!-- markdown-toc end -->

Preparing to install Windows Subsystem for Linux
-------------------------------------------------

To install WSL, you first need to enable the Windows Subsystem for Linux extra feature.

First, open up the Windows Control panel and click on Programs:

![](./img/windows-wsl-install-1-control-panel-home.png)

Then, click on "Turn Windows features on or off":

![](./img/windows-wsl-install-2-control-panel-programs.png)

In the new window, scroll down and check the box next to "Windows Subsystem for Linux":

![](./img/windows-wsl-install-3-enable-windows-features.png)

Click "OK" and reboot if necessary.

Installing WSL From the Microsoft Store
----------------------------------------

Once your system has been configured to support WSL, Installation is just a matter of opening up the Microsoft Store app and searching for "Ubuntu".

There may be more than one result, but the one we use is "Ubuntu 18.04 LTS". Click on it's preview icon, then click "Install"

Once installed, you can click "Launch" from the Microsoft Store, or use the new Start menu item.
![](./img/windows-wsl-install-4-ubuntu-from-msstore.png)

Initial Setup of WSL
---------------------

The first time you launch Ubuntu 18.04 LTS, you will be asked to setup a username and password. These are separate from your Windows username and password:

![](./img/windows-wsl-install-5-wsl-setup-user.png)

After initial setup and user creation, make sure the system is up to date by running the following commands:

    sudo apt update
    sudo apt upgrade

*Note: whenever you run a command that starts with `sudo`, it is instructing the system to run the following commands with elevated privileges. You may be asked for your linux account's password.*

We then need to set the `DOCKER_HOST` environment variable and fix the `PATH` environment variable to strip out unwanted windows paths. Run the following commands:

    echo "export DOCKER_HOST=tcp://localhost:2375" >> ~/.bashrc
    echo "PATH=$(echo "$PATH" | sed -e 's/:\/mnt.*//g')" >> ~/.bashrc
    source ~/.bashrc

Next, edit the `/etc/wsl.conf` file to fix the Windows mount points to work with Docker. Run the following command:

    sudo nano /etc/wsl.conf

This will bring up the nano text editor, copy and paste the below (default paste action in a WSL window is right click).

    [automount]
    root = /
    options = "metadata"

Your screen should now look similar to this image:
![](./img/windows-wsl-install-6-wsl-setup-mounts.png)

Save (`ctrl+x`) the file, confirm you want to write to `/etc/wsl.conf` (press enter), then reboot your computer for the changes to take effect.

Proceed to Gitian Setup for Windows
------------------------------------

WSL is now prepared for use with Gitian, proceed to [Setup Gitian on Windows](./gitian-setup-windows.md).


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

AHMED ÞÝRANÝ

Geri

Son devir Osmanlý âlimlerinden. Ýsmi Ahmed Þîrânî Efendidir. Babasý Zürrâ'dan Mahmûd
Aðadýr. 1879 (H.1297) senesi Þiran kazâsýnýn Karaca köyünde doðdu. Medrese tahsîlini
bitirerek 1909 senesinde icâzet, diploma aldý. Müderrislik imtihanýný baþarý ile verdi.
Dâr-ül-Hikmet-i Ýslâmiyye memuriyeti, Cerîde-i Ýlmiyye Müdürlüðü yaptý. 1916'da da Sahn
Medresesi fýkýh müderrisliðine tâyin edildi. 1920'de Medreset-ül-Ýrþâd müdürü oldu. 1922'de
Konya Ýmam ve Hatip Mektebi müdür ve muallimliði, 1924'te Ýstanbul Ýmâm-Hatip Mektebi
hocasý oldu.

Türkçe, Arapça ve Farsçanýn yanýnda Fransýzca da bilen Ahmed Þîrânî Efendi,
Hayru'l-Kelâm ve Ý'tisâm isimlerinde mecmualar neþretti. Bu mecmualardaki yazýlarýnda

devrin reformcu ve mezhepsizleriyle mücâdele ederek, cevaplar verdi. Bir ara Ýttihatçýlarca
dîvân-ý harbe verilen Ahmed Þîrânî, mecmuasýnda bunlara þöyle cevap verdi:

Bir insan Allah'ý, Peygamberi, din ve mezhepleri inkâr ettikten sonra, "Benim nazarýmda din
ve mezhep, Kur'ân ve hadîsten ibârettir." derse, onda ilim ve irfân, akýl ve idrâk, muntazam
dimað, saðlam hâfýza bulunur mu?

"Benim nazarýmda dört imâm denilen muhterem zâtlar, Ýslâmî ilimlerde rusûh sâhibi, derin
âlim ve ictihâda kâdir, gücü yeten bir âlimden baþka bir þey deðillerdir." diyorsunuz. Bunun
hilâfýný, aksini iddiâ edecek kimse bulunmadýðýna göre anlatmak istediðiniz bir maksad var.
Fakat pek câhil olduðunuz için istediðiniz þekilde anlatamadýnýz. Demek istiyorsunuz ki:
"Ben onlarýn ilmî þahsiyetlerini tanýrým, fakat mezheplerini tanýmam." Artýk size ne diyeyim.
Açýklanmasý güç, gizlenmesi güç bir vereme tutulmuþsunuz. Bir mürþidin, yol göstericinin
irþâd eteðine, bir âlimin îkâz rahlesine (önüne) vakit geçirmeksizin mürâcaat etmenizi din
kardeþliði nâmýna tavsiye ederiz.

1) Son Devrin Ýslâm Akademisi; s.166

2) Þeriatten Lâikliðe; s.310

3) Son Devir Osmanlý Ulemâsý; c.1, s.226


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
BinTreeUtil
</TITLE>

<META NAME="keywords" CONTENT="jpaul.Graphs.BinTreeUtil class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

jpaul.Graphs

Class BinTreeUtil

java.lang.Object
  jpaul.Graphs.BinTreeUtil

public final class BinTreeUtil
extends java.lang.Object

BinTreeUtil is a wrapper for binary tree utilities.
 It is a non-instantiatable class with useful static members,
 similar to java.util.Collections.

Version:

$Id: BinTreeUtil.java,v 1.17 2006/03/21 17:37:30 adam_kiezun Exp $

Author:

Alexandru Salcianu - salcianu@alum.mit.edu

Method Summary

static

<T,T2 extends T>

java.util.Iterator<T>

inOrder(T2 root,
        BinTreeNavigator<T2> binTreeNav)

          Returns an iterator that traverses all vertices of a binary
        tree in inorder.

static

<T> void

inOrder(T root,
        BinTreeNavigator<T> binTreeNav,
        Action<T> action)

          Executes an action on all nodes from a tree, in inorder.

static

<T,T2 extends T>

java.util.Iterator<T>

postOrder(T2 root,
          BinTreeNavigator<T2> binTreeNav)

          Returns an iterator that traverses all vertices of a binary
        tree in postorder.

static

<T> void

postOrder(T root,
          BinTreeNavigator<T> binTreeNav,
          Action<T> action)

          Executes an action on all nodes from a tree, in postorder.

static

<T,T2 extends T>

java.util.Iterator<T>

preOrder(T2 root,
         BinTreeNavigator<T2> binTreeNav)

          Returns an iterator that traverses all vertices of a binary
        tree in preorder.

static

<T> void

preOrder(T root,
         BinTreeNavigator<T> binTreeNav,
         Action<T> action)

          Executes an action on all nodes from a tree, in preorder.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

inOrder

public static <T> void inOrder(T root,
                               BinTreeNavigator<T> binTreeNav,
                               Action<T> action)

Executes an action on all nodes from a tree, in inorder.  For
        trees with sharing, the same tree node object will be visited
        multiple times.

Parameters:
root - Binary tree root.
binTreeNav - Binary tree navigator.
action - Action to execute on each tree node.

preOrder

public static <T> void preOrder(T root,
                                BinTreeNavigator<T> binTreeNav,
                                Action<T> action)

Executes an action on all nodes from a tree, in preorder.  For
        trees with sharing, the same tree node object will be visited
        multiple times.

Parameters:
root - Binary tree root.
binTreeNav - Binary tree navigator.
action - Action to execute on each tree node.

postOrder

public static <T> void postOrder(T root,
                                 BinTreeNavigator<T> binTreeNav,
                                 Action<T> action)

Executes an action on all nodes from a tree, in postorder.  For
        trees with sharing, the same tree node object will be visited
        multiple times.

Parameters:
root - Binary tree root.
binTreeNav - Binary tree navigator.
action - Action to execute on each tree node.

inOrder

public static <T,T2 extends T> java.util.Iterator<T> inOrder(T2 root,
                                                             BinTreeNavigator<T2> binTreeNav)

Returns an iterator that traverses all vertices of a binary
        tree in inorder.  The iterator is lazy: it does not construct
        an explicit list with the tree vertices in inorder; instead,
        vertices are returned one-by-one, on demand.  The time
        complexity of iterating over an entire tree is linear in the
        tree size; the space complexity is linear in the tree depth.

Note1: the complication with two type parameters
        simulates the common-sense fact that the iterator subtyping is
        co-variant with the element subtyping.

Note2: supports trees with sharing; shared nodes
        will be returned multiple times.

Note3: of we had a parent pointer, it would have
        been possible to do the traversal with O(1) additional space;
        however, to simplify the interface, no such information is
        provided by the tree navigator, and we have to maintain an
        explicit stack of parent nodes.

Parameters:
root - The root node of the binary tree.
binTreeNav - The binary tree navigator.

preOrder

public static <T,T2 extends T> java.util.Iterator<T> preOrder(T2 root,
                                                              BinTreeNavigator<T2> binTreeNav)

Returns an iterator that traverses all vertices of a binary
        tree in preorder.  The iterator is lazy: it does not construct
        an explicit list with the tree vertices in preorder; instead,
        vertices are returned one-by-one, on demand.  The time
        complexity of iterating over an entire tree is linear in the
        tree size; the space complexity is linear in the tree depth.

All notes for inOrder
        apply to this method too.

Parameters:
root - The root node of the binary tree.
binTreeNav - The binary tree navigator.

postOrder

public static <T,T2 extends T> java.util.Iterator<T> postOrder(T2 root,
                                                               BinTreeNavigator<T2> binTreeNav)

Returns an iterator that traverses all vertices of a binary
        tree in postorder.  The iterator is lazy: it does not construct
        an explicit list with the tree vertices in postorder; instead,
        vertices are returned one-by-one, on demand.  The time
        complexity of iterating over an entire tree is linear in the
        tree size; the space complexity is linear in the tree depth.

All notes for inOrder
        apply to this method too.

Parameters:
root - The root node of the binary tree.
binTreeNav - The binary tree navigator.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 2005 Alexandru Salcianu - salcianu@alum.mit.edu


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%highlight{%-8p [%d{yyyy-MM-dd HH:mm:ss}] %c %L: %m%n}"/>
        </Console>
        <RollingFile name="RollingFile_additivity" fileName="mylogs/additivity/log.out" filePattern="mylogs/additivity/log.out.%i">
            <PatternLayout>
                <pattern>%-8p [%d{yyyy-MM-dd HH:mm:ss}] %c %L: %m%n</pattern>
            </PatternLayout>
            <SizeBasedTriggeringPolicy size="1KB" />
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
        <RollingFile name="RollingFile_system" fileName="mylogs/system/log.out" filePattern="mylogs/system/log.out.%i">
            <PatternLayout>
                <pattern>%-8p [%d{yyyy-MM-dd HH:mm:ss}] %c %L: %m%n</pattern>
            </PatternLayout>
            <SizeBasedTriggeringPolicy size="1KB" />
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <!-- 将包"cn.gridx.log4j2.examples.additivity"下的程序产生的所有日志写入到RollingFile_additivity中 -->
        <Logger name="cn.gridx.log4j2.examples.additivity" level="warn" additivity="false">
            <AppenderRef ref="RollingFile_additivity"/>
        </Logger>
        <!-- 将其他的程序都写入到Console和RollingFile_system -->
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile_system"/>
        </Root>
    </Loggers>
</Configuration>


text:
package catcher

import (
	"fmt"
	"sync"
)

var (
	mu        sync.RWMutex
	notifiers []NotifierFunc
)

// RegisterNotifiers adds all listed notifiers to a global list, each of them
// would be invoked upon an error occurs.
func RegisterNotifiers(fn ...NotifierFunc) {
	mu.Lock()
	notifiers = append(notifiers, fn...)
	mu.Unlock()
}

// Catch must be used together with defer to catch panics from suspicious functions.
// All listed receivers and all the global notifiers will be invoked with the
// error itself, function name and a stack trace.
func Catch(recv ...Receiver) {
	if panicData := recover(); panicData != nil {
		caller := getCaller(5) + " <= " + getCaller(6)
		if err, ok := panicData.(error); ok {
			if len(recv) > 0 {
				stack := getStack()
				for _, r := range recv {
					r.RecvError(err, nil, caller, stack)
				}
			}
			return
		}
		err := fmt.Errorf("%+v", panicData)

		if len(recv) > 0 {
			// invoke receivers
			stack := getStack()
			for _, r := range recv {
				r.RecvPanic(err, nil, caller, stack)
			}
		}
		mu.RLock()
		defer mu.RUnlock()
		if len(notifiers) > 0 {
			wg := new(sync.WaitGroup)
			// notify all registered notifiers
			for _, fn := range notifiers {
				wg.Add(1)
				go func(fn NotifierFunc) {
					fn(err)
					wg.Done()
				}(fn)
			}
			wg.Wait()
		}
	}
}

// CatchWithContext must be used together with defer to catch panics from suspicious functions.
// All listed receivers and all the global notifiers will be invoked with the error itself,
// function name and a stack trace, along with the provided context and meta.
func CatchWithContext(context, meta interface{}, recv ...Receiver) {
	if panicData := recover(); panicData != nil {
		caller := getCaller(5) + " <= " + getCaller(6)
		if err, ok := panicData.(error); ok {
			if len(recv) > 0 {
				stack := getStack()
				for _, r := range recv {
					r.RecvError(err, context, caller, stack)
				}
			}
			return
		}
		err := fmt.Errorf("%+v", panicData)

		if len(recv) > 0 {
			stack := getStack()
			// invoke receivers
			for _, r := range recv {
				r.RecvPanic(err, context, caller, stack)
			}
		}
		mu.RLock()
		defer mu.RUnlock()
		if len(notifiers) > 0 {
			wg := new(sync.WaitGroup)
			// notify all registered notifiers
			for _, fn := range notifiers {
				wg.Add(1)
				go func(fn NotifierFunc) {
					fn(err, context, meta)
					wg.Done()
				}(fn)
			}
			wg.Wait()
		}
	}
}

// NotifierFunc is a func that may be used as a global notifier (via RegisterNotifiers()).
type NotifierFunc func(err error, rawData ...interface{}) error

// Receiver handles panics and errors thrown with a panic.
type Receiver interface {
	RecvError(err error, context interface{}, caller string, stack []byte)
	RecvPanic(err error, context interface{}, caller string, stack []byte)
}

// Error has additional context and stack that can be accessed outside receivers;
// by storing it to a variable using the RecvError receiver.
type Error struct {
	Err     error
	Context interface{}
	Caller  string
	Stack   []byte
}

func (e Error) Error() string {
	return e.Err.Error()
}


text:
CSS Sandbox
===========

A simple CSS sandbox for educational purposes.

MIT License


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

namespace BuildCs.AssemblyInfo
{
    public static class Extensions
    {
        public static AssemblyInfoHelper AssemblyInfoHelper(this IBuildSession session)
        {
            return session.GetService<AssemblyInfoHelper>();
        }

        public static void GenerateCSharpAssemblyInfo(this IBuildSession session, BuildItem outputPath, Action<GenerateArgs> config)
        {
            AssemblyInfoHelper(session).GenerateCSharp(outputPath, config);
        }
    }
}


text:
<form name="form" novalidate class="login-form">

{{'Sign in'|i18n}}

            {{authReason}}

            {{authError}}

{{'Please enter your login details'|i18n}}

        {{'Username'|i18n}}
        <input name="username" type="text" ng-model="user.name" required autofocus>
        {{'Password'|i18n}}
        <input name="pass" type="password" ng-model="user.password" required>

    	<button class="btn btn-primary login" id="googlePlusLoginButton" ng-show="authConfig.google">Google+</button>
        <button class="btn btn-primary login" ng-click="login()" ng-disabled='form.$invalid'" ng-show="authConfig.databaseAccount">{{'Sign in'|i18n}}</button>
        <button class="btn clear" ng-click="clearForm()" ng-show="authConfig.databaseAccount">{{'Clear'|i18n}}</button>

</form>


text:
/**
 * DO NOT MODIFY THIS CODE
 *
 * Place all of your changes in Transaction.java
 *
 * It has been machine generated from fixtures and your changes will be
 * lost if anything new needs to be added to the API.
 **/
// Last Generated: 2011-09-26T15:53:49-04:00
package com.shopify.api.resources;

import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * This code has been machine generated by processing the single entry
 * fixtures found from the Shopify API Documentation
 */

public class MGTransaction extends ShopifyResource {

	@JsonProperty("amount")
	public String getAmount() {
		return (String)getAttribute("amount");
	}
	@JsonProperty("amount")
	public void setAmount(String _amount) {
		setAttribute("amount", _amount);
	}

	@JsonProperty("authorization")
	public String getAuthorization() {
		return (String)getAttribute("authorization");
	}
	@JsonProperty("authorization")
	public void setAuthorization(String _authorization) {
		setAttribute("authorization", _authorization);
	}

	@JsonProperty("kind")
	public String getKind() {
		return (String)getAttribute("kind");
	}
	@JsonProperty("kind")
	public void setKind(String _kind) {
		setAttribute("kind", _kind);
	}

	@JsonProperty("order_id")
	public int getOrderId() {
		Integer value = (Integer)getAttribute("order_id");
		return value != null ? value : 0;
	}
	@JsonProperty("order_id")
	public void setOrderId(int _order_id) {
		setAttribute("order_id", _order_id);
	}

	@JsonProperty("receipt")
	public Receipt getReceipt() {
		return (Receipt)getAttribute("receipt");
	}
	@JsonProperty("receipt")
	public void setReceipt(Receipt _receipt) {
		setAttribute("receipt", _receipt);
	}

	@JsonProperty("status")
	public String getStatus() {
		return (String)getAttribute("status");
	}
	@JsonProperty("status")
	public void setStatus(String _status) {
		setAttribute("status", _status);
	}

}


text:
% SELECT Select file/format for a CustomFile object
%
% Syntax:
%    >> object=select(object,[filename],[format]);
%
% see also FileAccess, read
%

%
function object=select(object,filename,format)

if nargin<2
    filename='';
end

if nargin<3
    format='';
end

object=select@SMASH.FileAccess.File(object,filename);

if isempty(format)
    choice={'Ocean Optics measurement','Optronics Laboratory measurement','Optronics Laboratory screen dump'};
    short={'oceanoptics','optronicslab','optronicslabdump'};
    conversion=get(0,'ScreenPixelsPerInch');
    height=10/72*conversion; % assume 10 point font
    width=height/2;
    rows=numel(choice);
    cols=0;
    for n=1:rows
        cols=max(cols,numel(choice{n}));
    end
    [choice,ok]=listdlg('ListString',choice,...
        'PromptString','Select format:',...
        'Name','File format',...
        'SelectionMode','single',...
        'ListSize',[width*cols (height+2)*rows]);
    assert(ok==1,'ERROR: no format selected');
    format=short{choice};

end
object.Format=format;

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in de Candolle & Lamarck, Fl. franç. (Paris), Edn 3 6: 72 (1815)

#### Original name
Uredo labiatarum var. cycutae-majoris DC.

### Remarks
null


text:
namespace _01.ReverseNumbers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class ReverseNumbers
    {
        static void Main()
        {
            var inputNumbers = Console.ReadLine()
                .Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToList();
            var numbersStack = new Stack<int>(inputNumbers);

            Console.WriteLine(String.Join(" ", numbersStack));
        }
    }
}


text:
package com.whinc.downloader;

import android.content.Context;

/**
 * Created by wuhui on 9/6/15.
 */
public class DownloaderFactory {

    /** create a new {@link Downloader} instance */
    public static Downloader create(Context context) {
        return new DownloaderImpl(context);
    }
}


text:
/**
 * Missing ECMAScript Array functions
 */
(function(Array) {
    'use strict';

    if (!Array.prototype.indexOf) {
        /**
         * Searches the array for the specified item and returns its position
         * @param search
         * @return {Number}
         */
        Array.prototype.indexOf = function(search) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] === search) {
                    return i;
                }
            }
            return -1;
        };
    }
})(window.Array);


text:
This app demonstrates two ways of selecting points.

The first way is to use `nearPoints()` with the click input object.

The second way is to use `brushedPoints()` with the brush input object.


text:
using System.Windows.Controls;

namespace OQF.CommonUiElements.ProgressView
{
	/// <summary>
	/// Interaction logic for ProgressView.xaml
	/// </summary>
	public partial class ProgressView : UserControl
	{
		public ProgressView ()
		{
			InitializeComponent();
		}
	}
}


text:
package eu.leads.processor.core;

import eu.leads.processor.conf.LQPConfiguration;
import org.bson.BSONDecoder;
import org.bson.BSONEncoder;
import org.bson.BasicBSONDecoder;
import org.bson.BasicBSONEncoder;

import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * Created by vagvaz on 9/24/14.
 */
public class TupleUtils {
  static ConcurrentLinkedDeque<BSONDecoder> decoders;
  static ConcurrentLinkedDeque<BSONEncoder> encoders;
  static Object encCV = new Object();
  static Object decCV = new Object();

  public static void initialize() {
    decoders = new ConcurrentLinkedDeque<>();
    encoders = new ConcurrentLinkedDeque<>();
    int size = LQPConfiguration.getInstance().getConfiguration().getInt("processor.encoders.size", 200);
    for (int i = 0; i < size; i++) {
      decoders.add(new BasicBSONDecoder());
      encoders.add(new BasicBSONEncoder());
    }
  }

  public static BSONDecoder getDecoder() {
//    while (decoders.isEmpty()) {
//      synchronized (decCV) {
//        try {
//          decCV.wait();
//        } catch (InterruptedException e) {
//          e.printStackTrace();
//        }
//      }
//    }
    return decoders.poll();
  }

  public static BSONEncoder getEncoder() {
//    while (encoders.isEmpty()) {
//      synchronized (encCV) {
//        try {
//          encCV.wait();
//        } catch (InterruptedException e) {
//          e.printStackTrace();
//        }
//      }
//    }
    return encoders.poll();
  }

  public static void addDecoder(BSONDecoder decoder) {
    decoders.add(decoder);
//    synchronized (decCV) {
//      decCV.notify();
//    }
  }

  public static void addEncoder(BSONEncoder encoder) {
    encoders.add(encoder);
//    synchronized (encCV) {
//      encCV.notify();
//    }
  }

  public static int compareValues(Object o1, Object o2, String type) {
    int result = 0;
    if (type.startsWith("TEXT")) {
      String v1 = (String) o1;
      String v2 = (String) o2;
      result = v1.compareTo(v2);
    } else if (type.startsWith("BOOLEAN")) {
      Boolean v1 = (Boolean) o1;
      Boolean v2 = (Boolean) o2;
      result = v1.compareTo(v2);
    } else if (type.startsWith("INT")) {
      Number v1 = (Number) o1;
      Number v2 = (Number) o2;
      Long l1 = v1.longValue();
      Long l2 = v2.longValue();
      result = l1.compareTo(l2);
    } else if (type.startsWith("FLOAT") || type.startsWith("DOUBLE")) {
      Number v1 = (Number) o1;
      Number v2 = (Number) o2;
      Double d1 = v1.doubleValue();
      Double d2 = v2.doubleValue();
      result = d1.compareTo(d2);
    }

    return result;
  }
}


text:
{#-
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
-#}

  <input type="hidden" name="card-{{index}}.id" value="{{id}}"/>

{{name}}

      {% if settings_href %}

      {% endif %}

      {% if desc %}

{{ desc }}

      {% endif %}

        {% for role in roles %}
          {% if role.name %}

includes the {{ widget.role_name(role._id) }} group

          {% endif %}
        {% endfor %}

    {% for item in items | sort(attribute=widget.sort_key) %}

          {{ widget.item_display(item) }}
          <input type="hidden" name="card-{{index}}.value"
                 {{ widget.j2_attrs(dict(value=widget.item_id(item))) }} />

    {% endfor %}

      {{ widget.new_item.display(name='card-%s.new' % index) }}

        Add

            Block User

      Block List

        {% if block_list and block_list.get(name) %}
          {% for u, reason in block_list[name] %}

              <input type="checkbox" name="user_id" value="{{ u._id }}">{{ u.username }} {{ '(' + reason + ')' if reason else '' }}

          {% endfor %}
        {% endif %}


text:
<?xml version='1.0'?>
<!DOCTYPE x SYSTEM "tests.dtd">
<x xmlns="http://www.schemaTest.org/xinclude-test"
   xmlns:xi="http://www.w3.org/2001/XInclude"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.schemaTest.org/xinclude-test tests.xsd">
   <elem bar="jpg"/>
   <!-- test including a document with a conflicting notation -->
   <!-- EXPECT FAILURE -->
   <xi:include parse="xml"
               href="../included/not2.xml"/>
</x>


text:
namespace media {

ClockImpl::ClockImpl(TimeProvider* time_provider)
    : time_provider_(time_provider),
      playing_(false),
      playback_rate_(1.0f) {
}

ClockImpl::~ClockImpl() {
}

base::TimeDelta ClockImpl::Play() {
  DCHECK(!playing_);
  reference_ = time_provider_();
  playing_ = true;
  return media_time_;
}

base::TimeDelta ClockImpl::Pause() {
  DCHECK(playing_);
  // Save our new accumulated amount of media time.
  media_time_ = Elapsed();
  playing_ = false;
  return media_time_;
}

void ClockImpl::SetTime(const base::TimeDelta& time) {
  if (time == StreamSample::kInvalidTimestamp) {
    NOTREACHED();
    return;
  }
  if (playing_) {
    reference_ = time_provider_();
  }
  media_time_ = time;
}

void ClockImpl::SetPlaybackRate(float playback_rate) {
  if (playing_) {
    base::Time time = time_provider_();
    media_time_ = ElapsedViaProvidedTime(time);
    reference_ = time;
  }
  playback_rate_ = playback_rate;
}

base::TimeDelta ClockImpl::Elapsed() const {
  if (!playing_) {
    return media_time_;
  }
  return ElapsedViaProvidedTime(time_provider_());
}

base::TimeDelta ClockImpl::ElapsedViaProvidedTime(
    const base::Time& time) const {
  // TODO(scherkus): floating point badness scaling time by playback rate.
  int64 now_us = (time - reference_).InMicroseconds();
  now_us = static_cast<int64>(now_us * playback_rate_);
  return media_time_ + base::TimeDelta::FromMicroseconds(now_us);
}

}  // namespace media


text:
title: 'Intermediate Power BI: Data Modeling'
description: "This course is the 2nd in DataSF's series on PowerBI. \_This course will provide a strong foundation in Data Structure and Data Modeling through the tool of PowerBI. \_Analyst tasked with getting multiple data sources to talk to each other in PowerBI will find this class of use."
prerequisites: >-
  Participants must have taken Data Academy's Intro to Power BI, and should be
  confident using the program.
length: Two 4-hour sessions, total 8
subjects:
  - Data Management
  - Visualization
  - PowerBI
series:
  - PowerBI
team_members:
  - alice-kassinger
course_short_name: 'Intermediate Power BI: Data Modeling'
course_materials_link: https://drive.google.com/open?id=1T_bQ75Uj96aVq27C00CrWLth5S2XzUXq
order: '1'
category: academy
categories:
  - academy
---
## About this course

This course is the 2nd in DataSF's series on PowerBI.  This course will provide a strong foundation in Data Structure and Data Modeling through the tool of PowerBI.  Analyst tasked with getting multiple data sources to "talk" to each other in PowerBI will find this class of use.

While most dashboarding tools, force the user to 'flatten' multiple data sources into a single table, PowerBI allows for more robust Data Modeling.  Instead of making a single table, you establish relationships between many tables.  This Data Modeling capability allows for far greater analytical flexibility; allowing you to answer more questions and pose better questions.

However, it is often the case that the data you are using lacks the proper structure for data modeling.  You encounter issues like: you have difficulty getting your charts to work, simple calculations seem inexplicably complex, or you are getting weird results.  This course will also address how to structure your data for modeling.

This course will give analyst a new set of data eyes allowing them to identify and solve common data structure and data modeling issues.

## What you'll learn in this course

* Data Structure
  * What is ideal data structure for analytics
  * How to recognize a poorly structured dataset
  * How to reshape the data in PowerBI
* Data Modeling
  * Foundational concepts in data modeling for analytics
  * How to model properly structured data
  * Identify and fix common data modeling challenges
  * Workflow best practice

## Course Outline

* Data Structure - 1.5 hours
* Mid-Point Exercise - .5 hours
* Data Modeling - 4 hours
* Workflow Best Practices - .5 hours

## Pre-requisites

This course is best suited for users responsible for creating PowerBI data models that involve multiple datasets.

Completion of Data Academy's Intro to PowerBI Course is required.  This course assume a good working knowledge of how PowerBI works.  Heavy use is made of the query editor and familiarity is assumed.  Exceptions at discretion of instructor (mayor.cdo.intern@sfgov.org)

Attendees should have made use of PowerBI since taking the Intro to PowerBI Course.  This course is not designed as a refresher course, but as the next stage in training for advanced PowerBI analyst.  Attendees out of practice should refresh their memories via an online course or work through the [final exercise again from the Intro Class](https://drive.google.com/drive/folders/1ot7J4lkhaoBR24dBhXbJbqs7wO5gJQpR){: target="_blank"}.

Not everyone who takes the Intro to PowerBI course needs (or should) take this course; it is fast paced and geared for users of PowerBI tasked with complicated Data Modeling scenarios.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
src.java.com.infusion.util.event.groovy.builder
</TITLE>

<META NAME="keywords" CONTENT="src/java/com/infusion/util/event/groovy/builder package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

src.java.com.infusion.util.event.groovy.builder

Classes

EventBuilder
EventConsumerListBuilder
EventTypeListBuilder


text:
define([], function() {

  var Cache = function() {

    var store = {};

    this.cacheOrStore = function(key, fn) {
      var cachedResult = store[key];
      if (cachedResult !== undefined) {
        return cachedResult;
      }
      var result = fn();
      store[key] = result;
      return result;
    };
  };

  return Cache;

});


text:
package com.speakingfish.pipe;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamGobbler implements Runnable {
    final InputStream  _input ;
    final OutputStream _output;

    /*
     * StreamGobbler(InputStream is, String type) { this(is, type, null); }
     */
    public StreamGobbler(InputStream input, OutputStream output) {
        _input  = input ;
        _output = output;
    }

    public void run() {
        try {
            final byte[] buffer = new byte[1024*1024];
            while (true) {
                final int count = _input.read(buffer);
                if (count <= 0)
                    break;
                _output.write(buffer, 0, count);
                _output.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}