text:
#import "CRLCrashReleasedObject.h"
#import <objc/message.h>

@implementation CRLCrashReleasedObject

- (NSString *)category { return @"Objective-C"; }
- (NSString *)title { return @"Message a released object"; }
- (NSString *)desc { return @"Send a message to an object whose memory has already been freed."; }

- (void)crash
{
#if __i386__ && !TARGET_IPHONE_SIMULATOR
	NSObject *object = [[NSObject alloc] init];
#else
	NSObject * __unsafe_unretained object = (__bridge NSObject *)CFBridgingRetain([[NSObject alloc] init]);
#endif

#if __i386__ && !TARGET_IPHONE_SIMULATOR
	[object release];
#else
	CFRelease((__bridge CFTypeRef)object);
#endif
	^ __attribute__((noreturn)) {
		for (;;) {
			[object self];
			[object description];
			[object debugDescription];
		}
	}();
}

@end


text:
(function(){
	/**
	 * Creates Modals for general use, inspired in
	 * http://tympanus.net/Development/ModalWindowEffects/
	 *
	 * @class Modal
	 * @requires Initclass
	 * @requires classie
	 * @param  {JSON} j Contains all the neccesary parameters
	 * @return {Modal}   A modal DOM is created and shown
	 */
	var Modal = function(j){
		/**
		 * Default values if not specified in Modal Class
		 * @type {JSON}
		 * @param {String} title Title of the Modal
		 * @param {String} message Message or description
		 * @param {JSON} actions Contains the actions to perform, each action object must be a function, And will be converted to a button. If actions is equal to {} no actions will be created
		 * @param {Function} createHelper After the DOM is created, this function will come in handy if extra DOM is required.
		 * @param {String} container The specified DOM node that will contain the Modal
		 * @param {Integer} effect Specifies the decired effect to perform
		 */
		var defaults = {
			title: 'Modal Title',
			message: 'Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an. Qui ut wisi vocibus suscipiantur, quo dicit ridens inciderint id. Quo mundi lobortis reformidans eu, legimus senserit definiebas an eos. Eu sit tincidunt incorrupte definitionem, vis mutat affert percipit cu, eirmod consectetuer signiferumque eu per. In usu latine equidem dolores.',
			subtitle: 'Sub title',
			actions: {
				accept: {
					text: 'Accept',
					icon: 'glyphicon glyphicon-ok',
					clas: 'btn btn-success',
					action: {}
				},
				cancel: {
					text: 'Cancel',
					icon: 'glyphicon glyphicon-cancel',
					clas: 'btn btn-danger',
					action: {}
				}
			},
			createHelper: function(){},
			container:'body',
			effect: 1
		};

		var js = {data:j, defaults:defaults};
		Initclass.call(this, js);

		this.create();

		var This = this;
	};

	/**
	 * Creates the DOM
	 * @private
	 */
	Modal.prototype.create = function(){

		var container = document.querySelector(this.container);

		var main = document.createElement('div');
		main.className = 'md-modal md-effect-'+this.effect;

		var content = document.createElement('div');
		content.className = 'md-content';

		var header = document.createElement('div');
		header.className = 'md-header modal-header';

		var body = document.createElement('div');
		body.className = 'md-body modal-body';

		var footer = document.createElement('div');
		footer.className = 'md-footer modal-footer';

		var title = document.createElement('h2');
		title.className = 'md-title';
		title.appendChild(document.createTextNode(this.title));

		if(this.subtitle != ''){
			//For subtitles

			var br = document.createElement('br');
			title.appendChild(br);

			var small = document.createElement('small');
			small.appendChild(document.createTextNode(this.subtitle));
			title.appendChild(small);
			this.subtitleDOM = small;
		}

		var message = document.createElement('p');
		message.appendChild(document.createTextNode(this.message));

		header.appendChild(title);
		content.appendChild(header);

		body.appendChild(message);
		content.appendChild(body);

		content.appendChild(footer)

		main.appendChild(content);

		this.modal = main;

		var overlay = document.createElement('div');
		overlay.className = 'md-overlay';

		overlay._t = this;
		overlay.addEventListener('click', function(){
			this._t.vaporize();
		});

		//Before appending, removes if existing
		this.remove();

		this.header = header;
		this.footer = footer;
		this.body = body;

		container.appendChild(main);
		container.appendChild(overlay);

		this.createHelper(this);
		this.actions_creator();
	};

	Modal.prototype.actions_creator = function() {
		for(var k in this.actions){
			if(this.actions.hasOwnProperty(k) &&typeof this.actions[k].action === 'function'){
				var btn = document.createElement('button');
				btn.className = this.actions[k].clas;

				var span = document.createElement('span');
				var text = document.createTextNode(this.actions[k].text);
				span.appendChild(text);
				btn.appendChild(span);

				var icon = document.createElement('i');
				icon.className = this.actions[k].icon;
				btn.appendChild(icon);

				this.footer.appendChild(btn);
				btn._t = this;
				btn._action = this.actions[k].action;
				btn.addEventListener('click', function(){
					this._action(this._t, this);
				}, false);

			}
		}
	};

	/**
	 * Deletes the DOM
	 */
	Modal.prototype.remove = function(){
		var ex = document.querySelector('.md-modal');
		if(ex !== null){
			ex.parentNode.removeChild(ex);
		}

		var ex1 = document.querySelector('.md-overlay');
		if(ex1 !== null){
			ex1.parentNode.removeChild(ex1);
		}
	};

	/**
	 * Shows the DOM
	 */
	Modal.prototype.show = function(){
		classie.toggle(this.modal, 'md-show');
	};

	/**
	 * Hides the DOM
	 */
	Modal.prototype.hide = function(){
		classie.toggle(this.modal, 'md-show');
	};

	/**
	 * Hides and remove the DOM
	 */
	Modal.prototype.vaporize = function() {
		var t = this;
		this.hide(function(){
			//300 plus 1 ms of the css until deletion
			setTimeout(function(){
				t.remove();
			}, 301);
		});
	};

	window.Modal = function(j){
		return new Modal(j);
	};
})();

redpajama_set_name: RedPajamaGithub


text:
<component name="libraryTable">
  <library name="gradle-wrapper54">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/Lesson03-Green-Recycler-View/T03.03-Exercise-RecyclerViewAdapter/gradle/wrapper/gradle-wrapper.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package org.jbehave.core.model;

