text:
package fi.testee;

import fi.testee.deployment.BeanArchiveDiscovery;
import fi.testee.interceptor.UseInterceptor;
import fi.testee.jdbc.PlaygroundConnectionFactory;
import fi.testee.jdbc.TestDataSource;
import org.junit.Test;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.sql.DataSource;

import static fi.testee.interceptor.TestInterceptor.Type.AROUND_INVOKE;
import static fi.testee.interceptor.TestInterceptor.Type.POST_CONSTRUCT;
import static fi.testee.interceptor.TestInterceptor.Type.PRE_DESTROY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class DependencyInjectionTest extends BaseDependencyInjectionTest<DependencyInjectionTest.TestBean> {
    public DependencyInjectionTest() {
        super(TestBean.class);
    }

    @Test
    public void cdi_in_root_via_inject() {
        runTest(() -> {
            assertNotNull(root.getCdiInRootViaInject());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void ejb_in_root_via_ejb() {
        runTest(() -> {
            assertNotNull(root.getEjbInRootViaEjb());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void ejb_in_cdi_via_inject() {
        runTest(() -> {
            assertNotNull(root.getCdiInRootViaInject().getEjbInCdiViaInject());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT);
            ensureInterception(ExampleBean1.class, "getEjbInCdiViaInject", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void ejb_in_ejb_via_inject() {
        runTest(() -> {
            assertNotNull(root.getEjbInRootViaEjb().getEjbInEjbViaInject());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT); // TODO can't this happen lazily?
            ensureInterception(SessionBean1.class, "getEjbInEjbViaInject", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });

    }

    @Test
    public void ejbIface_in_root_via_inject() {
        runTest(() -> {
            assertEquals("Hello, world", root.ejbIfaceViaInject.test());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT); // TODO can't this happen lazily?
            ensureInterception(SessionBean1.class, "test", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void ejbIface_in_root_via_ejb() {
        runTest(() -> {
            assertEquals("Hello, world", root.ejbIfaceViaInject.test());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT); // TODO can't this happen lazily?
            ensureInterception(SessionBean1.class, "test", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void ejb_in_ejb_via_ejb() {
        runTest(() -> {
            assertNotNull(root.getEjbInRootViaEjb().getEjbInEjbViaEjb());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT); // TODO can't this happen lazily?
            ensureInterception(SessionBean1.class, "getEjbInEjbViaEjb", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void resource_in_ejb() {
        runTest(() -> {
            assertNotNull(root.getEjbInRootViaEjb().getResourceInEjb());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT); // TODO can't this happen lazily?
            ensureInterception(SessionBean1.class, "getResourceInEjb", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void resource_in_root() {
        runTest(() -> {
            assertNotNull(root.getResourceInRoot());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT); // TODO can't this happen lazily?
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void resource_in_cdi() {
        runTest(() -> {
            assertNotNull(root.getCdiInRootViaInject().getResourceInCdi());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT);
            ensureInterception(ExampleBean1.class, "getResourceInCdi", AROUND_INVOKE);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Test
    public void bean_from_different_archive() {
        runTest(() -> {
            assertNotNull(root.getBeanFromDifferentArchive());
            ensureInterception(ExampleBean1.class, null, POST_CONSTRUCT);
        }, () -> {
            ensureInterception(ExampleBean1.class, null, PRE_DESTROY);
        });
    }

    @Override
    TestBean instance() {
        return new TestBean();
    }

    @Stateless
    @UseInterceptor
    public static class SessionBean2 {
        @PostConstruct
        public void postConstruct() {
        }

        @PreDestroy
        public void preDestroy() {
        }
    }

    public interface SessionBeanInterface {
        String test();
    }

    public abstract static class BaseSessionBean {
        @EJB
        private SessionBean2 ejbInEjbViaEjb;

        public SessionBean2 getEjbInEjbViaEjb() {
            return ejbInEjbViaEjb;
        }
    }

    @Stateless
    @UseInterceptor
    public static class SessionBean1 extends BaseSessionBean implements SessionBeanInterface {
        @Inject
        private SessionBean2 ejbInEjbViaInject;
        @Resource(mappedName = "testds")
        private DataSource resourceInEjb;

        public SessionBean2 getEjbInEjbViaInject() {
            return ejbInEjbViaInject;
        }

        public DataSource getResourceInEjb() {
            return resourceInEjb;
        }

        @Override
        public String test() {
            return "Hello, world";
        }
    }

    @UseInterceptor
    public static class ExampleBean1 {
        @Inject
        private SessionBean1 ejbInCdiViaInject;
        @Resource(mappedName = "testds")
        private DataSource resourceInCdi;

        @PostConstruct
        public void postConstruct() {
        }

        @PreDestroy
        public void preDestroy() {
        }

        public SessionBean1 getEjbInCdiViaInject() {
            return ejbInCdiViaInject;
        }

        public DataSource getResourceInCdi() {
            return resourceInCdi;
        }
    }

    @UseInterceptor
    public static abstract class BaseTestBean {
        @EJB
        private SessionBean1 ejbInRootViaEjb;
        @Resource(mappedName = "testds")
        private DataSource resourceInRoot;

        public SessionBean1 getEjbInRootViaEjb() {
            return ejbInRootViaEjb;
        }

        public DataSource getResourceInRoot() {
            return resourceInRoot;
        }
    }

    @TestDataSource(name = "testds", factory = PlaygroundConnectionFactory.class)
    public static class TestBean extends BaseTestBean {
        @Inject
        private ExampleBean1 cdiInRootViaInject;
        @Inject
        private BeanArchiveDiscovery beanFromDifferentArchive;
        @Inject
        private SessionBeanInterface ejbIfaceViaInject;
        @EJB
        private SessionBeanInterface ejbIfaceViaEjb;

        public ExampleBean1 getCdiInRootViaInject() {
            return cdiInRootViaInject;
        }

        public BeanArchiveDiscovery getBeanFromDifferentArchive() {
            return beanFromDifferentArchive;
        }
    }

}


text:
package com.amazonaws.services.machinelearning.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.machinelearning.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RDSMetadataMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RDSMetadataMarshaller {

    private static final MarshallingInfo<StructuredPojo> DATABASE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Database").build();
    private static final MarshallingInfo<String> DATABASEUSERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DatabaseUserName").build();
    private static final MarshallingInfo<String> SELECTSQLQUERY_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SelectSqlQuery").build();
    private static final MarshallingInfo<String> RESOURCEROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceRole").build();
    private static final MarshallingInfo<String> SERVICEROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ServiceRole").build();
    private static final MarshallingInfo<String> DATAPIPELINEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DataPipelineId").build();

    private static final RDSMetadataMarshaller instance = new RDSMetadataMarshaller();

    public static RDSMetadataMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(RDSMetadata rDSMetadata, ProtocolMarshaller protocolMarshaller) {

        if (rDSMetadata == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(rDSMetadata.getDatabase(), DATABASE_BINDING);
            protocolMarshaller.marshall(rDSMetadata.getDatabaseUserName(), DATABASEUSERNAME_BINDING);
            protocolMarshaller.marshall(rDSMetadata.getSelectSqlQuery(), SELECTSQLQUERY_BINDING);
            protocolMarshaller.marshall(rDSMetadata.getResourceRole(), RESOURCEROLE_BINDING);
            protocolMarshaller.marshall(rDSMetadata.getServiceRole(), SERVICEROLE_BINDING);
            protocolMarshaller.marshall(rDSMetadata.getDataPipelineId(), DATAPIPELINEID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
import { createStore } from '../src';

describe('createStore', () => {
  it('exposes the public API', () => {
    const store = createStore();
    const methods = Object.keys(store);

    expect(methods.length).toBe(3);
    expect(methods).toContain('getState');
    expect(methods).toContain('getStore');
    expect(methods).toContain('dispatch');
  });

  it('accepts an initial state', () => {
    const store = createStore({
      count: 0,
      foo: 'bar'
    });

    expect(store.getState()).toEqual({
      count: 0,
      foo: 'bar'
    });
  });
});


text:
class AddImageToPlayers < ActiveRecord::Migration[5.0]
  def change
    add_column :players, :image, :string
  end
end


text:
export type FulfillmentRequest = {
    responseId: string,
    queryResult: {
        queryText: string,
        action: string,
        parameters: any,
        intent: {
            name: string,
            displayName: string
        },
        intentDetectionConfidence: number,
        languageCode: string
    },
    originalDetectIntentRequest: any,
    session: string
}

export type FulfillmentResponse = {
    // speech?: string;
    // displayText?: string;
    // data?: {
    //     slack?: any
    // };
    fulfillmentText: string,
    payload?: {
        slack: any
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>"engine/loggers/logger-cfg" | tia</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					tia

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited

					Menu

					Globals

					"engine/loggers/logger-cfg"

External module "engine/loggers/logger-cfg"

Index

Variables

console<wbr>Log<wbr>Prefix

defLLLog<wbr>Action

err<wbr>Prefix

exc<wbr>Prefix

indentation

Functions

get<wbr>DefLLLog<wbr>Action

set<wbr>DefLLLog<wbr>Action

Variables

Const console<wbr>Log<wbr>Prefix

console<wbr>Log<wbr>Prefix: "" = ""

Defined in engine/loggers/logger-cfg.ts:1

Let defLLLog<wbr>Action

defLLLog<wbr>Action: boolean | null = null

Defined in engine/loggers/logger-cfg.ts:7

Const err<wbr>Prefix

err<wbr>Prefix: "ERR: " = "ERR: "

Defined in engine/loggers/logger-cfg.ts:2

Const exc<wbr>Prefix

exc<wbr>Prefix: "EXC: " = "EXC: "

Defined in engine/loggers/logger-cfg.ts:3

Const indentation

indentation: "| " = "| "

Defined in engine/loggers/logger-cfg.ts:4

Functions

get<wbr>DefLLLog<wbr>Action

get<wbr>DefLLLog<wbr>Action(): boolean

Defined in engine/loggers/logger-cfg.ts:13

Returns boolean

set<wbr>DefLLLog<wbr>Action

set<wbr>DefLLLog<wbr>Action(enable: boolean): void

Defined in engine/loggers/logger-cfg.ts:9

Parameters

enable: boolean

Returns void

						Globals

						"engine/loggers/logger-<wbr>cfg"

						console<wbr>Log<wbr>Prefix

						defLLLog<wbr>Action

						err<wbr>Prefix

						exc<wbr>Prefix

						indentation

						get<wbr>DefLLLog<wbr>Action

						set<wbr>DefLLLog<wbr>Action

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Type alias with type parameter

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method


text:
CREATE TABLE BASE (
	-- Base has Base GUID
	BASE_GUID                               RAW(16) NOT NULL DEFAULT SYS_GUID(),
	-- Base has base-Val
	BASE_VAL                                Val NOT NULL,
	-- Primary index to Base(Base GUID in "Base has Base GUID")
	PRIMARY KEY(BASE_GUID)
);

CREATE TABLE "PARTITION" (
	-- Partition is a kind of Base that has Base GUID
	BASE_GUID                               RAW(16) NOT NULL DEFAULT SYS_GUID(),
	-- Partition is a kind of Base that has base-Val
	BASE_VAL                                Val NOT NULL,
	-- Partition has part-Val
	PART_VAL                                Val NOT NULL,
	-- Primary index to Partition(Base GUID in "Base has Base GUID")
	PRIMARY KEY(BASE_GUID)
);

CREATE TABLE PARTITION_IND (
	-- PartitionInd is a kind of Base that has Base GUID
	BASE_GUID                               RAW(16) NOT NULL,
	-- PartitionInd is a kind of Base that has base-Val
	BASE_VAL                                Val NOT NULL,
	-- PartitionInd has PartitionInd Key
	PARTITION_IND_KEY                       RAW(16) NOT NULL DEFAULT SYS_GUID(),
	-- maybe PartitionInd is an AbsorbedPart that has abs- part Val
	ABSORBED_PART_ABS_PART_VAL              Val NULL,
	-- Primary index to PartitionInd(PartitionInd Key in "PartitionInd has PartitionInd Key")
	PRIMARY KEY(PARTITION_IND_KEY),
	-- Unique index to PartitionInd(Base GUID in "Base has Base GUID")
	UNIQUE(BASE_GUID)
);

CREATE TABLE SEPARATE (
	-- Separate is a kind of Base that has Base GUID
	BASE_GUID                               RAW(16) NOT NULL,
	-- Separate has sep-Val
	SEP_VAL                                 Val NOT NULL,
	-- Primary index to Separate(Base in "Separate is a kind of Base")
	PRIMARY KEY(BASE_GUID),
	FOREIGN KEY (BASE_GUID) REFERENCES BASE (BASE_GUID)
);


text:
package com.timtripcony;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;
import org.openntf.domino.Document;
import org.openntf.domino.Item;
import org.openntf.domino.Item.Type;
import org.openntf.domino.utils.DominoUtils;
import org.openntf.osgiworlds.model.GenericDatabaseUtils;

import com.ibm.commons.util.StringUtil;
import com.ibm.jscript.debug.ArrayListUtil;
import com.vaadin.ui.Notification;

import uk.co.intec.keyDatesApp.model.KeyDateDatabaseUtils;

/**
 * @author Tim Tripcony, Paul Withers
 *
 *         Extension of AbstractMapModel to add Document-related /
 *         XPages-related properties. Amended by PW to rely on OpenNTF Domino
 *         API (this allowed me to remove a lot of code Tim had repeated from
 *         ODA)
 *
 */
public abstract class AbstractDocumentMapModel extends AbstractMapModel {
	private static final long serialVersionUID = 1L;
	private String unid;
	private String parentUnid;
	private String documentId;
	private boolean newNote;
	private boolean deleted;
	private boolean readOnly;
	private Map<String, Item.Type> fieldTypeMap;
	private HashMap<String, Class<?>> typeConversionMap;

	/**
	 * Constructor, calling overloaded constructor and simulating DominoDocument
	 * datasource, to get default Document based on URL
	 */
	public AbstractDocumentMapModel() {
		this("");
	}

	/**
	 * Overloaded constructor, added by PW, allowing loading based on documentId
	 *

	 *

	 * ignoreRequestParams and requestParamPrefix are irrelevant. We're creating
	 * objects in Java, no point querying URL parameters here
	 *
	 * @param documentId
	 *            String alternative UNID / Note ID from which to load Document
	 */
	public AbstractDocumentMapModel(String documentId) {
		// This doesn't get called immediately, so we can set properties
		// elsewhere
		try {
			initialiseTypeConversionMap();
			setDocumentId(documentId);
			if (StringUtil.isNotEmpty(getDocumentId())) {
				load(getDocumentId());
			} else {
				initNew();
			}
		} catch (final Throwable t) {
			KeyDateDatabaseUtils.handleException(t);
		}
	}

	/**
	 * Getter for unid property
	 *
	 * @return String UNID of the Document being interacted with
	 */
	public String getUnid() {
		return unid;
	}

	/**
	 * Setter for unid property
	 *
	 * @param unid
	 *            String of the Document to interact with
	 */
	public void setUnid(String unid) {
		this.unid = unid;
	}

	/**
	 * A Map of Item names and the specific Item type (e.g. READERS, AUTHORS
	 * etc). Added by PW
	 *
	 * @return Map<String, Item.Type> specific Item types, where Key = Item
	 *         name, Value = Item type
	 */
	public Map<String, Item.Type> getFieldTypeMap() {
		return fieldTypeMap;
	}

	/**
	 * Load a Map of Item names and specific Item types (e.g. READERS, AUTHORS
	 * etc). Added by PW
	 *
	 * @param fieldTypeMap
	 *            Map<String, Item.Type> specific Item types, where Key = Item
	 *            name, Value = Item type
	 */
	public void setFieldTypeMap(Map<String, Item.Type> fieldTypeMap) {
		this.fieldTypeMap = fieldTypeMap;
	}

	/**
	 * Returns Form name to use for this Document
	 *
	 * @return String Form property of this Document
	 */
	public abstract String getFormName();

	/**
	 * Returns a description for the Form used for this Document, useful for
	 * displaying in Form Tables
	 *
	 * @return String Form description
	 */
	public abstract String getFormDescription();

	/**
	 * Sets the Document as a new note
	 */
	public void initNew() {
		setNewNote(true);
	}

	/**
	 * Loads the object with settings based on the passed UNID:
	 *

	 *

	 * Whether or not it is a new Document
	 *

	 *

	 * Whether or not the Document is deleted
	 *

	 *

	 * Whether or not the Document is read only
	 *

	 *

	 * Sets wrappedDoc as a DominoDocument object
	 *

	 *

	 * Loads all fields into the object, omitting named fields, anything
	 * prefixed with "$", or with type "Error"
	 *

	 *

	 *
	 * Extended by PW to allow specific fields to be ignored and to ensure empty
	 * fields are loaded as "" (empty String), not "[]" (String version of empty
	 * Vector)
	 *
	 * @param unid
	 *            String UNID or Note ID relating to this Document (empty = new
	 *            Document)
	 */
	public void load(final String unid) {
		setUnid(unid);
		Document doc = null;
		setNewNote(true); // Default to true
		setDeleted(false); // Default to false
		setReadOnly(false); // Default to false
		try {
			if (StringUtil.isNotEmpty(unid)) {
				try {
					doc = GenericDatabaseUtils.getDocumentByNoteID_Or_UNID(unid);
					for (final Object eachItem : doc.getItems()) {
						if (eachItem instanceof Item) {
							final Item item = (Item) eachItem;
							final String itemName = item.getName();
							// Certainly not a comprehensive list of items to
							// skip
							final ArrayList<String> ignoreList = ArrayListUtil.stringToArrayList("MIME_Version");
							final String firstChar = StringUtils.left(itemName, 1);
							if (!ignoreList.contains(itemName) && !StringUtils.equals(firstChar, "$")) {
								// Item may be of type "Error"
								if (item.getTypeEx() != Type.ERRORITEM) {
									Object itemValue = null;
									try {
										if (getTypeConversionMap().containsKey(itemName)) {
											itemValue = doc.getItemValue(itemName, getTypeConversionMap().get(itemName));
										} else {
											itemValue = doc.getItemValue(itemName);
										}
									} catch (final Exception e) {
										DominoUtils.handleException(new Throwable("Error encountered getting field value for " + itemName + " on document " + unid));
									}
									setValue(itemName, itemValue);
									if (itemValue instanceof Vector) {
										if ("[]".equals(itemValue.toString())) {
											setValue(itemName, new String(""));
										} else {
											if (((Vector) itemValue).size() == 1) {
												setValue(itemName, ((Vector) itemValue).get(0));
											}
										}
									}
								}
							}
						}
					}
					if (doc.isDeleted() || !doc.isValid()) {
						setDeleted(true);
					}
					setNewNote(false);
				} catch (final Throwable t) {
					KeyDateDatabaseUtils.handleException(t);
				}
			}
		} catch (final Throwable t) {
			KeyDateDatabaseUtils.handleException(t);
		}
	}

	/**
	 * PostSave event code to run
	 *
	 * @return boolean Success / Failure in running postSave code, required to
	 *         handle onward routing
	 */
	public boolean postSave() {
		return true;
	}

	/**
	 * QuerySave event code to run
	 *
	 * @return boolean success / Failure in running querySave code, required to
	 *         handle onward routing
	 */
	public boolean querySave() {
		return true;
	}

	/**
	 * Sets Item types based on fieldTypeMap. Currently only handles READERS,
	 * AUTHORS or NAMES
	 *
	 * @param doc
	 *            Document being saved
	 * @return boolean success / failure of setting Item types
	 */
	public boolean setSpecialFieldTypes(Document doc) {
		final boolean result = false;
		try {
			if (getFieldTypeMap() != null) {
				for (final String itemName : getFieldTypeMap().keySet()) {
					if (doc.hasItem(itemName)) {
						final Item item = doc.getFirstItem(itemName);
						final Item.Type fieldType = getFieldTypeMap().get(itemName);
						if (fieldType.equals(Type.AUTHORS)) {
							item.setAuthors(true);
						} else if (fieldType.equals(Type.READERS)) {
							item.setReaders(true);
						} else if (fieldType.equals(Type.NAMES)) {
							item.setNames(true);
						}
					}
				}
			}
			return true;
		} catch (final Throwable t) {
			KeyDateDatabaseUtils.handleException(t);
		}
		return result;
	}

	/**
	 * Save of the Document, calling querySave at the start and postSave at the
	 * end
	 *
	 * @return boolean success / failure of the save
	 */
	public boolean save() {
		boolean result = false;
		if (querySave()) {
			Document doc = null;
			try {
				if (StringUtil.isEmpty(getUnid())) {
					doc = GenericDatabaseUtils.getDataDb().createDocument();
					setUnid(doc.getUniversalID());
					doc.replaceItemValue("Form", getFormName());
				} else {
					doc = GenericDatabaseUtils.getDocumentByNoteID_Or_UNID(getUnid());
				}
				for (final Entry entry : getValues().entrySet()) {
					final String itemName = entry.getKey().toString();
					doc.replaceItemValue(itemName, entry.getValue());
				}
				if (setSpecialFieldTypes(doc)) {
					if (doc.save()) {
						if (StringUtils.isNotEmpty(parentUnid)) {
							final Document parentDoc = GenericDatabaseUtils.getDocumentByNoteID_Or_UNID(parentUnid);
							doc.makeResponse(parentDoc);
						}
						result = postSave();
						setNewNote(false);
					}
				}
			} catch (final Throwable t) {
				KeyDateDatabaseUtils.handleException(t);
			}
		}
		return result;

	}

	/**
	 * Overloaded save method, allowing navigation handling to force return to a
	 * view, if required
	 *
	 * @param goToView
	 *            boolean whether or not to go to the view
	 * @return String navigationRule name (defaults are xsp-success for going to
	 *         next page, xsp-current to stay on current page)
	 */
	public String save(boolean goToView) {
		String retVal_ = "";
		try {
			if (save()) {
				if (goToView) {
					retVal_ = "xsp-success";
				} else {
					retVal_ = "xsp-current";
				}
			} else {
				Notification.show("Save failed", com.vaadin.ui.Notification.Type.ERROR_MESSAGE);
			}
		} catch (final Throwable t) {
			KeyDateDatabaseUtils.handleException(t);
		}
		return retVal_;
	}

	/**
	 * Setter for newNote
	 *
	 * @param newNote
	 *            boolean whether or not this is a new Document
	 */
	public void setNewNote(boolean newNote) {
		this.newNote = newNote;
	}

	/**
	 * Getter for newNote
	 *
	 * @return boolean whether or not this is a new Document
	 */
	public boolean isNewNote() {
		return newNote;
	}

	/**
	 * Setter for deleted. NB Not intended to actually delete the
	 * document
	 *
	 * @param deleted
	 *            boolean whether or not the Document should be considered
	 *            deleted
	 */
	public void setDeleted(boolean deleted) {
		this.deleted = deleted;
	}

	/**
	 * Getter for deleted
	 *
	 * @return boolean whether or not the document is deleted
	 */
	public boolean isDeleted() {
		return deleted;
	}

	/**
	 * Setter for readOnly
	 *
	 * @param readOnly
	 *            boolean whether or not the Document should be considered read
	 *            only
	 */
	public void setReadOnly(boolean readOnly) {
		this.readOnly = readOnly;
	}

	/**
	 * Getter for readOnly
	 *
	 * @return boolean whether or not the Document is read only
	 */
	public boolean isReadOnly() {
		return readOnly;
	}

	/**
	 * Setter for parentUnid
	 *
	 * @param parentUnid
	 *            String UNID or NoteID of the Document's parent
	 */
	public void setParentUnid(String parentUnid) {
		this.parentUnid = parentUnid;
	}

	/**
	 * Getter for parentUnid
	 *
	 * @return String UNID or NoteID of the Document's parent
	 */
	public String getParentUnid() {
		return parentUnid;
	}

	/**
	 * Setter for documentId
	 *
	 * @param documentId
	 *            String UNID or NoteID for the Document
	 */
	public void setDocumentId(String documentId) {
		this.documentId = documentId;
	}

	/**
	 * Getter for documentId
	 *
	 * @return String UNID or NoteID for the Document
	 */
	public String getDocumentId() {
		return documentId;
	}

	/**
	 * Getter for typeConversionMap, to facilitate type conversion of Items.
	 * When loading item values into this object, if an Item name is found in
	 * this map, the value will be cast to the Class defined by this map for
	 * that Item. E.g. "date",Date.class will convert the "date" field to a Java
	 * Date.
	 *
	 * @return HashMap where the key is a String and the value is a Class
	 */
	public HashMap<String, Class<?>> getTypeConversionMap() {
		return typeConversionMap;
	}

	/**
	 * Setter for typeConversionMap, to facilitate type conversion of Items.
	 * E.g. where an item is a DateTime, that cannot be serialized, so will
	 * cause us problems. So an element would be added to the map to map the
	 * Item name to Date.class
	 *
	 * @param typeConversionMap
	 *            HashMap where the key is a String and the value is a Class
	 */
	public void setTypeConversionMap(HashMap<String, Class<?>> typeConversionMap) {
		this.typeConversionMap = typeConversionMap;
	}

	/**
	 * Initialises the map of fields with specific class types (i.e. types not
	 * automatically converted to Java objects
	 */
	public void initialiseTypeConversionMap() {
		setTypeConversionMap(new HashMap<String, Class<?>>());
	}

}


text:
Classes in this namespace implement the low level functions of
Config.


text:
import React from 'react'
import { render } from '../TestUtils'
import CellMeasurer from './CellMeasurer'
import CellSizeCache from './defaultCellSizeCache'

const HEIGHTS = [75, 50, 125, 100, 150]
const WIDTHS = [125, 50, 200, 175, 100]

function createCellRenderer () {
  const cellRendererParams = []
  const cellRenderer = (params) => {
    cellRendererParams.push(params)
    return (

        cell

    )
  }

  return {
    cellRenderer,
    cellRendererParams
  }
}

function renderHelper ({
  cellRenderer,
  cellSizeCache,
  columnCount = 1,
  columnWidth,
  rowCount = 1,
  rowHeight
} = {}) {
  let params
  render(

      <CellMeasurer
        cellRenderer={cellRenderer}
        cellSizeCache={cellSizeCache}
        columnCount={columnCount}
        height={rowHeight}
        rowCount={rowCount}
        width={columnWidth}
      >
        {(paramsToSave) => {
          params = paramsToSave

          return
foo

        }}
      </CellMeasurer>

  )

  return params
}

describe('CellMeasurer', () => {
  it('should calculate the height of a single-column row', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth,
      getRowHeight
    } = renderHelper({
      cellRenderer,
      columnWidth: 100
    })
    expect(cellRendererParams).toEqual([])
    expect(getRowHeight({ index: 0 })).toEqual(75)
    expect(cellRendererParams).toEqual([{ columnIndex: 0, index: 0, rowIndex: 0 }])
    expect(getColumnWidth({ index: 0 })).toEqual(100)

    // For some reason this explicit unmount is necessary.
    // Without it, Jasmine's :afterEach doesn't pick up and unmount the component correctly.
    render.unmount()
  })

  it('should calculate the width of a single-row column', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth,
      getRowHeight
    } = renderHelper({
      cellRenderer,
      rowHeight: 50
    })
    expect(cellRendererParams).toEqual([])
    expect(getColumnWidth({ index: 0 })).toEqual(125)
    expect(cellRendererParams).toEqual([{ columnIndex: 0, index: 0, rowIndex: 0 }])
    expect(getRowHeight({ index: 0 })).toEqual(50)
  })

  it('should calculate the height of a multi-column row based on the tallest column-cell', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth,
      getRowHeight
    } = renderHelper({
      cellRenderer,
      columnCount: 5,
      columnWidth: 100
    })
    expect(cellRendererParams.length).toEqual(0)
    expect(getRowHeight({ index: 0 })).toEqual(150)
    expect(cellRendererParams.length).toEqual(5)
    expect(getColumnWidth({ index: 0 })).toEqual(100)
  })

  it('should calculate the width of a multi-row column based on the widest row-cell', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth,
      getRowHeight
    } = renderHelper({
      cellRenderer,
      rowCount: 5,
      rowHeight: 50
    })
    expect(cellRendererParams.length).toEqual(0)
    expect(getColumnWidth({ index: 0 })).toEqual(200)
    expect(cellRendererParams.length).toEqual(5)
    expect(getRowHeight({ index: 0 })).toEqual(50)
  })

  it('should support :rowRenderer via :index param for easier List integration', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const { getColumnWidth } = renderHelper({
      cellRenderer,
      rowCount: 5,
      rowHeight: 50
    })
    getColumnWidth({ index: 0 })
    expect(cellRendererParams.length).toEqual(5)
    for (let i = 0; i < 5; i++) {
      expect(cellRendererParams[i].index).toEqual(i)
    }
  })

  it('should cache cell measurements once a cell has been rendered', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getRowHeight
    } = renderHelper({ cellRenderer })

    expect(cellRendererParams).toEqual([])
    getRowHeight({ index: 0 })
    getRowHeight({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 }
    ])

    getRowHeight({ index: 0 })
    getRowHeight({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 }
    ])
  })

  it('should reset all cached measurements when resetMeasurements() is called', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getRowHeight,
      resetMeasurements
    } = renderHelper({ cellRenderer })

    expect(cellRendererParams).toEqual([])
    getRowHeight({ index: 0 })
    getRowHeight({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 }
    ])

    resetMeasurements()

    getRowHeight({ index: 0 })
    getRowHeight({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 },
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 }
    ])
  })

  it('should reset a specific cached row measurement when resetMeasurementForColumn() is called', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth,
      resetMeasurementForColumn
    } = renderHelper({ cellRenderer })

    expect(cellRendererParams).toEqual([])
    getColumnWidth({ index: 0 })
    getColumnWidth({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 1, index: 0, rowIndex: 0 }
    ])

    resetMeasurementForColumn(0)

    getColumnWidth({ index: 0 })
    getColumnWidth({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 1, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 0, rowIndex: 0 }
    ])
  })

  it('should reset a specific cached row measurement when resetMeasurementForRow() is called', () => {
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getRowHeight,
      resetMeasurementForRow
    } = renderHelper({ cellRenderer })

    expect(cellRendererParams).toEqual([])
    getRowHeight({ index: 0 })
    getRowHeight({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 }
    ])

    resetMeasurementForRow(0)

    getRowHeight({ index: 0 })
    getRowHeight({ index: 1 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 },
      { columnIndex: 0, index: 1, rowIndex: 1 },
      { columnIndex: 0, index: 0, rowIndex: 0 }
    ])
  })

  it('should allow a custom caching strategy to be specified', () => {
    const customCellSizeCache = new CellSizeCache()
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth,
      getRowHeight
    } = renderHelper({
      cellRenderer,
      cellSizeCache: customCellSizeCache,
      columnCount: 5,
      columnWidth: 200,
      rowCount: 2,
      rowHeight: 50
    })

    expect(customCellSizeCache.getColumnWidth(0)).toEqual(undefined)
    expect(cellRendererParams.length).toEqual(0)
    expect(getColumnWidth({ index: 0 })).toEqual(200)
    expect(customCellSizeCache.getColumnWidth(0)).toEqual(200)
    expect(cellRendererParams.length).toEqual(2)
    expect(getColumnWidth({ index: 0 })).toEqual(200)
    expect(cellRendererParams.length).toEqual(2)

    expect(customCellSizeCache.getRowHeight(0)).toEqual(undefined)
    expect(cellRendererParams.length).toEqual(2)
    expect(getRowHeight({ index: 0 })).toEqual(50)
    expect(customCellSizeCache.getRowHeight(0)).toEqual(50)
    expect(cellRendererParams.length).toEqual(7)
    expect(getRowHeight({ index: 0 })).toEqual(50)
    expect(cellRendererParams.length).toEqual(7)
  })

  it('should support changing the custom caching strategy after initialization', () => {
    const customCellSizeCacheA = new CellSizeCache()
    const customCellSizeCacheB = new CellSizeCache()
    const { cellRenderer } = createCellRenderer()
    const { getColumnWidth: getColumnWidthA } = renderHelper({
      cellRenderer,
      cellSizeCache: customCellSizeCacheA,
      columnCount: 5,
      columnWidth: 200
    })
    expect(customCellSizeCacheA.getColumnWidth(0)).toEqual(undefined)
    expect(getColumnWidthA({ index: 0 })).toEqual(200)
    expect(customCellSizeCacheA.getColumnWidth(0)).toEqual(200)

    const { getColumnWidth: getColumnWidthB } = renderHelper({
      cellRenderer,
      cellSizeCache: customCellSizeCacheA,
      columnCount: 5,
      columnWidth: 100
    })
    expect(customCellSizeCacheA.getColumnWidth(0)).toEqual(200)
    expect(getColumnWidthB({ index: 0 })).toEqual(200)
    expect(customCellSizeCacheA.getColumnWidth(0)).toEqual(200)

    const { getColumnWidth: getColumnWidthC } = renderHelper({
      cellRenderer,
      cellSizeCache: customCellSizeCacheB,
      columnCount: 5,
      columnWidth: 50
    })
    expect(customCellSizeCacheB.getColumnWidth(0)).toEqual(undefined)
    expect(getColumnWidthC({ index: 0 })).toEqual(50)
    expect(customCellSizeCacheB.getColumnWidth(0)).toEqual(50)
  })

  it('should calculate row height just once when using the alternative uniform-size cell size cache', () => {
    const cellSizeCache = new CellSizeCache({
      uniformRowHeight: true
    })
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getRowHeight
    } = renderHelper({
      cellRenderer,
      cellSizeCache,
      rowCount: 5
    })

    expect(cellRendererParams).toEqual([])
    const height1 = getRowHeight({ index: 0 })
    const height2 = getRowHeight({ index: 1 })
    const height3 = getRowHeight({ index: 0 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 }
    ])

    const expectedHeight = HEIGHTS[0]

    expect(height1).toEqual(expectedHeight)
    expect(height2).toEqual(expectedHeight)
    expect(height3).toEqual(expectedHeight)
  })

  it('should calculate column-width just once when using the alternative uniform-size cell size cache', () => {
    const cellSizeCache = new CellSizeCache({
      uniformColumnWidth: true
    })
    const {
      cellRenderer,
      cellRendererParams
    } = createCellRenderer()
    const {
      getColumnWidth
    } = renderHelper({
      cellRenderer,
      cellSizeCache,
      columnCount: 5
    })

    expect(cellRendererParams).toEqual([])
    const width1 = getColumnWidth({ index: 0 })
    const width2 = getColumnWidth({ index: 1 })
    const width3 = getColumnWidth({ index: 0 })
    expect(cellRendererParams).toEqual([
      { columnIndex: 0, index: 0, rowIndex: 0 }
    ])

    const expectedWidth = WIDTHS[0]

    expect(width1).toEqual(expectedWidth)
    expect(width2).toEqual(expectedWidth)
    expect(width3).toEqual(expectedWidth)
  })
})


text:
/*
 * stack.h
 *
 *  Created on: 9 July 2015
 *      Author: Nick Brown
 */

#ifndef HOST_STACK_H_
#define HOST_STACK_H_

#define INITIAL_STACK_SIZE 10

struct stack_t {
    int size, width;
    char * type;
    void **data;
};

struct identifier_exp {
	char * identifier;
	struct memorycontainer* exp;
};

#include "byteassembler.h"

struct stack_t* getNewStack(void);
void clearStack(struct stack_t*);
void initStack(struct stack_t*);
int getStackSize(struct stack_t*);
int pop(struct stack_t*);
void push(struct stack_t*, int);
char* popIdentifier(struct stack_t*);
void pushIdentifier(struct stack_t*, char*);
int peek(struct stack_t*);
int getTopType(struct stack_t*);
struct memorycontainer* popExpression(struct stack_t*);
void pushExpression(struct stack_t*, struct memorycontainer*);
void pushIdentifierAssgnExpression(struct stack_t*, char*, struct memorycontainer*);
struct identifier_exp* popExpressionIdentifier(struct stack_t*);
struct memorycontainer* getExpressionAt(struct stack_t*, int);
struct identifier_exp* getExpressionIdentifierAt(struct stack_t*, int);
char* getIdentifierAt(struct stack_t*, int);
int getTypeAt(struct stack_t*, int);

#endif /* HOST_STACK_H_ */


text:
package org.kuali.rice.krad.datadictionary.validation.fieldlevel;

import org.junit.Test;
import org.kuali.rice.kns.datadictionary.validation.fieldlevel.YearValidationPattern;
import org.kuali.rice.krad.test.KRADTestCase;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * YearValidationPatternTest tests {@link YearValidationPattern}
 *
 *
Valid year values should match

 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class YearValidationPatternTest extends KRADTestCase {
    YearValidationPattern pattern;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        pattern = new YearValidationPattern();
    }

    @Test public final void testMatches_valid1() {
        assertTrue(pattern.matches("1901"));
    }

    @Test public final void testMatches_valid2() {
        assertTrue(pattern.matches("1991"));
    }

    @Test public final void testMatches_valid3() {
        assertTrue(pattern.matches("2005"));
    }

    @Test public final void testMatches_valid4() {
        assertTrue(pattern.matches("1837"));
    }

    @Test public final void testMatches_invalid1() {
        assertFalse(pattern.matches("992"));
    }

    @Test public final void testMatches_invalid2() {
        assertFalse(pattern.matches("1514"));
    }

    @Test public final void testMatches_invalid3() {
        assertFalse(pattern.matches("3103"));
    }

    @Test public final void testMatches_invalid4() {
        assertFalse(pattern.matches("10001"));
    }
}


text:
module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var util = require('../../util'),
		async = require('async'),
		ormUtil = require('./util')(sails),
		Modules = require('../../moduleloader'),
		Waterline = require('waterline'),
		loadModules = require('./modules')(sails);

	/**
	 * Expose Hook definition
	 */

	return {

		// Always ready-- doesn't need to bind any routes
		ready: true,

		initialize: function(cb) {
			async.auto({
				modules: loadModules,
				start: ['modules', this.start]
			}, cb);
		},

		/**
		 * Start the ORM by instantiating Waterline Collections
		 */

		start: function(cb) {
			sails.log.verbose('Starting ORM...');

			// "Resolve" Adapters
			// Ensures that each model has somthing set for the adapter
			util.each(sails.models, function(model, identity) {
				model.adapter = ormUtil.resolveAdapter(model);
			});

			// Load all external adapters used in models
			util.each(sails.models, function(model, identity) {
				ormUtil.loadAdapters(identity);
			});

			// Build Config for each adapter
			util.each(sails.adapters, function(adapter, identity) {
				ormUtil.buildAdapterConfig(identity);
			});

			// Loop through models and instantiate a Waterline Collection
			async.each(Object.keys(sails.models), loadCollection, function(err) {
				if (err) return cb(err);
				cb();
			});

		},

		/**
		 * Stop the ORM by removing all references to instantiated models
		 */

		stop: function() {
			sails.log.verbose('Stopping ORM...');

			// delete all references to sails.models and their global
			Object.keys(sails.models).forEach(function(model) {
				if (global[model.globalId]) {
					delete global[model.globalId];
				}

				delete sails.models[model];
			});
		},

		/**
		 * Reload the ORM by removing all models and reloading them
		 * then reinstantiate the Waterline Collections.
		 */

		restart: function(cb) {
			sails.log.verbose('Restarting ORM...');

			var self = this;

			// Stop the ORM
			this.stop();

			// reload sails.models
			modelsLoader(function() {

				// Start the ORM
				self.start(cb);

			});
		}
	};

	/**
	 * Instantiate a new Waterline Collection from the Sails Model
	 */

	function loadCollection(model, cb) {

		// Determine if model is schema or schemaless
		var modelAdapters = sails.models[model].adapter;

		// Check if main model adapter config has a default schema setting
		var adapter = sails.adapters[modelAdapters[0]];
		var defaultSchema = adapter.config && adapter.config.hasOwnProperty('schema');

		// Check if the model is overriding the schema setting
		var overrideSchema = typeof sails.models[model].schema !== 'undefined';

		// Set the schema value if there is a default and nothing is overriding it
		if(defaultSchema && !overrideSchema) {
			sails.models[model].schema = adapter.config && adapter.config.schema;
		}

		// Mixin local model defaults to the adapters passed into the model
		var adapters = ormUtil.overrideConfig(model);

		// Wrap model in Waterline.Collection.extend
		var Model = Waterline.Collection.extend(sails.models[model]);

		new Model({

			// Pass in a default tableName, can be overwritten in a model definition
			tableName: model,

			// Pass in all the adapters Sails knows about
			adapters: adapters

		}, function(err, collection) {
			if (err) return cb(err);

			// Set Model to instantiated Collection
			sails.models[model] = collection;

			// Globalize Model if Enabled
			if (sails.config.globals.models) {
				var globalName = sails.models[model].globalId || sails.models[model].identity;
				global[globalName] = collection;
			}

			cb();
		});
	}

};


text:
let detectSVG = require('./detect-svg');
/**
 * URL encode our SVG
 * @param String svgURL - string of background-image value
 */
module.exports = {
    encodeSVG(decl) {
        // Default value is what we've passed in
        // If the regex is successful, this will be overidden
        let svgURL = decl.value;
        let newValue = svgURL;
        let matchSVG = detectSVG.getSVGElement(svgURL);
        if (matchSVG) {
            let encodedURL = matchSVG.svg;
            // Ensure that the <svg /></svg> segment of the URL is not already encoded
            // If not, encode it
            if (!matchSVG.svgAlreadyEncoded) {
                encodedURL = module.exports.encodeOptimizedSVGDataUri(matchSVG.svg);
            }
            let shorthandRules = matchSVG.shorthandRules;
            // Place the encoded URL back into the value structure
            newValue = `url("data:image/svg+xml,${encodedURL}")${shorthandRules}`;
        // If our Regex doesn't match, throw an error
        } else {
            throw decl.error('Background SVG syntax error - please correct your syntax and try again.', {plugin: 'postcss-encode-background-svgs'});
        }
        return newValue;
    },

    /**
     * Correctly optimise SVG
     * Taken from: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
     * @author Taylor Hunt
     * @param  String svgString - SVG unencoded
     * @return String
     */
    encodeOptimizedSVGDataUri(svgString) {
        var uriPayload = encodeURIComponent(svgString) // encode URL-unsafe characters
            .replace(/%0A/g, '') // remove newlines
            .replace(/%20/g, ' ') // put spaces back in
            .replace(/%3D/g, '=') // ditto equals signs
            .replace(/%3A/g, ':') // ditto colons
            .replace(/%2F/g, '/') // ditto slashes
            .replace(/%22/g, '\''); // replace quotes with apostrophes (may break certain SVGs)
        return uriPayload;
    }
};


text:
package almond.protocol

import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec
import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker

object Shutdown {

  final case class Request(restart: Boolean)
  final case class Reply(restart: Boolean)

  def requestType = MessageType[Request]("shutdown_request")
  def replyType = MessageType[Reply]("shutdown_reply")

  implicit val requestCodec: JsonValueCodec[Request] =
    JsonCodecMaker.make
  implicit val replyCodec: JsonValueCodec[Reply] =
    JsonCodecMaker.make

}


text:
module SvgExport
  class SvgController < ApplicationController
    skip_before_action :verify_authenticity_token, raise: false

    def create
      if Engine.batik_path.blank?
        raise ArgumentError, "Set SvgExport::Engine.batik_path = '...' to the correct path of the batik-rasterizer"
      end
      wrapper = CommandWrapper.new(params, base_url: request.referer)
      begin
        file = wrapper.call
      rescue SvgExport::Error => e
        render plain: "Unable to export image;\n #{e}", status: :unprocessable_entity
        return
      end
      send_file file, type: wrapper.type, filename: wrapper.filename, disposition: 'attachment', stream: false
    end
  end
end


text:
const WiseQuotes = require('./src/wise-quotes');
const DB = {
  file: '../db/sample.sqlite3',
  memory: ':memory:',
};

const wq = new WiseQuotes({
  database: DB.memory,
});

(async function () {
  // initialize.
  let result;
  result = await wq.migration();
  console.log(result);
  result = await wq.feed('feed-sample.json');
  console.log(result);

  // status.
  let count = await wq.count;
  console.log(`count: ${count}`);
  console.log(await wq.random);

  // all.
  console.log(await wq.all());
})();


text:
This article covers general [known issues](../Readme.md#knownissues) related to Apache Cordova or Ripple.

----------
**Cordova 5.x.x:** See [Cordova 5.x.x known issues](known-issues-cordova5.md) for details on Cordova and Ripple related issues that are specific to Cordova 5.0.0 and up.

----------
**Plugin with variables not working:** Due to a Cordova issue with Cordova 4.3.0 and 4.3.1, you can run into problems with plugin variables in Cordova < 5.0.0. Plugin variable information is lost if you install the "plugin" before the "platform" which can happen depending on your workflow. They do, however, function in Cordova 5.1.1 which you can use with VS 2015. Follow these steps to use a plugin with variables:

 1. Remove the plugins with the variables via the config designer.

 2. Update to Cordova 5.1.1 via the config designer (Platforms > Cordova CLI)

 3. Re-add your plugin via "Plugins" tab in the config.xml designer

----------
**TypeError: Request path contains unescaped characters:** When building or installing a plugin you may encounter this error if you are using a proxy with certain versions of Node.js and Cordova after a "npm http GET". This is a Cordova issue and the simplest workaround is to downgrade Node.js to 0.10.29. This will be resolved in a future version of Cordova. See [tips and workarounds](../tips-and-workarounds/general/README.md#cordovaproxy) for additional details.

----------
**Ripple - Camera plugin does not work when using DATA_URL:** When using the Camera plugin with Ripple and the DATA_URL option, a file reference is returned instead.

----------
**Ripple - I Haz Cheezburger?!?! error:** This error is Ripple's way of telling you that the Cordova plugin you attempted to use is not supported in the simulator. You can, however, enter data to simulate a success or failure callback to your code from this dialog.

----------
## More Information
* [Read up on additional known issues, tips, tricks, and tutorials](../Readme.md)
* [Download samples from our Cordova Samples repository](http://github.com/Microsoft/cordova-samples)
* [Follow us on Twitter](https://twitter.com/VSCordovaTools)
* [Visit our site http://aka.ms/cordova](http://aka.ms/cordova)
* [Read MSDN docs on using Visual Studio Tools for Apache Cordova](http://go.microsoft.com/fwlink/?LinkID=533794)
* [Ask for help on StackOverflow](http://stackoverflow.com/questions/tagged/visual-studio-cordova)
* [Email us your questions](mailto://multidevicehybridapp@microsoft.com)


text:
struct bad_global_struct1;
struct bad_global_struct2 {};
int bad_global = 0;
void bad_global_function() {}

namespace
{
    struct bad_anonymous_struct1;
    struct bad_anonymous_struct2 {};
    int bad_anonymous_global = 0;
    void bad_anonymous_function() {}
}

namespace csatr
{
    struct bad_csatr_struct1;
    struct bad_csatr_struct2 {};
    int bad_csatr_variable = 0;
    void bad_csatr_function() {}

    namespace
    {
        struct bad_csatr_anonymous_struct1;
        struct bad_csatr_anonymous_struct2 {};
        int bad_csatr_anonymous_variable = 0;
        void bad_csatr_anonymous_function() {}
    }
}

namespace top
{
    namespace csatr
    {
        struct bad_top_csatr_struct1;
        struct bad_top_csatr_struct2 {};
        int bad_top_csatr_variable = 0;
        void bad_top_csatr_function() {}

        namespace
        {
            struct bad_top_csatr_anonymous_struct1;
            struct bad_top_csatr_anonymous_struct2 {};
            int bad_top_csatr_anonymous_variable = 0;
            void bad_top_csatr_anonymous_function() {}
        }
    }
}

namespace bde_verify
{
    namespace csatr
    {
        struct good_source_struct1;
        struct good_source_struct2 {};
        int good_source_global = 0;
        void good_source_function() {}

        namespace
        {
            struct good_source_anonymous_struct1;
            struct good_source_anonymous_struct2 {};
            int good_source_anonymous_global = 0;
            void good_source_anonymous_function() {}
        }
    }
}

int main()
{
}

// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------


text:
define(["lib-build/css!./Desktop",
		"../../utils/HeaderHelper",
		"../../builder/InlineFieldEdit",
		"../../utils/CommonHelper",
		"dojo/has",
		"dojo/topic"],
	function(
		viewCss,
		HeaderHelper,
		InlineFieldEdit,
		CommonHelper,
		has,
		topic
	){
		return function Desktop(container, isInBuilder)
		{
			var _this = this;

			this.init = function(hide, title, subtitle, headerCfg, colors, displaySwitchBuilderButton, defaultToCompact)
			{
				setColor(colors);

				if (hide) {
					container.addClass('hideDesktop');
					return;
				}

				// Desktop builder
				if( isInBuilder ) {
					container.addClass('isBuilder');
					title =  "
" + (title || i18n.commonCore.inlineFieldEdit.editMe) + "
";
					title += "

";
					title += "<textarea rows='1' class='text_edit_input form-control' type='text' spellcheck='true'></textarea>";

					subtitle =  "" + (subtitle || i18n.commonCore.inlineFieldEdit.editMe) + "";
					subtitle += "

";
					subtitle += "<textarea rows='3' class='text_edit_input form-control' type='text' spellcheck='true'></textarea>";
				}

				container.find('.title').html(title);
				container.find('.subtitle').html(subtitle);

				// Desktop builder
				if( isInBuilder )
					new InlineFieldEdit(container, editFieldsEnterEvent, editFieldsExitEvent);

				if( ! isInBuilder && ! subtitle ) {
					var isCompact = headerCfg.compactSize === undefined ? defaultToCompact : headerCfg.compactSize;
					if ( ! isCompact ) {
						container.find('.title').css({
							paddingTop: 30,
							height: 90
						});
						container.find('.subtitle').css("height", 32).attr("tabindex", "-1");
					}
				}

				if ( displaySwitchBuilderButton ) {
					container.find(".switchBuilder")
						.html('' + i18n.viewer.headerFromCommon.builderButton)
						.click(CommonHelper.switchToBuilder)
						.show();
				}

				setHeader(headerCfg, defaultToCompact);
			};

			this.resize = function(widthViewport)
			{
				if ( ! widthViewport )
					widthViewport = $(document).width();

				var rightAreaWidth = Math.max(container.find(".logoImg").outerWidth() + 50, container.find(".rightArea").outerWidth() + 20);
				container.find(".textArea").width(widthViewport - rightAreaWidth - 15);
			};

			this.update = function(headerCfg, colors, defaultToCompact)
			{
				setColor(colors);
				setHeader(headerCfg, defaultToCompact);
			};

			this.getTitle = function()
			{
				if ( isInBuilder )
					return container.find('.title .text_edit_label').html();
				else
					return container.find('.title').html();
			};

			this.getSubtitle = function()
			{
				if ( isInBuilder )
					return container.find('.subtitle .text_edit_label').html();
				else
					return container.find('.subtitle').html();
			};

			this.setTitleAndSubtitle = function(title, subtitle)
			{
				var defaultText = isInBuilder ? i18n.commonCore.inlineFieldEdit.editMe : '';

				container.find('.title' + (isInBuilder ? ' .text_edit_label' : '')).html(title || defaultText);
				container.find('.subtitle' + (isInBuilder ? ' .text_edit_label' : '')).html(subtitle || defaultText);
			};

			this.toggleSocialBtnAppSharing = function(disable)
			{
				HeaderHelper.toggleSocialBtnAppSharing(container, disable);
			};

			/*
			 * 508 tab navigation
			 */

			this.focus = function(p)
			{
				if ( ! p || p.area == "social" ) {
					$("#headerDesktop .shareIcon").attr("tabindex", "0");

					if ( $("#headerDesktop .linkContainer a").length )
						$("#headerDesktop .linkContainer a").attr("tabindex", "0")[0].focus();
					else if ( $("#headerDesktop .linkContainer").length )
						$("#headerDesktop .linkContainer").attr("tabindex", "0")[0].focus();
					else if ( $("#headerDesktop .shareIcon:visible").length )
						$("#headerDesktop .shareIcon")[0].focus();
					else
						focusTitleOrSubtitle();
				}
				else {
					focusTitleOrSubtitle();
				}
			};

			function focusTitleOrSubtitle()
			{
				if ( $("#headerDesktop .subtitle:visible").length )
					$("#headerDesktop .subtitle")[0].focus();
				else
					$("#headerDesktop .title")[0].focus();
			}

			/*
			 * Styling
			 */

			function setColor(colors)
			{
				container.css("background-color", colors.header);
				container.find(".textArea").css("color", colors.headerTitle);
				container.find(".rightArea").css("color", colors.headerText);
			}

			function setHeader(headerCfg, defaultToCompact)
			{
				var isCompact = headerCfg.compactSize === undefined ? defaultToCompact : headerCfg.compactSize;

				HeaderHelper.setLogo(container, headerCfg, _this.resize);
				HeaderHelper.setLink(container, headerCfg);
				HeaderHelper.setSocial(container, headerCfg);
				HeaderHelper.initEvents(container, "bottom");

				container.toggleClass('compact', isCompact);

				// Prevent logo and social links to be properly aligned
				if ( isCompact ) {
					container.find(".rightArea").hide();
					setTimeout(function(){
						container.find(".rightArea").show();
					}, 0);
				}
			}

			/*
			 * Builder
			 */

			function editFieldsEnterEvent()
			{
				//
			}

			function editFieldsExitEvent(src, value)
			{
				setTimeout(function(){
					topic.publish("HEADER_EDITED", {
						src: $(src).attr("class").split(' ')[0],
						value: value
					});
					// TODO only if the value has changed
					$(src).removeClass("error");
				}, has("ios") || has("ie") >= 10 ? 700 : 0);

				app.builder.hideSaveConfirmation();
			}

			this.setTitleError = function()
			{
				container.find(".title").addClass("error");
			};

			this.initLocalization = function()
			{

			};
		};
	}
);


text:
<?php

namespace Addons\Photo\Model;
use Think\Model;

/**
 * Photo模型
 */
class PhotoModel extends Model{

}


text:
Sponsors & Backers

Vue Material do not run under the umbrella of any company or something like that. Is an independent project created by Marcos Moura on spare time that became one of the most used UI Libraries for Vue.js. The development is active and we are working hard to release great things for you.

If you think that this project helped you or your company in some way, you can consider become a backer/sponsor on Patreon:

Sponsors

Yatima Kagurazaka

Backers

* Ivo Benner
* Nathanael Björkgård


text:
use crate::block_number::BlockTag;
#[cfg(test)]
use crate::block_number::Tag;
use crate::log::Log;
use cita_types::traits::BloomTools;
use cita_types::{Address, Bloom, H256};
use jsonrpc_types::rpc_types::{Filter as RpcFilter, FilterAddress, Topic, VariadicValue};

/// Address Filter.
#[derive(Debug, PartialEq, Clone)]
pub struct AddressFilter {
    addresses: Option<Vec<Address>>,
}

impl AddressFilter {
    pub fn new(addresses: Option<Vec<Address>>) -> Self {
        AddressFilter { addresses }
    }

    pub fn blooms(&self) -> Vec<Bloom> {
        match self.addresses {
            Some(ref addresses) if !addresses.is_empty() => addresses
                .iter()
                .map(|ref address| Bloom::from_raw(address))
                .collect(),
            _ => vec![Bloom::default()],
        }
    }

    pub fn matches(&self, log: &Log) -> bool {
        match self.addresses {
            Some(ref addresses) if !addresses.is_empty() => {
                addresses.iter().any(|address| &log.address == address)
            }
            _ => true,
        }
    }
}

impl From<Option<FilterAddress>> for AddressFilter {
    fn from(addresses: Option<FilterAddress>) -> AddressFilter {
        let addresses = addresses.and_then(|address| match address {
            VariadicValue::Null => None,
            VariadicValue::Single(addr) => Some(vec![addr.into()]),
            VariadicValue::Multiple(addr) => Some(addr.into_iter().map(Into::into).collect()),
        });

        AddressFilter { addresses }
    }
}

impl Default for AddressFilter {
    fn default() -> Self {
        AddressFilter { addresses: None }
    }
}

/// Topic Filter.
#[derive(Debug, PartialEq)]
pub struct TopicFilter {
    topics: Vec<Option<Vec<H256>>>,
}

impl TopicFilter {
    pub fn new(topics: Vec<Option<Vec<H256>>>) -> Self {
        TopicFilter { topics }
    }

    pub fn zip_blooms(&self, blooms: Vec<Bloom>) -> Vec<Bloom> {
        self.topics.iter().fold(blooms, |bs, topic| match *topic {
            None => bs,
            Some(ref topics) => bs
                .into_iter()
                .flat_map(|bloom| {
                    topics
                        .iter()
                        .map(|topic| {
                            let mut bloom = bloom;
                            bloom.accrue_raw(topic);
                            bloom
                        })
                        .collect::<Vec<Bloom>>()
                })
                .collect(),
        })
    }

    pub fn matches(&self, log: &Log) -> bool {
        self.topics
            .iter()
            .enumerate()
            .all(|(index, topic)| match *topic {
                Some(ref topics) if !topics.is_empty() => topics
                    .iter()
                    .any(|topic| log.topics.get(index) == Some(topic)),
                _ => true,
            })
    }
}

impl From<Option<Vec<Topic>>> for TopicFilter {
    fn from(topics: Option<Vec<Topic>>) -> TopicFilter {
        let mut iter = topics
            .map_or_else(Vec::new, |topics| {
                topics
                    .into_iter()
                    .take(4)
                    .map(|topic| match topic {
                        VariadicValue::Null => None,
                        VariadicValue::Single(t) => Some(vec![t.into()]),
                        VariadicValue::Multiple(t) => Some(t.into_iter().map(Into::into).collect()),
                    })
                    .collect()
            })
            .into_iter();

        let topics = vec![
            iter.next().unwrap_or(None),
            iter.next().unwrap_or(None),
            iter.next().unwrap_or(None),
            iter.next().unwrap_or(None),
        ];

        TopicFilter { topics }
    }
}

impl Clone for TopicFilter {
    fn clone(&self) -> Self {
        let mut topics = [None, None, None, None];
        topics[..4].clone_from_slice(&self.topics[..4]);

        TopicFilter {
            topics: topics.to_vec(),
        }
    }
}

impl Default for TopicFilter {
    fn default() -> Self {
        let topics = vec![None, None, None, None];

        TopicFilter { topics }
    }
}

/// All filter.
#[derive(Debug, PartialEq)]
pub struct Filter {
    pub from_block: BlockTag,
    pub to_block: BlockTag,
    pub addresses: AddressFilter,
    pub topics: TopicFilter,
    pub limit: Option<usize>,
}

impl Filter {
    /// Zip blooms with address and topic.
    pub fn zip_blooms(&self) -> Vec<Bloom> {
        self.topics.zip_blooms(self.addresses.blooms())
    }

    /// Check the given log entry matches address or topic.
    pub fn matches(&self, log: &Log) -> bool {
        self.addresses.matches(log) && self.topics.matches(log)
    }

    // For test
    #[cfg(test)]
    pub fn new_with_address_and_topic(addresses: AddressFilter, topics: TopicFilter) -> Self {
        Filter {
            from_block: BlockTag::Tag(Tag::Earliest),
            to_block: BlockTag::Tag(Tag::Latest),
            addresses,
            topics,
            limit: None,
        }
    }
}

impl From<RpcFilter> for Filter {
    fn from(v: RpcFilter) -> Filter {
        Filter {
            from_block: v.from_block.into(),
            to_block: v.to_block.into(),
            addresses: v.address.into(),
            topics: v.topics.into(),
            limit: v.limit,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::filter::{AddressFilter, Filter, TopicFilter};
    use crate::log::Log;
    use cita_types::{Address, Bloom, H256};

    #[test]
    fn test_zip_blooms_none() {
        let none_filter =
            Filter::new_with_address_and_topic(Default::default(), Default::default());

        let blooms = none_filter.zip_blooms();
        assert_eq!(blooms.len(), 1);
        assert!(blooms[0].is_zero())
    }

    #[test]
    fn test_zip_blooms_single_address_and_single_topic() {
        let topics = vec![Some(vec![H256::zero()]), None, None, None];
        let addresses = Some(vec![Address::default()]);

        let filter = Filter::new_with_address_and_topic(
            AddressFilter::new(addresses),
            TopicFilter::new(topics),
        );

        let zip_blooms = filter.zip_blooms();
        let blooms: Vec<Bloom> = vec![
            "0000000000000000008000000000000000000000000000000000000000000000
             0000000000000000000000000000000200000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000002000000000000000000080000000000000000000000000000000000
             0000000000000000000000000000000100000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000002000
             0000000000000000000000000000000000000000000000000000000000000000"
                .into(),
        ];
        assert_eq!(zip_blooms, blooms);
    }

    #[test]
    fn test_zip_bloom_single_address_and_mul_topics() {
        let topics = vec![
            Some(vec![H256::zero()]),
            Some(vec![H256::zero()]),
            Some(vec![H256::zero()]),
            Some(vec![H256::zero()]),
        ];
        let addresses = Some(vec![Address::default()]);

        let filter = Filter::new_with_address_and_topic(
            AddressFilter::new(addresses),
            TopicFilter::new(topics),
        );

        let zip_blooms = filter.zip_blooms();
        let blooms: Vec<Bloom> = vec![
            "0000000000000000008000000000000000000000000000000000000000000000
             0000000000000000000000000000000200000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000002000000000000000000080000000000000000000000000000000000
             0000000000000000000000000000000100000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000002000
             0000000000000000000000000000000000000000000000000000000000000000"
                .into(),
        ];
        assert_eq!(zip_blooms, blooms);
    }

    #[test]
    fn test_zip_blooms_mul_addresses_and_mul_topics() {
        let topics = vec![
            Some(vec![H256::zero(), H256::zero()]),
            Some(vec![H256::zero()]),
            Some(vec![H256::zero()]),
            Some(vec![H256::zero()]),
        ];
        let addresses = Some(vec![Address::default(), Address::default()]);

        let filter = Filter::new_with_address_and_topic(
            AddressFilter::new(addresses),
            TopicFilter::new(topics),
        );

        let zip_blooms = filter.zip_blooms();
        let blooms: Vec<Bloom> = vec![
            "0000000000000000008000000000000000000000000000000000000000000000
             0000000000000000000000000000000200000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000002000000000000000000080000000000000000000000000000000000
             0000000000000000000000000000000100000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000002000
             0000000000000000000000000000000000000000000000000000000000000000"
                .into(),
            "0000000000000000008000000000000000000000000000000000000000000000
             0000000000000000000000000000000200000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000002000000000000000000080000000000000000000000000000000000
             0000000000000000000000000000000100000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000002000
             0000000000000000000000000000000000000000000000000000000000000000"
                .into(),
            "0000000000000000008000000000000000000000000000000000000000000000
             0000000000000000000000000000000200000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000002000000000000000000080000000000000000000000000000000000
             0000000000000000000000000000000100000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000002000
             0000000000000000000000000000000000000000000000000000000000000000"
                .into(),
            "0000000000000000008000000000000000000000000000000000000000000000
             0000000000000000000000000000000200000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000002000000000000000000080000000000000000000000000000000000
             0000000000000000000000000000000100000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000000000
             0000000000000000000000000000000000000000000000000000000000002000
             0000000000000000000000000000000000000000000000000000000000000000"
                .into(),
        ];
        assert_eq!(zip_blooms, blooms);
    }

    #[test]
    fn test_matches() {
        let topics = vec![
            Some(vec![H256::zero()]),
            Some(vec![H256::zero()]),
            None,
            None,
        ];
        let addresses = Some(vec![Address::default()]);

        let filter = Filter::new_with_address_and_topic(
            AddressFilter::new(addresses),
            TopicFilter::new(topics),
        );

        let entry0 = Log {
            address: Address::default(),
            topics: vec![H256::zero(), H256::zero(), H256::random()],
            data: Default::default(),
        };

        let entry1 = Log {
            address: Address::default(),
            topics: vec![H256::zero(), H256::random(), H256::random()],
            data: Default::default(),
        };

        let entry2 = Log {
            address: Address::random(),
            topics: vec![H256::random(), H256::random(), H256::random()],
            data: Default::default(),
        };

        // Filter matches
        assert_eq!(filter.matches(&entry0), true);
        assert_eq!(filter.matches(&entry1), false);
        assert_eq!(filter.matches(&entry2), false);
        // Topic filter matches
        assert_eq!(filter.topics.matches(&entry0), true);
        assert_eq!(filter.topics.matches(&entry1), false);
        assert_eq!(filter.topics.matches(&entry2), false);
        // Address filter matches
        assert_eq!(filter.addresses.matches(&entry0), true);
        assert_eq!(filter.addresses.matches(&entry1), true);
        assert_eq!(filter.addresses.matches(&entry2), false);
    }
}


text:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections.Generic;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;

namespace OpenSim.Data.MSSQL
{
    /// <summary>
    /// A MSSQL Interface for the Asset server
    /// </summary>
    public class MSSQLAssetData : AssetDataBase
    {
        private const string _migrationStore = "AssetStore";

        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private long m_ticksToEpoch;
        /// <summary>
        /// Database manager
        /// </summary>
        private MSSQLManager m_database;
        private string m_connectionString;

        #region IPlugin Members

        override public void Dispose() { }

        /// <summary>
        /// <para>Initialises asset interface</para>
        /// </summary>
        // [Obsolete("Cannot be default-initialized!")]
        override public void Initialise()
        {
            m_log.Info("[MSSQLAssetData]: " + Name + " cannot be default-initialized!");
            throw new PluginNotInitialisedException(Name);
        }

        /// <summary>
        /// Initialises asset interface
        /// </summary>
        /// <para>
        /// a string instead of file, if someone writes the support
        /// </para>
        /// <param name="connectionString">connect string</param>
        override public void Initialise(string connectionString)
        {
            m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;

            m_database = new MSSQLManager(connectionString);
            m_connectionString = connectionString;

            //New migration to check for DB changes
            m_database.CheckMigration(_migrationStore);
        }

        /// <summary>
        /// Database provider version.
        /// </summary>
        override public string Version
        {
            get { return m_database.getVersion(); }
        }

        /// <summary>
        /// The name of this DB provider.
        /// </summary>
        override public string Name
        {
            get { return "MSSQL Asset storage engine"; }
        }

        #endregion

        #region IAssetDataPlugin Members

        /// <summary>
        /// Fetch Asset from m_database
        /// </summary>
        /// <param name="assetID">the asset UUID</param>
        /// <returns></returns>
        override public AssetBase GetAsset(UUID assetID)
        {
            string sql = "SELECT * FROM assets WHERE id = @id";
            using (SqlConnection conn = new SqlConnection(m_connectionString))
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.Add(m_database.CreateParameter("id", assetID));
                conn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        AssetBase asset = new AssetBase(
                            DBGuid.FromDB(reader["id"]),
                            (string)reader["name"],
                            Convert.ToSByte(reader["assetType"]),
                            reader["creatorid"].ToString()
                        );
                        // Region Main
                        asset.Description = (string)reader["description"];
                        asset.Local = Convert.ToBoolean(reader["local"]);
                        asset.Temporary = Convert.ToBoolean(reader["temporary"]);
                        asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"]));
                        asset.Data = (byte[])reader["data"];
                        return asset;
                    }
                    return null; // throw new Exception("No rows to return");
                }
            }
        }

        /// <summary>
        /// Create asset in m_database
        /// </summary>
        /// <param name="asset">the asset</param>
        override public void StoreAsset(AssetBase asset)
        {

            string sql =
                @"IF EXISTS(SELECT * FROM assets WHERE id=@id)
                    UPDATE assets set name = @name, description = @description, assetType = @assetType,
                            local = @local, temporary = @temporary, creatorid = @creatorid, data = @data
                           WHERE id=@id
                   ELSE
                    INSERT INTO assets
                    ([id], [name], [description], [assetType], [local],
                     [temporary], [create_time], [access_time], [creatorid], [asset_flags], [data])
                    VALUES
                    (@id, @name, @description, @assetType, @local,
                     @temporary, @create_time, @access_time, @creatorid, @asset_flags, @data)";

            string assetName = asset.Name;
            if (asset.Name.Length > 64)
            {
                assetName = asset.Name.Substring(0, 64);
                m_log.WarnFormat(
                    "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
                    asset.Name, asset.ID, asset.Name.Length, assetName.Length);
            }

            string assetDescription = asset.Description;
            if (asset.Description.Length > 64)
            {
                assetDescription = asset.Description.Substring(0, 64);
                m_log.WarnFormat(
                    "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
                    asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
            }

            using (SqlConnection conn = new SqlConnection(m_connectionString))
            using (SqlCommand command = new SqlCommand(sql, conn))
            {
                int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
                command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
                command.Parameters.Add(m_database.CreateParameter("name", assetName));
                command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
                command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
                command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
                command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
                command.Parameters.Add(m_database.CreateParameter("access_time", now));
                command.Parameters.Add(m_database.CreateParameter("create_time", now));
                command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags));
                command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID));
                command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
                conn.Open();
                try
                {
                    command.ExecuteNonQuery();
                }
                catch(Exception e)
                {
                    m_log.Error("[ASSET DB]: Error storing item :" + e.Message);
                }
            }
        }

// Commented out since currently unused - this probably should be called in GetAsset()
//        private void UpdateAccessTime(AssetBase asset)
//        {
//            using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id"))
//            {
//                int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
//                cmd.Parameters.AddWithValue("@id", asset.FullID.ToString());
//                cmd.Parameters.AddWithValue("@access_time", now);
//                try
//                {
//                    cmd.ExecuteNonQuery();
//                }
//                catch (Exception e)
//                {
//                    m_log.Error(e.ToString());
//                }
//            }
//        }

        /// <summary>
        /// Check if asset exist in m_database
        /// </summary>
        /// <param name="uuid"></param>
        /// <returns>true if exist.</returns>
        override public bool ExistsAsset(UUID uuid)
        {
            if (GetAsset(uuid) != null)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Returns a list of AssetMetadata objects. The list is a subset of
        /// the entire data set offset by <paramref name="start" /> containing
        /// <paramref name="count" /> elements.
        /// </summary>
        /// <param name="start">The number of results to discard from the total data set.</param>
        /// <param name="count">The number of rows the returned list should contain.</param>
        /// <returns>A list of AssetMetadata objects.</returns>
        public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
        {
            List<AssetMetadata> retList = new List<AssetMetadata>(count);
            string sql = @"WITH OrderedAssets AS
                (
                    SELECT id, name, description, assetType, temporary, creatorid,
                    RowNumber = ROW_NUMBER() OVER (ORDER BY id)
                    FROM assets
                )
                SELECT *
                FROM OrderedAssets
                WHERE RowNumber BETWEEN @start AND @stop;";

            using (SqlConnection conn = new SqlConnection(m_connectionString))
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.Add(m_database.CreateParameter("start", start));
                cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1));
                conn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        AssetMetadata metadata = new AssetMetadata();
                        metadata.FullID = DBGuid.FromDB(reader["id"]);
                        metadata.Name = (string)reader["name"];
                        metadata.Description = (string)reader["description"];
                        metadata.Type = Convert.ToSByte(reader["assetType"]);
                        metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
                        metadata.CreatorID = (string)reader["creatorid"];
                        retList.Add(metadata);
                    }
                }
            }

            return retList;
        }

        public override bool Delete(string id)
        {
            return false;
        }
        #endregion
    }
}


text:
package com.invariantproperties.project.student.matcher;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import com.invariantproperties.project.student.domain.Term;

/**
 * Hamcrest matcher for 'Term' class.
 *
 * @author Bear Giles <bgiles@coyotesong.com>
 */
public class TermEquality extends TypeSafeMatcher<Term> {
    private final Term expected;

    private TermEquality(Term expected) {
        this.expected = expected;
    }

    @Override
    public boolean matchesSafely(Term actual) {
        if (actual == null) {
            return false;
        }

        EqualsBuilder eq = new EqualsBuilder();
        eq.append(expected.getId(), actual.getId());
        eq.append(expected.getUuid(), actual.getUuid());
        eq.append(expected.getName(), actual.getName());
        eq.append(expected.getCreationDate(), actual.getCreationDate());

        return eq.isEquals();
    }

    public void describeTo(Description description) {
        description.appendText("Term comparison");
    }

    @Factory
    public static <T> Matcher<Term> equalTo(Term term) {
        return new TermEquality(term);
    }
}


text:
FROM debian:sid
MAINTAINER golang-dev <golang-dev@googlegroups.com>

ENV DEBIAN_FRONTEND noninteractive

ADD /scripts/install-apt-deps.sh /scripts/
RUN /scripts/install-apt-deps.sh

ADD /scripts/build-go-builder.sh /scripts/
RUN GO_REV=go1.4 BUILDER_REV=6735829fe0 /scripts/build-go-builder.sh && test -f /usr/local/bin/builder


text:
//
//  SymmetricKey.cs
//
//  Author:
//  	Jim Borden  <jim.borden@couchbase.com>
//
//  Copyright (c) 2015 Couchbase, Inc All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;

#if NET_3_5
using Rackspace.Threading;
#endif

namespace Couchbase.Lite.Store
{
    /// <summary>
    /// Basic AES encryption. Uses a 256-bit (32-byte) key.
    /// </summary>
    public sealed class SymmetricKey
    #if !NET_3_5
        : IDisposable
    #endif
    {

        #region Constants

        /// <summary>
        /// Number of bytes in a 256-bit key
        /// </summary>
        public const int DATA_SIZE = 32;

        /// <summary>
        /// The data type associated with encrypted content
        /// </summary>
        public const string ENCRYPTED_CONTENT_TYPE = "application/x-beanbag-aes-256";

        private const int KEY_SIZE = 32;
        private const int BLOCK_SIZE = 16;
        private const int IV_SIZE = BLOCK_SIZE;
        private const int CHECKSUM_SIZE = sizeof(uint);
        private const string DEFAULT_SALT = "Salty McNaCl";
        private const int DEFAULT_PBKDF_ROUNDS = 64000;

        /// <summary>
        /// Type of block returned by SymmetricKey.CreateEncryptor.
        /// This block can be called repeatedly with input data and returns additional output data.
        /// At EOF, the block should be called with a null parameter, and
        /// it will return the remaining encrypted data from its buffer.
        /// </summary>
        public delegate byte[] CryptorBlock(byte[] input);

        #endregion

        #region Private Members

        private Aes _cryptor;

        private struct Header
        {
            public byte[] iv;
            public byte[] encrypted;
        }

        #endregion

        #region Properties

        /// <summary>
        /// The SymmetricKey's key data; can be used to reconstitute it.
        /// </summary>
        public byte[] KeyData {
            get {
                return _cryptor.Key;
            }
        }

        /// <summary>
        /// The key data encoded as hex.
        /// </summary>
        public string HexData {
            get {
                return BitConverter.ToString(KeyData);
            }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Creates an instance with a random key.
        /// </summary>
        public SymmetricKey()
        {
            InitCryptor();
            _cryptor.GenerateKey();
        }

        /// <summary>
        /// Creates an instance with a key derived from a password.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <param name="salt">A fixed data blob that perturbs the generated key.
        /// Should be kept fixed for any particular app, but doesn't need to be secret.</param>
        /// <param name="rounds">The number of rounds of hashing to perform.
        /// More rounds is more secure but takes longer.</param>
        public SymmetricKey(string password, byte[] salt, int rounds)
        {
            if(password == null) {
                throw new ArgumentNullException("password");
            }
            if(salt.Length <= 4) {
                throw new ArgumentOutOfRangeException("salt", "Value is too short");
            }
            if(rounds <= 200) {
                throw new ArgumentOutOfRangeException("rounds", "Insufficient rounds");
            }

            InitCryptor();
            Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
            pbkdf2.IterationCount = rounds;
            _cryptor.Key = pbkdf2.GetBytes(KEY_SIZE);
        }

        /// <summary>
        /// Creates an instance with a key derived from a password, using default salt and rounds.
        /// </summary>
        public SymmetricKey(string password) :
        this(password, Encoding.UTF8.GetBytes(DEFAULT_SALT), DEFAULT_PBKDF_ROUNDS) {}

        /// <summary>
        /// Creates an instance from existing key data.
        /// </summary>
        public SymmetricKey(byte[] keyData)
        {
            InitCryptor();
            if(keyData.Length != KEY_SIZE) {
                throw new ArgumentOutOfRangeException("keyData", "Value is incorrect size");
            }

            _cryptor.Key = keyData;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Encrypts a data blob.
        /// The output consists of a 16-byte random initialization vector,
        /// followed by PKCS7-padded ciphertext.
        /// </summary>
        public byte[] EncryptData(byte[] data)
        {
            byte[] encrypted = null;
            _cryptor.GenerateIV();
            using(var ms = new MemoryStream())
            using(var cs = new CryptoStream(ms, _cryptor.CreateEncryptor(), CryptoStreamMode.Write)) {
                ms.Write(_cryptor.IV, 0, IV_SIZE);
                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();
                encrypted = ms.ToArray();
            }

            return encrypted;
        }

        /// <summary>
        /// Decrypts data encoded by encryptData.
        /// </summary>
        public byte[] DecryptData(byte[] encryptedData)
        {
            var buffer = new List<byte>();
            using(var ms = new MemoryStream(encryptedData))
            using(var cs = DecryptStream(ms)) {
                int next;
                while((next = cs.ReadByte()) != -1) {
                    buffer.Add((byte)next);
                }
            }

            return buffer.ToArray();
        }

        /// <summary>
        /// Streaming decryption.
        /// </summary>
        public Stream DecryptStream(Stream stream)
        {
            if(!stream.CanRead) {
                throw new ArgumentException("Unable to read from stream", "stream");
            }

            byte[] iv = new byte[IV_SIZE];
            int bytesRead = stream.ReadAsync(iv, 0, IV_SIZE).Result;

            if(bytesRead != IV_SIZE) {
                return null;
            }

            _cryptor.IV = iv;
            return new CryptoStream(stream, _cryptor.CreateDecryptor(), CryptoStreamMode.Read);
        }

        /// <summary>
        /// Incremental encryption: returns a block that can be called repeatedly with input data and
        /// returns additional output data. At EOF the block should be called with a nil parameter, and
        /// it will return the remaining encrypted data from its buffer.
        /// </summary>
        public CryptorBlock CreateEncryptor()
        {
            _cryptor.GenerateIV();
            var encryptor = _cryptor.CreateEncryptor();
            bool wroteIv = false;
            byte[] prevBlock = null;
            var inputBuffer = new List<byte>();
            return new CryptorBlock((input) => {
                if(prevBlock == null) {
                    prevBlock = input;
                    return new byte[0];
                }

                inputBuffer.AddRange(prevBlock);
                List<byte> outputBuffer = null;
                if(input != null) {
                    //Unlike iOS, .NET has no "update" method so we have to manually
                    //break the input into blocks
                    outputBuffer = new List<byte>();
                    while(inputBuffer.Count > encryptor.InputBlockSize) {
                        var tmpBuffer = new byte[encryptor.OutputBlockSize];
                        encryptor.TransformBlock(inputBuffer.Take(encryptor.InputBlockSize).ToArray(), 0, encryptor.InputBlockSize, tmpBuffer, 0);
                        inputBuffer.RemoveRange(0, encryptor.InputBlockSize);
                        outputBuffer.AddRange(tmpBuffer);
                    }
                } else {
                    var tmp = encryptor.TransformFinalBlock(inputBuffer.ToArray(), 0, inputBuffer.Count);
                    outputBuffer = new List<byte>(tmp);
                }

                if(!wroteIv) {
                    outputBuffer.InsertRange(0, _cryptor.IV);
                    wroteIv = true;
                }

                prevBlock = input;
                return outputBuffer.ToArray();
            });
        }

        #endregion

        #region Private Methods

        private void InitCryptor()
        {
            _cryptor = Aes.Create();
            _cryptor.KeySize = KEY_SIZE * 8;
            _cryptor.BlockSize = BLOCK_SIZE * 8;
            _cryptor.Padding = PaddingMode.PKCS7;
        }

        #endregion

        #if !NET_3_5
        #region IDisposable
        #pragma warning disable 1591

        public void Dispose()
        {
            _cryptor.Dispose();
        }

        #pragma warning restore 1591
        #endregion
        #endif
    }
}


text:
import os

import numpy as np

class Spectrum:
    def __init__(self, filename):
        self.path = os.path.abspath(filename)
        self.basename = os.path.basename(filename)
        try:
            self.import_scn(filename)
        except:
            self.name = ''
            self.header = []
            self.mass_values = np.array([])

    def import_scn(self, filename):
        skiprows = 5
        self.name = os.path.basename(filename)
        with open(filename, 'r') as f:
            self.header = [f.readline() for _ in range(skiprows)]
        if self.name:
            self.mass_values = np.loadtxt(filename, skiprows=skiprows)


text:
__author__ = 'Alex Gusev <alex@flancer64.com>'
"""
Domain related classes.
"""