import static java.util.Arrays.asList;
import static org.codehaus.plexus.util.StringUtils.isBlank;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.params.provider.Arguments.arguments;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.jbehave.core.annotations.AsParameters;
import org.jbehave.core.annotations.Parameter;
import org.jbehave.core.i18n.LocalizedKeywords;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.model.ExamplesTable.ColumnNotFound;
import org.jbehave.core.model.ExamplesTable.RowNotFound;
import org.jbehave.core.model.ExamplesTable.TableProperties;
import org.jbehave.core.model.TableTransformers.TableTransformer;
import org.jbehave.core.steps.ConvertedParameters.ValueNotFound;
import org.jbehave.core.steps.ParameterControls;
import org.jbehave.core.steps.ParameterConverters;
import org.jbehave.core.steps.ParameterConverters.MethodReturningConverter;
import org.jbehave.core.steps.ParameterConverters.ParameterConverter;
import org.jbehave.core.steps.Parameters;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public class ExamplesTableBehaviour {

    private static final String VALUE_SEPARATOR_KEY = "valueSeparator";
    private static final String HEADER_SEPARATOR_KEY = "headerSeparator";
    private static final String IGNORABLE_SEPARATOR_KEY = "ignorableSeparator";

    private String tableAsString = "|one|two|\n" + "|11|12|\n" + "|21|22|\n";

    private String tableWithSpacesAsString = "|one |two | |\n" + "|11 |12 | |\n" + "| 21| 22| |\n";

    private String landscapeTableAsString = "|one|11|21|\n" + "|two|12|22|\n";

    private String wikiTableAsString = "||one||two||\n" + "|11|12|\n" + "|21|22|\n";

    private String tableWithCommentsAsString = "|---------|\n" + "|one|two|\n" + "|-- A comment --|\n" + "|11|12|\n"
            + "|-- Another comment --|\n" + "|21|22|\n";

    @Test
    void shouldParseTableWithDefaultSeparators() {
        ExamplesTable table = new ExamplesTable(tableAsString);
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo(tableAsString));
    }

    @Test
    void shouldCreateEmptyTable() {
        ExamplesTable table = ExamplesTable.empty();
        assertThat(table.asString(), equalTo(""));
        assertFalse(table == ExamplesTable.empty());
    }

    @Test
    void shouldGetColumn() {
        ExamplesTable table = new ExamplesTable(tableAsString);
        assertThat(table.getColumn("one"), equalTo(asList("11", "21")));
        assertThat(table.getColumn("two"), equalTo(asList("12", "22")));
    }

    @Test
    void shouldFailIfColumnDoesNotExist() {
        ExamplesTable table = new ExamplesTable(tableAsString);
        ColumnNotFound exception = assertThrows(ColumnNotFound.class, () -> table.getColumn("three"));
        assertThat(exception.getMessage(), equalTo("The 'three' column does not exist"));
    }

    @Test
    void shouldParseTableWithDifferentSeparators() {
        String headerSeparator = "||";
        String valueSeparator = "|";
        String ignorableSeparator = "!--";
        String tableWithCustomSeparator = wikiTableAsString;
        ExamplesTable table = new ExamplesTable(tableWithCustomSeparator, headerSeparator, valueSeparator,
                ignorableSeparator);
        assertThat(table.getHeaderSeparator(), equalTo(headerSeparator));
        assertThat(table.getValueSeparator(), equalTo(valueSeparator));

        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo(tableWithCustomSeparator));
    }

    @Test
    void shouldParseTableWithDifferentCustomSeparators() {
        String headerSeparator = "!!";
        String valueSeparator = "!";
        String ignorableSeparator = "!--";
        String tableWithCustomSeparator = wikiTableAsString.replace("|", "!");
        ExamplesTable table = new ExamplesTable(tableWithCustomSeparator, headerSeparator, valueSeparator,
                ignorableSeparator);
        assertThat(table.getHeaderSeparator(), equalTo(headerSeparator));
        assertThat(table.getValueSeparator(), equalTo(valueSeparator));
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo("!!one!!two!!\n!11!12!\n!21!22!\n"));
    }

    @Test
    void shouldTrimTableBeforeParsing() {
        String untrimmedTableAsString = "\n    \n" + tableAsString + "\n    \n";
        ExamplesTable table = new ExamplesTable(untrimmedTableAsString);
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo("|one|two|\n|11|12|\n|21|22|\n"));
    }

    @Test
    void shouldParseTableWithCommentsInValues() {
        String tableWithEmptyValues = "{commentSeparator=#}\n|one #comment|two|\n |11 #comment|12 #comment|\n |21|22|\n";
        ExamplesTable table = new ExamplesTable(tableWithEmptyValues);
        assertThat(table.getRowCount(), equalTo(2));
        for (Parameters row : table.getRowsAsParameters()) {
            Map<String, String> values = row.values();
            assertThat(values.size(), equalTo(2));
            for (String column : values.keySet()) {
                assertThat(values.get(column), not(containsString("#comment")));
            }
        }
        assertThat(table.asString(), equalTo("{commentSeparator=#}\n|one|two|\n|11|12|\n|21|22|\n"));
    }

    @Test
    void shouldParseTableWithUntrimmedCommentsInValues() {
        String tableWithEmptyValues = "{commentSeparator=#, trim=false}\n|one #comment|two|\n |11 #comment|12 #comment|\n |21|22|\n";
        ExamplesTable table = new ExamplesTable(tableWithEmptyValues);
        assertThat(table.getRowCount(), equalTo(2));
        for (Parameters row : table.getRowsAsParameters()) {
            Map<String, String> values = row.values();
            assertThat(values.size(), equalTo(2));
            for (String column : values.keySet()) {
                assertThat(values.get(column), not(containsString("#comment")));
            }
        }
        assertThat(table.asString(), equalTo("{commentSeparator=#, trim=false}\n|one |two|\n|11 |12 |\n|21|22|\n"));
    }

    @Test
    void shouldParseEmptyTable() {
        String tableAsString = "";
        ExamplesTable table = new ExamplesTable(tableAsString);
        assertThat(table.getHeaders().size(), equalTo(0));
        assertThat(table.getRows().size(), equalTo(0));
        assertThat(table.getRowsAsParameters().size(), equalTo(0));
        assertThat(table.asString(), equalTo(tableAsString));
    }

    @Test
    void shouldParseTableWithBlankValues() {
        String tableWithEmptyValues = "|one|two|\n |||\n | ||\n || |\n";
        ExamplesTable table = new ExamplesTable(tableWithEmptyValues);
        assertThat(table.getRowCount(), equalTo(3));
        for (Parameters row : table.getRowsAsParameters()) {
            Map<String, String> values = row.values();
            assertThat(values.size(), equalTo(2));
            for (String column : values.keySet()) {
                assertThat(isBlank(values.get(column)), is(true));
            }
        }
        assertThat(table.asString(), equalTo("|one|two|\n|||\n|||\n|||\n"));
    }

    @Test
    void shouldParseTableWithoutLeftBoundarySeparator() {
        String tableAsString = "one|two|\n 11|12|\n 21|22|\n";
        ExamplesTable table = new ExamplesTable(tableAsString);
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo("|one|two|\n|11|12|\n|21|22|\n"));
    }

    @Test
    void shouldParseTableWithoutRightBoundarySeparator() {
        String tableAsString = "|one|two\n |11|12\n |21|22\n";
        ExamplesTable table = new ExamplesTable(tableAsString);
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo("|one|two|\n|11|12|\n|21|22|\n"));
    }

    @Test
    void shouldParseTableWithoutAnyBoundarySeparators() {
        String tableAsString = "one|two\n 11|12\n 21|22\n";
        ExamplesTable table = new ExamplesTable(tableAsString);
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo("|one|two|\n|11|12|\n|21|22|\n"));
    }

    @Test
    void shouldParseTablePreservingWhitespace() {
        String tableWithProperties = "{trim=false}\n" + tableWithSpacesAsString;
        ExamplesTable table = new ExamplesTable(tableWithProperties);
        Properties properties = table.getProperties();
        assertThat(properties.getProperty("trim"), equalTo("false"));
        ensureWhitespaceIsPreserved(table);
        assertThat(table.asString(), equalTo("{trim=false}\n|one |two | |\n|11 |12 | |\n| 21| 22| |\n"));
    }

    @Test
    void shouldParseTableWithSeparatorsSpecifiedViaProperties() {
        String tableWithProperties = "{ignorableSeparator=!--,headerSeparator=!,valueSeparator=!}\n"
                + tableWithCommentsAsString.replace("|", "!");
        ExamplesTable table = new ExamplesTable(tableWithProperties);
        Properties properties = table.getProperties();
        assertThat(properties.getProperty(IGNORABLE_SEPARATOR_KEY), equalTo("!--"));
        assertThat(properties.getProperty(HEADER_SEPARATOR_KEY), equalTo("!"));
        assertThat(properties.getProperty(VALUE_SEPARATOR_KEY), equalTo("!"));
        ensureColumnOrderIsPreserved(table);
    }

    @Test
    void shouldParseTableAsLandscape() {
        String tableWithProperties = "{transformer=FROM_LANDSCAPE}\n" + landscapeTableAsString;
        ExamplesTableFactory factory = createFactory();
        ExamplesTable table = factory.createExamplesTable(tableWithProperties);
        Properties properties = table.getProperties();
        assertThat(properties.getProperty("transformer"), equalTo("FROM_LANDSCAPE"));
        ensureColumnOrderIsPreserved(table);
    }

    @Test
    void shouldParseTableWithCustomTransformerSpecifiedViaProperties() {
        String tableWithProperties = "{transformer=myTransformer, trim=false}\n" + tableWithCommentsAsString;
        TableTransformers tableTransformers = new TableTransformers();
        tableTransformers.useTransformer("myTransformer", new TableTransformer() {

            @Override
            public String transform(String tableAsString, TableParsers tableParsers, TableProperties properties) {
                return tableWithSpacesAsString;
            }

        });
        ExamplesTable table = new ExamplesTableFactory(new LoadFromClasspath(), tableTransformers).createExamplesTable(
                tableWithProperties);
        Properties properties = table.getProperties();
        assertThat(properties.getProperty("transformer"), equalTo("myTransformer"));
        ensureWhitespaceIsPreserved(table);
    }

    @Test
    void shouldParseTableWithCustomNestedTransformers() {
        String tableWithProperties = "{transformer=myTransformer, trim=false, " +
                "table=\\{transformer=NESTED_TRANSFORMER\\, parameter=value\\}}\n" + tableWithCommentsAsString;
        TableTransformers tableTransformers = new TableTransformers();
        tableTransformers.useTransformer("myTransformer", new TableTransformer() {

            @Override
            public String transform(String tableAsString, TableParsers tableParsers, TableProperties properties) {
                return tableWithSpacesAsString;
            }

        });
        ExamplesTable table = new ExamplesTableFactory(new LoadFromClasspath(), tableTransformers).createExamplesTable(
                tableWithProperties);
        Properties properties = table.getProperties();
        assertThat(properties.getProperty("transformer"), equalTo("myTransformer"));
        assertThat(properties.getProperty("table"), equalTo("{transformer=NESTED_TRANSFORMER, parameter=value}"));
        ensureWhitespaceIsPreserved(table);
    }

    @Test
    void shouldParseTableWithSequenceOfTransformers() {
        String tableWithProperties =
                        "{transformer=REPLACING, replacing=33, replacement=22}\n"
                      + "{transformer=MODIFYING_PROPERTIES}\n"
                      + "{transformer=FROM_LANDSCAPE}\n"
                    + landscapeTableAsString.replace("22", "33");
        TableTransformers tableTransformers = new TableTransformers();
        tableTransformers.useTransformer("MODIFYING_PROPERTIES", (tableAsString, tableParsers, properties) -> {
            properties.getProperties().setProperty("headerSeparator", "!");
            properties.getProperties().setProperty("valueSeparator", "!");
            return tableAsString.replace('|', '!');
        });
        ExamplesTableFactory factory = createFactory(tableTransformers);
        ExamplesTable table = factory.createExamplesTable(tableWithProperties);
        Properties properties = table.getProperties();
        assertThat(properties.getProperty("transformer"), equalTo("FROM_LANDSCAPE"));
        assertThat(properties.getProperty("headerSeparator"), equalTo("!"));
        assertThat(properties.getProperty("valueSeparator"), equalTo("!"));
        ensureColumnOrderIsPreserved(table);
    }

    private void ensureColumnOrderIsPreserved(ExamplesTable table) {
        assertThat(table.getHeaders(), equalTo(asList("one", "two")));
        List<Map<String, String>> rows = table.getRows();
        assertThat(rows.size(), equalTo(2));
        ensureRowContentIs(rows, 0, asList("11", "12"));
        ensureRowContentIs(rows, 1, asList("21", "22"));
        ensureCellContentIs(table, 0, "one", "11");
        ensureCellContentIs(table, 0, "two", "12");
        ensureCellContentIs(table, 1, "one", "21");
        ensureCellContentIs(table, 1, "two", "22");
    }

    private void ensureWhitespaceIsPreserved(ExamplesTable table) {
        assertThat(table.getHeaders(), equalTo(asList("one ", "two ", " ")));
        List<Map<String, String>> rows = table.getRows();
        assertThat(rows.size(), equalTo(2));
        ensureRowContentIs(rows, 0, asList("11 ", "12 ", " "));
        ensureRowContentIs(rows, 1, asList(" 21", " 22", " "));
        ensureCellContentIs(table, 0, "one ", "11 ");
        ensureCellContentIs(table, 0, "two ", "12 ");
        ensureCellContentIs(table, 0, " ", " ");
        ensureCellContentIs(table, 1, "one ", " 21");
        ensureCellContentIs(table, 1, "two ", " 22");
        ensureCellContentIs(table, 1, " ", " ");
    }

    private void ensureRowContentIs(List<Map<String, String>> rows, int row, List<String> expected) {
        assertThat(new ArrayList<>(rows.get(row).values()), equalTo(expected));
    }

    private void ensureCellContentIs(ExamplesTable table, int row, String header, String value) {
        assertThat(table.getRow(row).get(header), equalTo(value));
    }

    @Test
    void shouldConvertParameterValuesOfTableRow() throws Exception {
        // Given
        ExamplesTableFactory factory = createFactory(new MethodReturningConverter(methodFor("convertDate"), this));

        // When
        String tableAsString = "|one|two|\n|11|22|\n|1/1/2010|2/2/2010|";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString);

        // Then
        Parameters integers = examplesTable.getRowAsParameters(0);
        assertThat(integers.<Integer>valueAs("one", Integer.class), equalTo(11));
        assertThat(integers.<Integer>valueAs("two", Integer.class), equalTo(22));
        Parameters dates = examplesTable.getRowAsParameters(1);
        assertThat(dates.<Date>valueAs("one", Date.class), equalTo(convertDate("1/1/2010")));
        assertThat(dates.<Date>valueAs("two", Date.class), equalTo(convertDate("2/2/2010")));
    }

    @Test
    void shouldConvertParameterValuesOfTableRowWithDefaults() throws Exception {
        // Given
        ExamplesTableFactory factory = createFactory(new MethodReturningConverter(methodFor("convertDate"), this));

        // When
        String tableDefaultsAsString = "|three|\n|99|";
        ExamplesTable defaultsTable = factory.createExamplesTable(tableDefaultsAsString);

        Parameters defaults = defaultsTable.getRowAsParameters(0);
        String tableAsString = "|one|\n|11|\n|22|";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString).withDefaults(defaults);

        // Then
        Parameters firstRow = examplesTable.getRowAsParameters(0);
        Map<String, String> firstRowValues = firstRow.values();
        assertThat(firstRowValues.containsKey("one"), is(true));
        assertThat(firstRow.<String>valueAs("one", String.class), is("11"));
        assertThat(firstRow.<Integer>valueAs("one", Integer.class), is(11));
        assertThat(firstRowValues.containsKey("three"), is(true));
        assertThat(firstRow.<String>valueAs("three", String.class), is("99"));
        assertThat(firstRow.<Integer>valueAs("three", Integer.class), is(99));
        assertThat(firstRowValues.containsKey("XX"), is(false));
        assertThat(firstRow.valueAs("XX", Integer.class, 13), is(13));

        Parameters secondRow = examplesTable.getRowAsParameters(1);
        Map<String, String> secondRowValues = secondRow.values();
        assertThat(secondRowValues.containsKey("one"), is(true));
        assertThat(secondRow.<String>valueAs("one", String.class), is("22"));
        assertThat(secondRow.<Integer>valueAs("one", Integer.class), is(22));
        assertThat(secondRowValues.containsKey("three"), is(true));
        assertThat(secondRow.<String>valueAs("three", String.class), is("99"));
        assertThat(secondRow.<Integer>valueAs("three", Integer.class), is(99));
        assertThat(secondRowValues.containsKey("XX"), is(false));
        assertThat(secondRow.valueAs("XX", Integer.class, 13), is(13));

    }

    static Stream<Arguments> tablesWithNamedParameters() {
        return Stream.of(
                arguments("|Name|Value|\n|name1|<value>|", "value1", "value1"),
                arguments("|Name|Value|\n|name1|foo-<value>-bar|", "value1", "foo-value1-bar"),
                arguments("|Name|Value|\n|name1|<value>|", "value having the \\ backslash and the $ dollar character",
                        "value having the \\ backslash and the $ dollar character")
        );
    }

    @ParameterizedTest
    @MethodSource("tablesWithNamedParameters")
    void shouldReplaceNamedParameterValuesInRows(String tableAsString, String namedParameter, String expectedValue) {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        Map<String, String> namedParameters = new HashMap<>();
        namedParameters.put("value", namedParameter);
        ExamplesTable table = factory.createExamplesTable(tableAsString).withNamedParameters(namedParameters);

        // Then
        Parameters firstRow = table.getRowsAsParameters(true).get(0);
        Map<String, String> firstRowValues = firstRow.values();
        assertThat(firstRowValues.containsKey("Value"), is(true));
        assertThat(firstRow.valueAs("Value", String.class), is(expectedValue));
    }

    @ParameterizedTest
    @MethodSource("tablesWithNamedParameters")
    void shouldReplaceNamedParameterValuesInColumns(String tableAsString, String namedParameter, String expectedValue) {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        Map<String, String> namedParameters = new HashMap<>();
        namedParameters.put("value", namedParameter);
        ExamplesTable table = factory.createExamplesTable(tableAsString).withNamedParameters(namedParameters);

        // Then
        List<String> column = table.getColumn("Value", true);
        assertThat(column.get(0), is(expectedValue));
    }

    @Test
    void shouldMapParametersToType() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|string|integer|stringList|integerList|parentString|rootParentString|\n"
                + "|11|22|1,1|2,2|value1|value2|";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString);

        // Then
        for (MyParameters parameters : examplesTable.getRowsAs(MyParameters.class)) {
            assertThat(parameters.string, equalTo("11"));
            assertThat(parameters.integer, equalTo(22));
            assertThat(parameters.stringList, equalTo(asList("1", "1")));
            assertThat(parameters.integerList, equalTo(asList(2, 2)));
            assertThat(parameters.getParentString(), equalTo("value1"));
            assertThat(parameters.getRootParentString(), equalTo("value2"));
        }
    }

    @Test
    void shouldMapParametersToTypeWithFieldMappings() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|aString|anInteger|aStringList|anIntegerList|\n|11|22|1,1|2,2|";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString);

        Map<String, String> nameMapping = new HashMap<>();
        nameMapping.put("aString", "string");
        nameMapping.put("anInteger", "integer");
        nameMapping.put("aStringList", "stringList");
        nameMapping.put("anIntegerList", "integerList");

        // Then
        for (MyParameters parameters : examplesTable.getRowsAs(MyParameters.class, nameMapping)) {
            assertThat(parameters.string, equalTo("11"));
            assertThat(parameters.integer, equalTo(22));
            assertThat(parameters.stringList, equalTo(asList("1", "1")));
            assertThat(parameters.integerList, equalTo(asList(2, 2)));
        }
    }

    @Test
    void shouldMapParametersToTypeWithAnnotatedFields() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|aString|anInteger|aStringList|anIntegerList|\n|11|22|1,1|2,2|";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString);

        // Then
        for (MyParametersWithAnnotatedFields parameters : examplesTable.getRowsAs(MyParametersWithAnnotatedFields.class)) {
            assertThat(parameters.string, equalTo("11"));
            assertThat(parameters.integer, equalTo(22));
            assertThat(parameters.stringList, equalTo(asList("1", "1")));
            assertThat(parameters.integerList, equalTo(asList(2, 2)));
        }
    }

    @Test
    void shouldThrowExceptionIfValuesOrRowsAreNotFound() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|one|two|\n|11|22|\n";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString);

        // Then
        Parameters integers = examplesTable.getRowAsParameters(0);
        assertThat(integers.<Integer>valueAs("one", Integer.class), equalTo(11));
        try {
            integers.valueAs("unknown", Integer.class);
            throw new AssertionError("Exception was not thrown");
        } catch (ValueNotFound e) {
            assertThat(e.getMessage(), equalTo("unknown"));
        }
        try {
            examplesTable.getRowAsParameters(1);
            throw new AssertionError("Exception was not thrown");
        } catch (RowNotFound e) {
            assertThat(e.getMessage(), equalTo("1"));
        }

    }

    @Test
    void shouldAllowAdditionAndModificationOfRowValues() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|one|two|\n|11|12|\n|21|22|";
        ExamplesTable examplesTable = factory.createExamplesTable(tableAsString);
        Map<String, String> values = new HashMap<>();
        values.put("one", "111");
        values.put("three", "333");
        examplesTable.withRowValues(0, values);
        Map<String, String> otherValues = new HashMap<>();
        otherValues.put("two", "222");
        examplesTable.withRowValues(1, otherValues);

        // Then
        Parameters firstRow = examplesTable.getRowAsParameters(0);
        assertThat(firstRow.<Integer>valueAs("one", Integer.class), equalTo(111));
        assertThat(firstRow.<Integer>valueAs("two", Integer.class), equalTo(12));
        assertThat(firstRow.<Integer>valueAs("three", Integer.class), equalTo(333));
        Parameters secondRow = examplesTable.getRowAsParameters(1);
        assertThat(secondRow.<Integer>valueAs("one", Integer.class), equalTo(21));
        assertThat(secondRow.<Integer>valueAs("two", Integer.class), equalTo(222));
        assertThat(secondRow.<String>valueAs("three", String.class), equalTo(""));
        assertThat(examplesTable.asString(), equalTo("|one|two|three|\n|111|12|333|\n|21|222||\n"));
    }

    @Test
    void shouldAllowBuildingOfTableFromContent() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|one|two|\n|11|12|\n|21|22|";
        ExamplesTable originalTable = factory.createExamplesTable(tableAsString);
        List<Map<String, String>> content = originalTable.getRows();
        content.get(0).put("three", "13");
        content.get(1).put("three", "23");
        ExamplesTable updatedTable = originalTable.withRows(content);

        // Then
        assertThat(updatedTable.asString(), equalTo("|one|two|three|\n|11|12|13|\n|21|22|23|\n"));
    }

    @Test
    void shouldAllowBuildingOfTableFromEmptyContent() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|one|two|\n|11|12|\n|21|22|";
        ExamplesTable originalTable = factory.createExamplesTable(tableAsString);
        ExamplesTable updatedTable = originalTable.withRows(Collections.emptyList());

        // Then
        assertThat(updatedTable.asString(), equalTo(""));
    }

    @Test
    void shouldAllowOutputToPrintStream() {
        // Given
        ExamplesTableFactory factory = createFactory();

        // When
        String tableAsString = "|one|two|\n|11|12|\n|21|22|\n";
        ExamplesTable table = factory.createExamplesTable(tableAsString);
        OutputStream out = new ByteArrayOutputStream();
        PrintStream output = new PrintStream(out);
        table.outputTo(output);

        // Then
        assertThat(out.toString(), equalTo(tableAsString));
    }

    @Test
    void shouldIgnoreEmptyLines() {
        // ignore blank line
        String tableWithEmptyLine = "|one|two|\n|a|b|\n\n|c|d|\n";
        ExamplesTable table = new ExamplesTable(tableWithEmptyLine);
        assertThat(table.getRowCount(), equalTo(2));
        assertThat(table.asString(), equalTo("|one|two|\n|a|b|\n|c|d|\n"));
    }

    @Test
    void shouldIgnoreAllCommentLines() {
        // ignore comment lines
        ExamplesTable table = new ExamplesTable(tableWithCommentsAsString);
        ensureColumnOrderIsPreserved(table);
        assertThat(table.asString(), equalTo(tableAsString));
    }

    @Test
    void shouldHandleWrongNumberOfColumns() {
        assertTableAsString("|a|b|\n|a|\n", "|a|b|\n|a||\n");
        assertTableAsString("|a|b|\n|a|b|c|\n", "|a|b|\n|a|b|\n");
    }

    @Test
    void shouldHaveEmptyTableAsImmutable() {
        ExamplesTable table = ExamplesTable.EMPTY;
        assertThat(table.asString(), equalTo(""));
        assertThat(table, instanceOf(ImmutableExamplesTable.class));
    }

    private ExamplesTableFactory createFactory(ParameterConverter... converters) {
        TableTransformers tableTransformers = new TableTransformers();
        return createFactory(tableTransformers, converters);
    }

    private ExamplesTableFactory createFactory(TableTransformers tableTransformers, ParameterConverter... converters) {
        LoadFromClasspath resourceLoader = new LoadFromClasspath();
        ParameterControls parameterControls = new ParameterControls();
        ParameterConverters parameterConverters = new ParameterConverters(resourceLoader, parameterControls,
                tableTransformers, true);
        LocalizedKeywords keywords = new LocalizedKeywords();
        TableParsers tableParsers = new TableParsers(keywords, parameterConverters);
        parameterConverters.addConverters(converters);
        return new ExamplesTableFactory(keywords, resourceLoader, parameterConverters, parameterControls, tableParsers,
                tableTransformers);
    }

    private void assertTableAsString(String tableAsString, String expectedTableAsString) {
        assertThat(new ExamplesTable(tableAsString).asString(), equalTo(expectedTableAsString));
    }

    public Date convertDate(String value) throws ParseException {
        return new SimpleDateFormat("dd/MM/yyyy").parse(value);
    }

    public static Method methodFor(String methodName) throws IntrospectionException {
        BeanInfo beanInfo = Introspector.getBeanInfo(ExamplesTableBehaviour.class);
        for (MethodDescriptor md : beanInfo.getMethodDescriptors()) {
            if (md.getMethod().getName().equals(methodName)) {
                return md.getMethod();
            }
        }
        return null;
    }

    public static abstract class AbstractRootMyParameters {
        private String rootParentString;

        public String getRootParentString() {
            return rootParentString;
        }
    }

    public static abstract class AbstractMyParameters extends AbstractRootMyParameters {
        private String parentString;

        public String getParentString() {
            return parentString;
        }
    }

    @AsParameters
    public static class MyParameters extends AbstractMyParameters {

        private String string;
        private Integer integer;
        private List<String> stringList;
        private List<Integer> integerList;

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
        }
    }

    @AsParameters
    public static class MyParametersWithAnnotatedFields {

        @Parameter(name = "aString")
        private String string;
        @Parameter(name = "anInteger")
        private Integer integer;
        @Parameter(name = "aStringList")
        private List<String> stringList;
        @Parameter(name = "anIntegerList")
        private List<Integer> integerList;

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
        }
    }

}


text:
package rholang.parsing.rholang1.Absyn; // Java Package generated by the BNF Converter.

public class ListName extends java.util.LinkedList<String> {
}


text:
using DarkUI.Forms;
using System.Windows.Forms;

namespace Example
{
    public partial class DialogAbout : DarkDialog
    {
        #region Constructor Region

        public DialogAbout()
        {
            InitializeComponent();

            lblVersion.Text = $"Version: {Application.ProductVersion.ToString()}";
            btnOk.Text = "Close";
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2018 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    style="@style/AlertDialogContent">

    <org.chromium.ui.widget.ChromeImageView
        android:id="@+id/title_icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginEnd="8dp"
        android:importantForAccessibility="no" />

    <androidx.appcompat.widget.DialogTitle
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textAppearance="@style/TextAppearance.AlertDialogTitleStyle" />
</LinearLayout>


text:
package slack

import (
	"encoding/json"
	"github.com/aphistic/gomol"
	"io/ioutil"
)

var Config *SlackConfig

type SlackConfig struct {
	BotUsername string `json:"bot_username"`
	WebhookUrl  string `json:"webhook_url"`
}

func InitSlackConfig() error {
	var err error
	Config, err = newSlackConfig("slack.json")

	return err
}

func newSlackConfig(path string) (*SlackConfig, error) {
	var config *SlackConfig
	configFile, err := ioutil.ReadFile(path)
	if err != nil {
		gomol.Fatal(err.Error())
		return nil, err
	}

	if err := json.Unmarshal(configFile, &config); err != nil {
		gomol.Fatal(err.Error())
		return nil, err
	}

	return config, nil
}


text:
'use strict';

var Promise = require('bluebird');
var chalk = require('chalk');
var inquirer = require('inquirer');
var fsStat = Promise.promisify(require('fs').stat);
var fsUnlink = Promise.promisify(require('fs').unlink);
var fsRmdir = Promise.promisify(require('rimraf'));

module.exports = function modExports(args) {
  var searchTerms;

  if (!args._.join('')) {
    console.log(chalk.red('You need to search for a specific post before you can remove it. Check `hexo help remove` for usage details.'));
    process.exit();
  } else {
    // every whitespace-separated word in the input search is a case-insensitive regular expression
    searchTerms = args._.map(function mapSearchTerms(arg) {
      return new RegExp(arg, 'i');
    });
  }

  // load database
  this.load().then(function loadDb() {
    var locals = this.locals;

    // load posts and pages
    getArticles(locals).then(function loadArticles(articles) {
      return selectArticle(articles);
    }).then(function processSelected(selected) {
      return confirmRemove(selected);
    }).catch(function failProcessSelected(err) {
      console.log(err.stack ? chalk.red(err.stack) : chalk.gray(err));
      process.exit();
    });

    function getArticles(data) {
      return Promise.resolve(data.get('posts').toArray().concat(locals.get('pages').toArray()));
    }

    function filterOnName(articles, terms) {
      return articles.filter(function filterArticles(article) {
        return terms.every(function checkRE(term) {
          return term.test(article.title) || term.test(article.slug);
        });
      });
    }

    function selectArticle(items) {
      var filtered = filterOnName(items, searchTerms);

      if (filtered.length === 0) {
        return Promise.reject(chalk.red('No posts or pages found using your query.'));
      }

      if (filtered.length === 1) {
        return Promise.resolve(filtered[0]);
      }

      var entries = filtered.map(function mapEntries(article) {
        return [article.title, ' (', chalk.green(article.source), ')'].join('');
      });

      return inquirer.prompt([
        {
          type: 'list',
          name: 'selected',
          message: 'Select the post or page you wish to rename.',
          choices: entries,
        },
      ]).then(function getAnswer(answer) {
        var pos = entries.indexOf(answer.selected);
        return filtered[pos];
      });
    }

    function confirmRemove(post) {
      var message = '\n - Remove ' + chalk.green.underline(post.title) + '?\n' + chalk.red.bgBlack('Warning: this action is irreversible!');
      var del = chalk.red('Delete it!');
      var can = chalk.green('Cancel');

      return inquirer.prompt([
        {
          type: 'list',
          message: message,
          name: 'answer',
          choices: [
            del,
            can,
          ],
        },
      ]).then(function getResponse(response) {
        var ans = response.answer;

        switch (ans) {
        case del:
          remove(post);
          break;
        case can:
          console.log(chalk.gray('OK. See you later.'));
          process.exit();
          break;
        default:
          console.log(chalk.red('This shouldn\'t happen, please file a bug report.'));
          process.exit();
        }
        return chalk.gray('Done.');
      });
    }

    function remove(post) {
      var src = post.full_source;

      // first check if the file exists
      fsStat(src).then(function getStats(stats) {
        if (stats.isFile()) {

          // delete the file
          fsUnlink(src).then(function unlinkFile() {
            var assetDir = src.substr(0, src.lastIndexOf('.'));
            console.log(chalk.red.underline(src + ' deleted.'));

            // check for the asset directory
            fsStat(assetDir).then(function getAssetDirStats(adStats) {
              if (adStats.isDirectory()) {

                // delete the asset dir
                fsRmdir(assetDir).then(function unlinkAssetDir() {
                  console.log(chalk.red.underline(assetDir + ' (asset directory) deleted.'));
                });
              }
            }).catch(function failAssetDir() {
              console.log(chalk.gray('No asset dir found.'));
            });
          });
        }
      }).catch(function failRemove(err) {
        console.log(chalk.red('Problem deleting article :', err));
        process.exit();
      });
    }

  }.bind(this));
};


text:
'use strict';

var _chai = require('chai');

var _index = require('../src/index.js');

var app = new _index.ArgdownApplication();
var parserPlugin = new _index.ParserPlugin();
app.addPlugin(parserPlugin, 'parse-input');

describe("Application", function () {
  it("can add, get, call and remove plugins", function () {
    var source = "Hello World!";
    var statements = 0;
    var plugin = {
      name: "TestPlugin",
      argdownListeners: {
        statementEntry: function statementEntry() {
          return statements++;
        }
      },
      run: function run(request, response) {
        response.testRunCompleted = true;
        return response;
      }
    };
    app.addPlugin(plugin, 'test');
    (0, _chai.expect)(app.getPlugin(plugin.name, 'test')).to.equal(plugin);
    var result = app.run({ process: ['parse-input', 'test'], input: source });
    (0, _chai.expect)(statements).to.equal(1);
    (0, _chai.expect)(result.testRunCompleted).to.be.true;
    statements = 0;
    app.removePlugin(plugin, 'test');
    result = app.run({ process: ['parse-input', 'test'], input: source });
    (0, _chai.expect)(statements).to.equal(0);
    (0, _chai.expect)(result.testRunCompleted).to.be.undefined;
  });
});
//# sourceMappingURL=application.spec.js.map


text:
$.ajax({
    data: { 'ini': 0, 'fin': $("#list-personas").data('items-per-page') },
    type: 'POST',
    dataType: 'json',
    url: 'php/personasSel.php',
}).done(function (data) {
    for (var key in data.resultado) {
        var original = $('#list-personas').find('.list-personas-item.hidden');

        var persona = original.clone();
        persona.removeClass('hidden');
        persona.text(data.resultado[key].PER_NOMBRE + " " + data.resultado[key].PER_P_APELLIDO + " " + data.resultado[key].PER_S_APELLIDO);
        persona.data('cedula', data.resultado[key].PER_CODIGO);

        original.before(persona);
    }

}).fail(function () {
    alert('Funcion no funciono');
});

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'php/personasCount.php',
}).done(function (data) {
    var size = parseInt(data.resultado['CANTIDAD']);
    var pageSize = $("#list-personas").data('items-per-page');
    var pages = Math.floor((size + pageSize - 1) / pageSize);

    if (pages <= 1) return;

    var pagination = $('#pagination-personas');
    pagination.removeClass('hidden');

    var original = pagination.find('.pagination-personas-item.hidden');

    for (i = 1; i <= pages; i++) {
        var page = original.clone();

        page.removeClass('hidden');
        page.find('a').text(i);

        if (i == 1) {
            page.addClass('active');
        }

        original.before(page);
    }

    original.remove();

}).fail(function () {
    alert('Funcion no funciono');
});

$('#pagination-personas').on('click', '.pagination-personas-item', function (e) {
    e.preventDefault();

    var element = $(this);
    if (element.hasClass('active')) return;

    $('#pagination-personas li').removeClass('active');
    element.addClass('active');

    var list = $('#list-personas');
    list.find('.list-personas-item').not('.hidden').remove();

    var fin = $("#list-personas").data('items-per-page');
    var ini = (element.text() - 1) * fin;

    $.ajax({
        data: { 'ini': ini, 'fin': fin },
        type: 'POST',
        dataType: 'json',
        url: 'php/personasSel.php'
    }).done(function (data) {
        var original = list.find('.list-personas-item.hidden');

        for (var key in data.resultado) {
            var persona = original.clone();
            persona.removeClass('hidden');
            persona.text(data.resultado[key].PER_NOMBRE + " " + data.resultado[key].PER_P_APELLIDO + " " + data.resultado[key].PER_S_APELLIDO);
            persona.data('cedula', data.resultado[key].PER_CODIGO);

            original.before(persona);
        }
    }).fail(function () {
        alert('Funcion no funciono');
    });
});

$('#list-personas').on('click', '.list-personas-item', function (e) {
    e.preventDefault();

    var element = $(this);
    if (element.hasClass('active')) return;

    $('#list-personas a').removeClass('active');
    element.addClass('active');

    var target = element.attr('href');
    var cedula = element.data('cedula');
    $(target).data('cedula', cedula);

    $('#form-personas').hide();
    $(target).show();

    $.ajax({
        data: { 'id_Persona': cedula },
        type: 'POST',
        dataType: 'json',
        url: 'php/personasSel.php'
    })
        .done(function (p) {
        if (p.estado == 'ok') {
            $('#name-persona').text(p.resultado[0].PER_NOMBRE + " " + p.resultado[0].PER_P_APELLIDO + " " + p.resultado[0].PER_S_APELLIDO);
            $('#codigo-persona').text(p.resultado[0].PER_CODIGO);
            $('#fechanacimiento-persona').text(p.resultado[0].PER_F_NACIMIENTO);
            $('#genero-persona').text(p.resultado[0].PER_GENERO === "M" ? "Masculino" : "Femenino");

            // CONTACTOS
            $.ajax({
                data: { 'id_Persona': p.resultado[0].PER_CODIGO },
                type: 'POST',
                dataType: 'json',
                url: 'php/contactosSel.php'
            })
                .done(function (c) {
                if (c.estado == 'ok') {
                    var list = $('#list-contactos');
                    list.empty();

                    if (!jQuery.isEmptyObject(c.resultado)) {
                        for (var key in c.resultado) {
                            var contacto = $('
', {
                                'class': 'list-group-item'
                            });
                            var btnEliminar = $('<button>', {
                                type: 'button',
                                'class': 'close',
                                'data-toggle': 'modal',
                                'data-target': '#modalRemoverContacto'
                            });

                            btnEliminar.html('');
                            btnEliminar.data('tipo', c.resultado[key].CON_TIPCODIGO);
                            btnEliminar.appendTo(contacto);
                            contacto.append(c.resultado[key].TIP_NOMBRE + ': ' + c.resultado[key].CON_DATO);

                            list.append(contacto);
                        }
                    }
                    else {
                        list.append('
No tiene contactos
');
                    }

                } else {
                    alert(c.msj);
                }
            })
                .fail(function () {
                alert('Funcion no funciono');
            });

            // DIRECCIONES
            $.ajax({
                data: { 'id_Persona': p.resultado[0].PER_CODIGO },
                type: 'POST',
                dataType: 'json',
                url: 'php/direccionesSel.php'
            })
                .done(function (d) {
                if (d.estado == 'ok') {
                    var list = $('#list-direcciones');
                    list.empty();

                    if (!jQuery.isEmptyObject(d.resultado)) {
                        for (var key in d.resultado) {
                            var direccion = $('
', {
                                'class': 'list-group-item'
                            });
                            var btnEliminar = $('<button>', {
                                type: 'button',
                                'class': 'close',
                                'data-toggle': 'modal',
                                'data-target': '#modalRemoverDireccion'
                            });

                            btnEliminar.html('');
                            btnEliminar.data('codigo', d.resultado[key].DIR_CODIGO);
                            btnEliminar.appendTo(direccion);
                            direccion.append($('
', {
                                'class': 'list-group-item-text',
                                text: 'Pais: ' + d.resultado[key].PAI_NOMBRE
                            }));
                            direccion.append($('
', {
                                'class': 'list-group-item-text',
                                text: 'Provincia: ' + d.resultado[key].PRO_NOMBRE
                            }));
                            direccion.append($('
', {
                                'class': 'list-group-item-text',
                                text: 'Canton: ' + d.resultado[key].CAN_NOMBRE
                            }));
                            direccion.append($('
', {
                                'class': 'list-group-item-text',
                                text: 'Distrito: ' + d.resultado[key].DIS_NOMBRE
                            }));
                            direccion.append($('
', {
                                'class': 'list-group-item-text',
                                text: 'Barrio: ' + d.resultado[key].BAR_NOMBRE
                            }));

                            direccion.append($('
', {
                                'class': 'list-group-item-text',
                                text: 'Direccion: ' + d.resultado[key].DIR_DESCRIPCION
                            }));

                            list.append(direccion);
                        }
                    }
                    else {
                        list.append('
No tiene direcciones
');
                    }

                } else {
                    alert(d.msj);
                }
            })
                .fail(function () {
                alert('Funcion no funciono');
            });

            // CURSOS MATRICULADOS
            $.ajax({
                data: { 'id_Persona': p.resultado[0].PER_CODIGO },
                type: 'POST',
                dataType: 'json',
                url: 'php/matriculaSel.php'
            })
                .done(function (c) {
                if (c.estado == 'ok') {
                    var list = $('#list-matriculados');
                    list.empty();

                    if (!jQuery.isEmptyObject(c.resultado)) {
                        for (var key in c.resultado) {
                            var curso = $('
', {
                                'class': 'list-group-item'
                            });
                            var btnEliminar = $('<button>', {
                                type: 'button',
                                'class': 'close',
                                'data-toggle': 'modal',
                                'data-target': '#modalRemoverContacto'
                            });
                            curso.append(c.resultado[key].CUR_NOMBRE + ' (' + c.resultado[key].TIP_TIPO_CURSO + ')');

                            list.append(curso);
                        }
                    }
                    else {
                        list.append('
No tiene cursos matriculados
');
                    }
                } else {
                    alert(c.msj);
                }
            })
                .fail(function () {
                alert('Funcion no funciono');
            });

            // CURSOS INSTRUCTOR
            /*$.ajax({
                data: { 'id': p.resultado[0].PER_CODIGO },
                type: 'POST',
                dataType: 'json',
                url: 'php/instructorGetByPer.php'
            })
                .done(function (c) {
                if (c.estado == 'ok') {
                    var list = $('#list-instructores');
                    list.empty();

                    if (!jQuery.isEmptyObject(c.resultado)) {
                        for (var key in c.resultado) {
                            var curso = $('
', {
                                'class': 'list-group-item'
                            });
                            var btnEliminar = $('<button>', {
                                type: 'button',
                                'class': 'close',
                                'data-toggle': 'modal',
                                'data-target': '#modalRemoverContacto'
                            });
                            curso.append(c.resultado[key].CUR_CODIGO + ': ' + c.resultado[key].CUR_NOMBRE);

                            list.append(curso);
                        }
                    }
                    else {
                        list.append('
No tiene cursos como instructor
');
                    }
                } else {
                    alert(c.msj);
                }
            })
                .fail(function () {
                alert('Funcion no funciono');
            });*/

        } else {
            alert(p.msj);
        }
    })
        .fail(function () {
        alert("Funcion no funciono");
    });
});

$('#list-personas').on('click', '.list-personas-add', function (e) {
    e.preventDefault();
    $('#list-personas a').removeClass('active');
    $(this).addClass('active');

    $('#details-personas').hide();
    $('#form-personas').show();

    $('#form-personas').find('input:text, input:password, input:file, select, textarea').val('');
    $('#form-personas').find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
});

$('#btnModificarPersona').on('click', function (e) {
    e.preventDefault();

    $('#details-personas').hide();
    $('#form-personas').show();

    var id_Persona = $('#details-personas').data('cedula');

    $.ajax({
        data: { 'id_Persona': id_Persona },
        type: 'POST',
        dataType: 'json',
        url: 'php/personasSel.php'
    })
        .done(function (data) {
        if (data.estado == 'ok') {
            $('#inputSecretoPersona').val(id_Persona);
            $('#inputCodigoPersona').val(data.resultado[0].PER_CODIGO);
            $('#inputNombrePersona').val(data.resultado[0].PER_NOMBRE);
            $('#inputApellido1Persona').val(data.resultado[0].PER_P_APELLIDO);
            $('#inputApellido2Persona').val(data.resultado[0].PER_S_APELLIDO);
            $('#inputGeneroPersona').val(data.resultado[0].PER_GENERO);
            $('#inputNacimientoPersona').val(data.resultado[0].PER_F_NACIMIENTO);
        } else {
            alert(data.msj);
        }
    })
        .fail(function () {
        alert('Funcion no funciono');
    });
});

$('#btnGuardarPersona').on('click', function(e) {
    e.preventDefault();

    var secreto_Persona = $('#inputSecretoPersona').val();
    var id_Persona = $('#inputCodigoPersona').val();
    var nombre_Persona = $('#inputNombrePersona').val();
    var papellido_Persona = $('#inputApellido1Persona').val();
    var sapellido_Persona = $('#inputApellido2Persona').val();
    var genero_Persona = $('#inputGeneroPersona').val();
    var fnacimiento_Persona = $('#inputNacimientoPersona').val();

    datos = {'secreto_Persona': secreto_Persona, 'id_Persona': id_Persona, 'nombre_Persona': nombre_Persona, 'papellido_Persona': papellido_Persona, 'sapellido_Persona': sapellido_Persona, 'genero_Persona': genero_Persona, 'fnacimiento_Persona': fnacimiento_Persona};

    var url = 'php/personasIns.php';
    if(secreto_Persona != '') {
        url = 'php/personasMod.php';
    }

    $.ajax({
        data: datos,
        type: 'POST',
        dataType: 'json',
        url: url
    })
        .done(function (data) {
            if (data.estado == 'ok') {
                alert(data.msj);
                location.reload();

            } else {
                alert(data.msj);
            }

        })
        .fail(function () {
           alert('Funcion no funciono');
        });

});

$('#btnEliminarPersona').on('click', function(e) {
    e.preventDefault();

    var id_Persona = $('#details-personas').data('cedula');

    $.ajax({
        data: { 'id_Persona': id_Persona },
        type: 'POST',
        dataType: 'json',
        url: 'php/personasEli.php'
    })
        .done(function (data) {
            if (data.estado == 'ok') {
                alert(data.msj)
                location.reload();
            } else {
                alert(data.msj);
            }
    })
        .fail(function () {
            alert('Funcion no funciono');
    });
});

/* CONTACTOS */
$('#modalIngresarContacto').on('show.bs.modal', function (event) {
    $.ajax({
        data: { 'ini': 0, 'fin': 32 },
        type: 'POST',
        dataType: 'json',
        url: 'php/tipocontactoSelectAll.php'
    }).done(function (data) {
        if (data.estado == '1') {
            $('#inputTipoContacto').empty();
            for (var key in data.resultados) {
                $('#inputTipoContacto').append('<option value="' + data.resultados[key].TIP_CODIGO + '">' + data.resultados[key].TIP_NOMBRE + '</option>');
            }
        } else {
            alert(data.mensaje);
        }
    }).fail(function () {
        alert('Funcion no funciono');
    });
});

$('#btnGuardarContacto').on('click', function(e) {
    e.preventDefault();

    var secreto_Contacto = $('#inputSecretoContacto').val();
    var tip_Contacto = $('#inputTipoContacto').val();
    var id_Persona = $('#details-personas').data('cedula');
    var dato_Contacto = $('#inputDatoContacto').val();

    datos = {'secreto_Contacto': secreto_Contacto, 'tip_Contacto': tip_Contacto, 'id_Persona': id_Persona, 'dato_Contacto': dato_Contacto};

    var url = 'php/contactosIns.php';
    if(secreto_Contacto != '') {
        url = 'php/contactosMod.php';
    }

    $.ajax({
        data: datos,
        type: 'POST',
        dataType: 'json',
        url: url
    })
        .done(function (data) {
            if (data.estado == 'ok') {
                alert(data.msj);
                location.reload();

            } else {
                /*ERROR, reiniciar aca toda la informacion del formulario*/
                alert(data.msj);
            }

        })
        .fail(function () {
           alert("Funcion no funciono")
        });

});

$('#modalRemoverContacto').on('show.bs.modal', function (event) {
    var boton = $(event.relatedTarget);
    var tipo = boton.data('tipo');

    var modal = $(this);
    modal.data('tipo', tipo);
});

$('#btnEliminarContacto').on('click', function(e) {
    e.preventDefault();

    var id_Persona = $('#details-personas').data('cedula');
    var tip_Contacto = $('#modalRemoverContacto').data('tipo');

    $.ajax({
        data: { 'id_Persona': id_Persona, 'tip_Contacto': tip_Contacto },
        type: 'POST',
        dataType: 'json',
        url: 'php/contactosEli.php'
    }).done(function (data) {
        if (data.estado == 'ok') {
            alert(data.msj)
            location.reload();
        } else {
            alert(data.msj);
        }
    }).fail(function () {
        alert('Funcion no funciono');
    });
});

/* DIRECCIONES */
$('#modalRemoverDireccion').on('show.bs.modal', function (event) {
    var boton = $(event.relatedTarget);
    var codigo = boton.data('codigo');

    var modal = $(this);
    modal.data('codigo', codigo);
});

$('#btnEliminarDireccion').on('click', function(e) {
    e.preventDefault();

    var id_Direccion = $('#modalRemoverDireccion').data('codigo');

    $.ajax({
        data: { 'id_Direccion': id_Direccion },
        type: 'POST',
        dataType: 'json',
        url: 'php/direccionesEli.php'
    }).done(function (data) {
        if (data.estado == 'ok') {
            alert(data.msj)
            location.reload();
        } else {
            alert(data.msj);
        }
    }).fail(function () {
        alert('Funcion no funciono');
    });
});


text:
*{

	margin:0px;
	padding:0px;

}

body
{

	width :100%;

}

.submit{

	margin-right:5px;

}

.back{

	margin-left:70px;

}

.sub{

	position :relative;
     top:30px;

}

#form2{

	 position :relative;
     top:40px;

}

@-webkit-keyframes spaceboots {
	0% { -webkit-transform: translate(2px, 1px) rotate(0deg); }
	10% { -webkit-transform: translate(-1px, -2px) rotate(-1deg); }
	20% { -webkit-transform: translate(-3px, 0px) rotate(1deg); }
	30% { -webkit-transform: translate(0px, 2px) rotate(0deg); }
	40% { -webkit-transform: translate(1px, -1px) rotate(1deg); }
	50% { -webkit-transform: translate(-1px, 2px) rotate(-1deg); }
	60% { -webkit-transform: translate(-3px, 1px) rotate(0deg); }
	70% { -webkit-transform: translate(2px, 1px) rotate(-1deg); }
	80% { -webkit-transform: translate(-1px, -1px) rotate(1deg); }
	90% { -webkit-transform: translate(2px, 2px) rotate(0deg); }
	100% { -webkit-transform: translate(1px, -2px) rotate(-1deg); }
}
.shake:hover,
.shake:focus {
	-webkit-animation-name: spaceboots;
	-webkit-animation-duration: 0.8s;
	-webkit-transform-origin:50% 50%;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-timing-function: linear;
}
.shake {
	display:inline-block
}

/*

@-webkit-keyframes thumb {
	0% { -webkit-transform: scale(1); }
	50% { -webkit-transform: scale(0.9); }
	100% { -webkit-transform: scale(1); }
}

.shake:hover
{
	-webkit-animation-name: thumb;
	-webkit-animation-duration: 200ms;
	-webkit-transform-origin:50% 50%;
	-webkit-animation-iteration-count: 2;
	-webkit-animation-timing-function: linear;
}*/


text:
#import "NSObject.h"

// Not exported
@interface CHBReader : NSObject
{
}

+ (void)readChart:(id)arg1 state:(id)arg2;

@end


text:
import pytest

import networkx as nx

import cirq
import cirq.contrib.routing as ccr

def test_ops_are_consistent_with_device_graph():
    device_graph = ccr.get_linear_device_graph(3)
    qubits = cirq.LineQubit.range(3)
    circuit = cirq.Circuit(cirq.ZZ(qubits[0], qubits[2]))
    assert not ccr.ops_are_consistent_with_device_graph(circuit.all_operations(), device_graph)
    assert not ccr.ops_are_consistent_with_device_graph(
        [cirq.X(cirq.GridQubit(0, 0))], device_graph
    )

def test_get_circuit_connectivity():
    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit(cirq.CZ(a, b), cirq.CZ(b, c), cirq.CZ(c, d), cirq.CZ(d, a))
    graph = ccr.get_circuit_connectivity(circuit)
    assert graph.number_of_nodes() == 4
    assert graph.number_of_edges() == 4
    is_planar, _ = nx.check_planarity(graph)
    assert is_planar

def test_is_valid_routing_with_bad_args():
    p, q, r = cirq.LineQubit.range(3)
    x, y = cirq.NamedQubit('x'), cirq.NamedQubit('y')
    circuit = cirq.Circuit([cirq.CNOT(x, y), cirq.CZ(x, y)])
    routed_circuit = cirq.Circuit([cirq.CNOT(p, q), cirq.CZ(q, r)])
    initial_mapping = {p: x, q: y}
    swap_network = ccr.SwapNetwork(routed_circuit, initial_mapping)
    assert not ccr.is_valid_routing(circuit, swap_network)

    def equals(*args):
        raise ValueError

    with pytest.raises(ValueError):
        ccr.is_valid_routing(circuit, swap_network, equals=equals)


text:
using namespace std;
using namespace boost;

namespace impala {

scoped_ptr<HdfsFsCache> HdfsFsCache::instance_;

void HdfsFsCache::Init() {
  DCHECK(HdfsFsCache::instance_.get() == NULL);
  HdfsFsCache::instance_.reset(new HdfsFsCache());
}

hdfsFS HdfsFsCache::GetConnection(const string& host, int port) {
  lock_guard<mutex> l(lock_);
  HdfsFsMap::iterator i = fs_map_.find(make_pair(host, port));
  if (i == fs_map_.end()) {
    hdfsBuilder* hdfs_builder = hdfsNewBuilder();
    if (!host.empty()) {
      hdfsBuilderSetNameNode(hdfs_builder, host.c_str());
    } else {
      // Connect to local filesystem
      hdfsBuilderSetNameNode(hdfs_builder, NULL);
    }
    hdfsBuilderSetNameNodePort(hdfs_builder, port);
    hdfsFS conn = hdfsBuilderConnect(hdfs_builder);
    DCHECK(conn != NULL);
    fs_map_.insert(make_pair(make_pair(host, port), conn));
    return conn;
  } else {
    return i->second;
  }
}

hdfsFS HdfsFsCache::GetDefaultConnection() {
  // "default" uses the default NameNode configuration from the XML configuration files.
  return GetConnection("default", 0);
}

hdfsFS HdfsFsCache::GetLocalConnection() {
  return GetConnection("", 0);
}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>cpuaff: cpuaff::impl::basic_cpu< TRAITS > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

cpuaff

Multi-platform C++ interface to CPU affinity management

cpuaff

impl

basic_cpu

Public Types |
Public Member Functions |
Friends |
List of all members

cpuaff::impl::basic_cpu< TRAITS > Class Template Reference

#include <fwd.hpp>

Public Types

typedef TRAITS::cpu_identifier_type 	cpu_identifier_type

typedef TRAITS::cpu_identifier_wrapper_type 	cpu_identifier_wrapper_type

Public Member Functions

 	basic_cpu ()

 	basic_cpu (const cpu_spec &spec, const cpu_identifier_wrapper_type &id, const numa_type &numa)

const numa_type & 	numa () const

const socket_type & 	socket () const

const core_type & 	core () const

const processing_unit_type & 	processing_unit () const

const cpu_spec & 	spec () const

const cpu_identifier_wrapper_type & 	id () const

bool 	operator< (const basic_cpu &rhs) const

bool 	operator== (const basic_cpu &rhs) const

Friends

std::ostream & 	operator<< (std::ostream &s, const basic_cpu &cpu)

Detailed Description

template<typename TRAITS>

class cpuaff::impl::basic_cpu< TRAITS >

basic_cpu is a representation of a cpu on the system. It contains all the data needed to get and set thread affinity as well data specifying the hardware layout of the cpu.

Member Typedef Documentation

◆ cpu_identifier_type

template<typename TRAITS >

          typedef TRAITS::cpu_identifier_type cpuaff::impl::basic_cpu< TRAITS >::cpu_identifier_type

◆ cpu_identifier_wrapper_type

template<typename TRAITS >

          typedef TRAITS::cpu_identifier_wrapper_type cpuaff::impl::basic_cpu< TRAITS >::cpu_identifier_wrapper_type

Constructor & Destructor Documentation

◆ basic_cpu() [1/2]

template<typename TRAITS >

          cpuaff::impl::basic_cpu< TRAITS >::basic_cpu
          (
          	)

inline

Constructs a basic_cpu with invalid values for all member variables

◆ basic_cpu() [2/2]

template<typename TRAITS >

          cpuaff::impl::basic_cpu< TRAITS >::basic_cpu
          (
          const cpu_spec &
          spec,

          const cpu_identifier_wrapper_type &
          id,

          const numa_type &
          numa

          )

inline

Constructs a basic_cpu with the given cpu_spec, id, and numa.

Parameters

spec	the cpu_spec (socket, core, processing unit) for this cpu

id	the native identifier for this cpu

the	numa node identifier for this cpu

Member Function Documentation

◆ core()

template<typename TRAITS >

          const core_type& cpuaff::impl::basic_cpu< TRAITS >::core
          (
          	)
           const

inline

Get the zero based core identifier for this cpu.

Returns

the zero based core identifier

◆ id()

template<typename TRAITS >

          const cpu_identifier_wrapper_type& cpuaff::impl::basic_cpu< TRAITS >::id
          (
          	)
           const

inline

Get the native cpu identifier wrapper for this cpu.

Returns

the native cpu identifier wrapper for this cpu

◆ numa()

template<typename TRAITS >

          const numa_type& cpuaff::impl::basic_cpu< TRAITS >::numa
          (
          	)
           const

inline

Get the zero based numa node identifier for this cpu.

Returns

the zero based numa node identifier for this cpu

◆ operator<()

template<typename TRAITS >

          bool cpuaff::impl::basic_cpu< TRAITS >::operator<
          (
          const basic_cpu< TRAITS > &
          rhs	)
           const

inline

Less than operator to allow basic_cpu to be a key in stl maps/sets

Parameters

rhs	the basic_cpu to compare to

Returns

true if this basic_cpu compares less than rhs. false otherwise.

◆ operator==()

template<typename TRAITS >

          bool cpuaff::impl::basic_cpu< TRAITS >::operator==
          (
          const basic_cpu< TRAITS > &
          rhs	)
           const

inline

Equality operator

Parameters

rhs	the basic_cpu to compare to

Returns

true if this basic_cpu has the same socket, core, and processing unit as rhs, false otherwise.

◆ processing_unit()

template<typename TRAITS >

          const processing_unit_type& cpuaff::impl::basic_cpu< TRAITS >::processing_unit
          (
          	)
           const

inline

Get the zero based processing unit identifier for this cpu.

Returns

the zero based processing unit identifier

◆ socket()

template<typename TRAITS >

          const socket_type& cpuaff::impl::basic_cpu< TRAITS >::socket
          (
          	)
           const

inline

Get the zero based socket identifier for this cpu.

Returns

the zero based socket identifier

◆ spec()

template<typename TRAITS >

          const cpu_spec& cpuaff::impl::basic_cpu< TRAITS >::spec
          (
          	)
           const

inline

Get the cpu_spec for this cpu

Returns

the cpu_spec for this cpu

Friends And Related Function Documentation

◆ operator<<

template<typename TRAITS >

          std::ostream& operator<<
          (
          std::ostream &
          s,

          const basic_cpu< TRAITS > &
          cpu

          )

friend

Stream operator

Print [id, numa, socket, core, processing unit]

The documentation for this class was generated from the following files:

include/cpuaff/fwd.hpp

include/cpuaff/impl/basic_cpu.hpp

<address class="footer">
Generated on Sat Nov 4 2017 12:43:53 for cpuaff by

 1.8.13
</address>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Open Modal with Form</title>

        <link rel="stylesheet" href="css/style.css">

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

  <title>Tabs Example</title>
<link href="css/ionic.css" rel="stylesheet">

  <ion-nav-bar class="bar-positive">
    <ion-nav-back-button class="button-icon ion-arrow-left-c">
    </ion-nav-back-button>
  </ion-nav-bar>

  <ion-nav-view></ion-nav-view>


text:
using System;
using NUnit.Framework;

namespace OneOf.UnitTests
{
    [TestFixture]
    public class MatchTests : OneOfTestBase
    {
        [Test]
        public void ReturnsDefaultWhenNoMatch()
        {
            var oo = new OneOf<int, string>(123);

            var ret = oo.Match((string x) => FailIfCalled<string>())
                        .Else((object x) => "ELSE:" + x.ToString());

            Assert.AreEqual("ELSE:123", ret);
        }

        [Test]
        public void ThrowsExceptionWhenNoMatch()
        {
            var oo = new OneOf<int, string>(123);

            TestDelegate test = () =>
            {
                var ret = oo
                    .Match((string x) => FailIfCalled<string>())
                    .ElseThrow((object x) => new InvalidOperationException());
            };

            NUnit.Framework.Assert.Throws<InvalidOperationException>(test);
        }

        [Test]
        public void ReturnsValueWhenMatch()
        {
            var oo = new OneOf<int, string>(123);

            var ret = oo.Match((string x) => FailIfCalled<string>())
                        .Match((int x) => "OK:" + x.ToString());

            Assert.AreEqual("OK:123", ret);
        }
    }
}


text:
function _typeof(obj) {
    for (var i = 1; obj && i < arguments.length; ++i) {
        if(typeof obj[arguments[i]] =='undefined'){
            return false;
        }
        obj = obj[arguments[i]]
    }
    return obj;
}
function eventFire(el, etype){
    if (el.fireEvent) {
        el.fireEvent('on' + etype);
    } else {
        var evObj = document.createEvent('HTMLEvents');
        evObj.initEvent(etype, false, true);
        el.dispatchEvent(evObj);
    }
}
function deepClone(obj, hash = new WeakMap()) {
    if (Object(obj) !== obj) return obj; // primitives
    if (hash.has(obj)) return hash.get(obj); // cyclic reference
    var result = Array.isArray(obj) ? []
        : obj.constructor ? new obj.constructor() : {};
    hash.set(obj, result);
    if (obj instanceof Map)
        Array.from(obj, ([key, val]) => result.set(key, deepClone(val, hash)) );
    return Object.assign(result, ...Object.keys(obj).map (
        key => ({ [key]: deepClone(obj[key], hash) }) ));
}
export { eventFire, _typeof, deepClone };


text:
from __future__ import absolute_import
from __future__ import unicode_literals
from ..util_tests import TestLogin
import evesrp
from evesrp import db
from evesrp.auth import PermissionType
from evesrp.auth.models import User, Group, Division, Permission
from evesrp.transformers import Transformer

class TestAddDivision(TestLogin):

    def test_add_division(self):
        client = self.login(self.admin_name)
        resp = client.post('/division/add/', follow_redirects=True,
                data={'name': 'Test Division'})
        self.assertEqual(resp.status_code, 200)
        with self.app.test_request_context():
            divisions = Division.query.all()
            self.assertEqual(len(divisions), 1)
            self.assertEqual(divisions[0].name, 'Test Division')

class TestListDivisions(TestLogin):

    def setUp(self):
        super(TestListDivisions, self).setUp()
        with self.app.test_request_context():
            divisions = [
                Division('Division One'),
                Division('Division Two'),
                Division('Division Three'),
            ]
            db.session.add_all(divisions)
            db.session.commit()

    def test_list_divisions(self):
        client = self.login(self.admin_name)
        resp = client.get('/division/', follow_redirects=True)
        self.assertIn('Division One', resp.get_data(as_text=True))
        self.assertIn('Division Two', resp.get_data(as_text=True))
        self.assertIn('Division Three', resp.get_data(as_text=True))

class TestDivisionDetails(TestLogin):

    def setUp(self):
        super(TestDivisionDetails, self).setUp()
        with self.app.test_request_context():
            db.session.add(Division('Test Division'))
            db.session.add(Group('Group 1', self.default_authmethod.name,
                    id=10))
            db.session.commit()
        self.app.config['SRP_SHIP_TYPE_URL_TRANSFORMERS'] = [
            ('Test Transformer', ''),
        ]
        evesrp.init_app(self.app)

    def test_add_entity_by_id(self):
        client = self.login(self.admin_name)
        resp = client.post('/division/1/', follow_redirects=True, data={
                'action': 'add',
                'permission': 'submit',
                'id_': 10,
                'form_id': 'entity',
        })
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Group 1', resp.get_data(as_text=True))
        with self.app.test_request_context():
            self.assertIsNotNone(Permission.query.filter_by(division_id=1,
                    entity_id=10, permission=PermissionType.submit).first())

    def test_add_entity_by_name(self):
        client = self.login(self.admin_name)
        resp = client.post('/division/1/', follow_redirects=True, data={
                'action': 'add',
                'permission': 'submit',
                'name': 'Group 1',
                'form_id': 'entity',
        })
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Group 1', resp.get_data(as_text=True))
        with self.app.test_request_context():
            self.assertIsNotNone(Permission.query.filter_by(division_id=1,
                    entity_id=10, permission=PermissionType.submit).first())

    def test_set_url_transformer(self):
        client = self.login(self.admin_name)
        resp = client.post('/division/1/', follow_redirects=True, data={
                'transformer': 'Test Transformer',
                'attribute': 'ship_type',
                'form_id': 'transformer',
        })
        self.assertEqual(resp.status_code, 200)
        with self.app.test_request_context():
            division = Division.query.get(1)
            self.assertEqual(division.transformers['ship_type'],
                    self.app.url_transformers['ship_type']['Test Transformer'])

    def test_unset_url_transformer(self):
        client = self.login(self.admin_name)
        with self.app.test_request_context():
            division = Division.query.get(1)
            division.ship_transformer = \
                    self.app.url_transformers['ship_type']['Test Transformer']
            db.session.commit()
        resp = client.post('/division/1/', follow_redirects=True, data={
                'transformer': 'none',
                'attribute': 'ship_type',
                'form_id': 'transformer',
        })
        self.assertEqual(resp.status_code, 200)
        with self.app.test_request_context():
            division = Division.query.get(1)
            self.assertIsNone(division.transformers.get('ship_type', None))


text:
In our progress towards browserless, modular TDD, we wound up a spot
where...we can't run in a browser! Since browsers don't currently
support modules, and certainly not CommonJS modules, we need a way
to transform our code into a browser-friendly format.

In this section we look at using
[Webpack](https://webpack.github.io)
to bundle our modular, CommonJS code into a single file fit for
the browser. Along the way, we also reduce our HTTP requests
by bundling our dependencies into the same file.

Finally, we end in a super spot: we switch to using Webpack's
development server, which re-bundles in-memory on every change *and*
automatically updates your browser, hands-free.

## Overview

- Show problem with using modules in a browser *without* a module loader

- Introduce and install Webpack

- Generate and use a bundle, including with external dependency

- Show live bundling and reloading with `webpack-dev-server`

## The Problem

Let's write a small web application, based around the `incrementer` in our
[Modules with CommonJS](../modules/modules.md). First, an ``index1.html``
file:

[include](../../../src/webpack/index1.html)

This loads a file `app1.js`:

[include](../../../src/webpack/app1.js)

...which uses CommonJS modules to import `incrementer` from `./lib.js`:

[include](../../../src/webpack/lib.js)

PyCharm makes this easy to run. In the editor tab for `index1.html`,
mouse-over the symbol for one of the browsers and click it to open in
the internal PyCharm webserver:

![Screenshot Chrome console](chrome_console.png)

As the screenshot shows, the browser console tells us we have a JavaScript
error `Uncaught ReferenceError: require is not defined`. Not surprising:
browsers don't support CommonJS export/import and modules, so `require`
is not available in a browser.

We need a module bundler. We'll use Webpack.

## Installation

Our goal is to take all of our Node-style, browserless, modular code
and combine it into a single `bundle.js` file, including jQuery as
a dependency. Let's use `npm` to install Webpack (and its development
server) as a *development* dependency:

```html
$ npm install --save-dev webpack webpack-dev-server
```

We can now run Webpack to "bundle" our files together:

```html
$ node_modules/.bin/webpack app1.js -o bundle.js
```

With this command, Webpack looks in `app1.js` for any `require`
imports, then in any of those imported files for more imports, and
bundles all the files into a single output file called `bundle.js`.

If we change our HTML to point at this `bundle.js` file:

[include](../../../src/webpack/index2.html)

...then we can see `4` in the browser console with no errors:

![Screenshot Chrome console works](chrome_console_works.png)

> #### info::Note
>
> What is the `bundle.js.map` file that got generated? Bundlers
> have a habit of making the tracebacks hard to follow back to
> the original line in the original file. The "source map"
> contains all the extra information needed for this. It is only
> loaded when the browser has the console window open for
> debugging. This source map can also be inlined into the
> `bundle.js` instead of into a separate file.

## Including Library Code

Imagine our frontend application used jQuery. In this case, included
via a `<script>` that pointed at a CDN:

[include](../../../src/webpack/index3.html)

Instead of logging the `incrementer` value to the console, we might
use jQuery to save it to the `<h1>` text node:

[include](../../../src/webpack/app2.js)

After re-bundling, this works fine in our browser:

![Screenshot After jQuery](after_jquery1.png)

However, we're not doing anything that feels like Pythonic development:

- Record a dependency on a version of jQuery

- Import jQuery into our application, rather than expecting it to
  magically appear as a global via `<script>`

Plus, we are making an extra HTTP request to get jQuery. Wouldn't it be
great if our frontend toolchain helped us manage this?

First we use `npm` to install jQuery as a dependency:

```html
$ npm install --save jquery
```

This gets the code into `node_modules` and adds an entry in
`package.json`. We now need to import it into our application code:

[include](../../../src/webpack/app3.js)

We can now eliminate the `<script>` that loads jQuery from CDN:

[include](../../../src/webpack/index4.html)

Loading `index4.html` in your browser via PyCharm shows this still
works. How did jQuery get in there? Webpack saw it imported, fetched
it, and included it.

We now have our external dependencies as part of our frontend toolchain
with revision control. Not too shabby. But we can take another, very
cool step forward.

> #### info::Note
>
> Why is bundle.map so big? It's now at 270 Kb. Well, jQuery isn't
> tiny. But also, we haven't done any work to make it smaller.
> Webpack can "minify", which strips out any comments and does lots
> of tricks for shrinking. Also, we are including the full jQuery.
> It is now available as multiple CommonJS submodules, so you can get
> only what you need. Or use a jQuery alternative.

## Live Bundling and Reload

It is certainly not fun having to re-bundle on every change. Wouldn't it
be nice if we had a tool that watched your files, and whenever anything
changed, would re-bundle? Or even better, provide a web server which
not only re-bundled, but told the browser to reload the page, hands-free?

The
[Webpack Dev Server](https://webpack.github.io/docs/webpack-dev-server.html)
does just this.
In fact, it doesn't write a bundle file to disk. It keeps things in memory.

We installed it at the top of this article, so we can jump straight into
using it:

```html
$ node_modules/.bin/webpack-dev-server app3.js
```

As logged to your console, this starts a web server on port 8080, so you can
now load `http://localhost:8080/webpack-dev-server/index4.html`. You
should see:

![Screenshot webpack dev server](webpack_dev_server.png)

Now, every time you make a change, the bundle will be regenerated *and* the
browser will reload the page. It's a seemingly-small, but in practice huge,
change in frontend development.

To make this more natural in PyCharm, we can first move the Webpack command
line options to a config file. By default, Webpack looks in
`webpack.config.js` in the project roo:

[include](../../../src/webpack/webpack.config.js)

We put in the options to drive both `webpack` and `webpack-dev-server`.
Next, let's automate this task by adding an `npm run` script in
`package.json`:

[include](../../../src/webpack/package.json)

Because `start` is a pre-defined shortcut, we can run `npm start` from
the command line. Or, we can let PyCharm browser our `package.json`'s
npm run scripts and execute `start` (and thus the `webpack-dev-server`)
in a run tool window.

## Wrapup

That wasn't too hard. Admittedly, that's because this introductory article
took the easiest possible course. As it turns out, bundling has a *ton* of
functionality and also thorny issues at nearly every turn.

It's one of the bittest pills in the frontend toolchain. On one hand, you
have the chance to radically improve your productivity and get a Pythonic
development cycle. On the other hand, you spend a large portion of your time
learning (constantly changing) tools and fighting the problems they introduce.

There are solutions to this. If you don't want to be bleeding edge, stick to
the minimum, such as the scope in this article.


text:
import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('reservations', '0002_auto_20191030_1851'),
    ]

    operations = [
        migrations.AlterField(
            model_name='queue',
            name='difficulty',
            field=models.PositiveSmallIntegerField(default=3, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)]),
        ),
    ]


text:
import { ExecutionContext, test } from 'ava';

import { Failure } from '../../src/try/failure';
import { Some } from '../../src/option/some';
import { Success } from '../../src/try/success';
import { Try } from '../../src/try/try';

const success: Try<string> = new Success('hello');

test('Success#isFailure', (t: ExecutionContext) => {
  t.false(success.isFailure);
});

test('Success#isSuccess', (t: ExecutionContext) => {
  t.true(success.isSuccess);
});

test('Success#equals', (t: ExecutionContext) => {
  t.true(success.equals(new Success('hello')));

  t.false(success.equals(new Success('world')));
});

test('Success#filter', (t: ExecutionContext) => {
  t.is(
    success.filter((v: string) => v === 'hello'),
    success
  );
  t.deepEqual(
    success.filter((v: string) => v === 'world'),
    new Failure<string>(new Error('Predicate does not hold for hello'))
  );
});

test('Success#flatMap', (t: ExecutionContext) => {
  t.deepEqual(
    success.flatMap(() => new Success('world')),
    new Success('world')
  );
});

test('Success#foreach', (t: ExecutionContext) => {
  let executions: number = 0;

  success.foreach(() => { executions += 1; });

  t.is(executions, 1);
});

test('Success#get', (t: ExecutionContext) => {
  try {
    t.is(
      success.get(),
      'hello'
    );
  }
  catch (e) {
    t.fail();
  }
});

test('Success#getOrElse', (t: ExecutionContext) => {
  t.is(
    success.getOrElse(() => 'world'),
    'hello'
  );
});

test('Success#map', (t: ExecutionContext) => {
  t.deepEqual(
    success.map((v: string) => `${v} world`),
    new Success('hello world')
  );
});

test('Success#match', (t: ExecutionContext) => {
  t.is(
    success.match({
      Success: (v: string): string => v,
      Failure: (): string => 'world'
    }),
    'hello'
  );
});

test('Success#orElse', (t: ExecutionContext) => {
  t.deepEqual(
    success.orElse(() => new Success('world')),
    new Success('hello')
  );
});

test('Success#recover', (t: ExecutionContext) => {
  t.is(
    success.recover((error: Error) => 'world'),
    success
  );
});

test('Success#recoverWith', (t: ExecutionContext) => {
  t.deepEqual(
    success.recoverWith((error: Error) => new Success('world')),
    success
  );
});

test('Success#toOption', (t: ExecutionContext) => {
  t.deepEqual(
    success.toOption(),
    new Some('hello')
  );
});


text:
/**
 * Created by Eirik on 17.09.2015.
 */
angular.module('ExamApp').controller('ExamsSavedController', ['$scope','savedExams', '$rootScope', 'Exam', function($scope, savedExams, $rootScope, Exam){

    //$scope.savedExams = savedExams;
    $scope.savedExams = Exam.getSavedExams();

    /*
    var sessionExams = localStorage.getItem("sessionexams");
    if(sessionExams) {
        $scope.savedExams = JSON.parse(sessionExams);
    }
*/
    $scope.updateNav = function() {
        $rootScope.$emit('UpdateNav', Exam.getSavedExamsLength());
    };

    $scope.showingPdfForIndex = -1;

    $scope.removeSaved = function(index) {
        $scope.hidePdf();
        Exam.delete(index);
        $scope.savedExams = Exam.getSavedExams();
        $scope.updateNav();

    };

    $scope.showPdf = function (index) {
        $scope.hidePdf();
        $scope.showingPdfForIndex = index;
        var examTable = document.getElementById('examstable').getElementsByTagName('tbody')[0];
        var row = examTable.insertRow(index+1);
        row.id = "pdfRow" ;
        row.innerHTML = '

	';
    };

    $scope.hidePdf = function() {
        $scope.showingPdfForIndex = -1;

        var pdfRow = document.getElementById("pdfRow");
        if(pdfRow) {
            pdfRow.parentNode.removeChild(pdfRow);

        }

    };

    $scope.isActiveRow = function(index) {
        return index === $scope.showingPdfForIndex;
    };

    $scope.clearList = function() {
        $scope.hidePdf();
        Exam.deleteSaved();
        $scope.savedExams = Exam.getSavedExams();
        $scope.updateNav();
    }

}]);


text:
package at.favre.lib.dali.builder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import at.favre.lib.dali.Dali;
import at.favre.lib.dali.builder.blur.BlurWorker;
import at.favre.lib.dali.util.BuilderUtil;

public class ExecutorManager {
    private static final int MAX_QUEUE = 25;

    public enum ThreadPoolType {
        SERIAL, CONCURRENT
    }

    private ThreadPoolExecutor serialThreadPool;
    private ThreadPoolExecutor concurrentThreadPool;
    private ThreadPoolExecutor fireAndForgetThreadPool;

    private Map<String, List<Future<BlurWorker.Result>>> taskList;

    public ExecutorManager(int maxConcurrentMainWorkers) {
        concurrentThreadPool = new ThreadPoolExecutor(maxConcurrentMainWorkers, maxConcurrentMainWorkers, 5000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(MAX_QUEUE));
        concurrentThreadPool.allowCoreThreadTimeOut(true);

        serialThreadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(MAX_QUEUE));

        fireAndForgetThreadPool = new ThreadPoolExecutor(4, 4, 5000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(MAX_QUEUE));
        fireAndForgetThreadPool.allowCoreThreadTimeOut(true);

        taskList = new ConcurrentHashMap<String, List<Future<BlurWorker.Result>>>();
    }

    public Future<BlurWorker.Result> submitThreadPool(Callable<BlurWorker.Result> callable, String tag, ThreadPoolType type) {
        Future<BlurWorker.Result> future = null;

        if (type.equals(ThreadPoolType.CONCURRENT)) {
            future = concurrentThreadPool.submit(callable);
        } else {
            future = serialThreadPool.submit(callable);
        }

        if (!taskList.containsKey(tag)) {
            taskList.put(tag, new ArrayList<Future<BlurWorker.Result>>());
        }

        taskList.get(tag).add(future);

        removeDoneTasks();

        return future;
    }

    /**
     * Cancel all task with this tag and returns the canceled task count
     *
     * @param tagToCancel
     * @return
     */
    public synchronized int cancelByTag(String tagToCancel) {
        int i = 0;
        if (taskList.containsKey(tagToCancel)) {
            removeDoneTasks();

            for (Future<BlurWorker.Result> future : taskList.get(tagToCancel)) {
                BuilderUtil.logVerbose(Dali.getConfig().logTag, "Canceling task with tag " + tagToCancel, Dali.getConfig().debugMode);
                future.cancel(true);
                i++;
            }

            //remove all canceled tasks
            Iterator<Future<BlurWorker.Result>> iter = taskList.get(tagToCancel).iterator();
            while (iter.hasNext()) {
                if (iter.next().isCancelled()) {
                    iter.remove();
                }
            }
        }
        return i;
    }

    private void removeDoneTasks() {
        for (String tag : taskList.keySet()) {
            Iterator<Future<BlurWorker.Result>> iter = taskList.get(tag).iterator();
            while (iter.hasNext()) {
                if (iter.next().isDone()) {
                    iter.remove();
                }
            }
            if (taskList.get(tag).isEmpty()) {
                taskList.remove(tag);
            }
        }
    }

    public void executeOnFireAndForgetThreadPool(Runnable r) {
        fireAndForgetThreadPool.execute(r);
    }

    public void shutDown() {
        concurrentThreadPool.shutdown();
        serialThreadPool.shutdown();
        fireAndForgetThreadPool.shutdown();
    }
}