text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Contact } from './contact';
import { ContactService } from './contact.service';
import { Router }   from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

import 'rxjs/add/operator/debounceTime';

@Component({
  moduleId: module.id+"",
  selector: 'contacts',
  templateUrl: 'contacts.component.html',
})
export class ContactsComponent implements OnInit, OnDestroy {
  selectedContact: any;
  contacts: any[];
  allContacts: any[];
  subscriptions: Array<Subscription> = [];

  term: string = '';

  constructor(
    private router: Router,
    private contactService: ContactService
  ){}

  ngOnInit(){
    this.getContacts();

    // subscribe to contact service change event
    let sub = this.contactService
    .contactChanged$
    // make sure we don't redraw contact list multiple times
    .debounceTime(300)
    .subscribe(contact_id => {
      //console.log("observable in contacts.component",contact_id);
      this.getContacts();
    });

    this.subscriptions.push(sub);
  }

  ngOnDestroy(){
    this.subscriptions.map(function(sub){
      //console.log("unsub", sub);
      sub.unsubscribe();
    });
  }

  getContacts(): void {
    this.contactService
    .getContacts()
      .then(contacts => {
        this.allContacts = contacts;
        this.applyFilters();
      });
  }

  onSelected(contact: Contact){

    this.selectedContact = contact;
    this.gotoDetail();
  }

  onRemove(event: any, contact: Contact) {
    event.stopPropagation();

    this.contactService
    .remove(contact)
    .then((response: any) => this.getContacts());
  }

  gotoDetail(): void {
    var id = 'create';
    if(this.selectedContact) {
      id = this.selectedContact.id;
    }

    this.router.navigate(['/contact', id]);
  }

  addContact(){
    this.gotoDetail();
  }

  resetDatabase(){
    this.contactService.deleteAll()
      .then((response: any) => this.getContacts());
  }

  termChanged(term: string) {
    console.log("termChanged", term);
    this.term = term;
    this.applyFilters();
  }

  applyFilters() {
    if(!this.term) {
      return this.contacts = this.allContacts;
    }

    let term = this.term;

    this.contacts = this.allContacts.filter(function(contact){
      let reg = new RegExp('^%term%'.replace(/%term%/g, term),'i');

      return reg.test(contact.forename) || reg.test(contact.surname) || reg.test(contact.mobile) || reg.test(contact.email);
    });
  }
}


text:
/*
 * 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.
 */

package org.nomencurator.gui.swing.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.HashSet;
import java.util.Set;

import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import org.nomencurator.gui.swing.AlignerTree;
import org.nomencurator.gui.swing.ViewportSynchronizer;

/**
 * <tt>AlignerTreeSynchronizer</tt> synchronizes AlignerTrees  to align nodes of  trees
 *
 * @version 	23 Oct. 2015
 * @author 	Nozomi `James' Ytow
 */
public class AlignerTreeSynchronizer
    implements TreeExpansionListener,
	       TreeSelectionListener

{
    protected TreeModel treeModel;

    protected Object eventSource;

    protected Set<AlignerTree> trees;

    protected boolean scrollSynchronize;

    protected ViewportSynchronizer viewports;

    protected static int count = 0;

    public AlignerTreeSynchronizer()
    {
	this(null);
    }

    public AlignerTreeSynchronizer(TreeModel model)
    {
	setModel(model);
	scrollSynchronize = true; //REVISIT
    }

    public synchronized void setModel(TreeModel model)
    {
	if(treeModel == model)
	    return;

	if(treeModel != null &&
	   trees != null) {
	    Iterator<AlignerTree> t = trees.iterator();
	    while(t.hasNext()) {
		t.next().removeTreeExpansionListener(this);
	    }
	    trees.clear();
	    trees = null;
	}

	treeModel = model;
    }

    public void add(AlignerTree tree)
    {
	if(tree == null)
	    return;

	if(trees == null) {
	    trees = new HashSet<AlignerTree>();
	    viewports =
		new ViewportSynchronizer
		    (ViewportSynchronizer.SYNCHRONIZE_Y, isScrollSynchronized());
	}

	if(trees.contains(tree))
	    return;

	if(treeModel == null)
	    setModel(tree.getModel());
	else if(treeModel != tree.getModel()) {
	    return;
	}

	trees.add(tree);
	/*
	viewports.add(tree);
	ViewportSynchronizer.getViewport(tree).addChangeListener(viewports);
	*/

	tree.addTreeExpansionListener(this);
	tree.setSynchronize(true);
	tree.addTreeSelectionListener(this);
	tree.setSelectionSynchronize(true);
    }

    public void remove(AlignerTree tree)
    {
	if(tree == null ||
	   trees == null||
	   !trees.contains(tree))
	    return;
	/*
	ViewportSynchronizer.getViewport(tree).removeChangeListener(viewports);
	viewports.remove(tree);
	*/
	tree.removeTreeSelectionListener(this);
	tree.removeTreeExpansionListener(this);
	trees.remove(tree);
	if(trees.isEmpty()) {
	    viewports = null;
	    trees = null;
	    setModel(null);
	}
    }

    protected synchronized  void setEventSource(Object source)
    {
	eventSource = source;
    }

    protected Object getEventSource()
    {
	return eventSource;
    }

    public void treeCollapsed(TreeExpansionEvent event)
    {
	Object source = event.getSource();
	if(getEventSource() != null ||
	   trees == null ||
	   trees.isEmpty())
	    return;

	setEventSource(event.getSource());

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();

	    if(getEventSource() == tree)
		continue;

	    if(tree.isSynchronized()) {
		tree.collapsePath(event.getPath());
	    }
	}

	setEventSource(null);
    }

    public void treeExpanded(TreeExpansionEvent event)
    {
	Object source = event.getSource();
	synchronized (this) {
	    if(getEventSource() != null ||
	       trees == null ||
	       trees.isEmpty())
		return;

	    setEventSource(event.getSource());
	}

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    /*
	    if(getEventSource() == tree)
		continue;
	    */
	    if(tree.isSynchronized()) {
		tree.expandPath(event.getPath());
	    }
	}

	synchronized (this) {
	    setEventSource(null);
	}
    }

    public void valueChanged(TreeSelectionEvent event)
    {
	Object source = event.getSource();
	if(getEventSource() != null ||
	   trees == null ||
	   trees.isEmpty()) {
	    return;
	}
	setEventSource(event.getSource());

	TreePath path = event.getPath();
	TreePath[] paths = event.getPaths();

	if(path == null) {
	    clearSelection();
	}
	else if(paths.length == 1) {
	    if(event.isAddedPath()) {
		clearSelection();
		setSelectionPath(path);
	    }
	    else {
		removeSelectionPath(path);
	    }
	}
	else {
	    final List<TreePath> selected = new ArrayList<TreePath>();
	    final List<TreePath> unselected = new ArrayList<TreePath>();

	    for(TreePath treePath : paths) {
		if(event.isAddedPath(treePath))
		    selected.add(treePath);
		else
		    unselected.add(treePath);
	    }

	    removeSelectionPaths(unselected.toArray(new TreePath[unselected.size()]));
	    addSelectionPaths(selected.toArray(new TreePath[selected.size()]));
	}
	setEventSource(null);
    }

    public void clearSelection()
    {
	if(trees == null)
	    return;

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    if(getEventSource() == tree)
		continue;
	    if(tree.isSelectionSynchronized())
		tree.clearSelection();
	}
    }

    /**
     * Sets selection to path.
     *
     * @param path TreePath to be set
     * as new selection
     */
    public void setSelectionPath(TreePath path)
    {
	if(trees == null)
	    return;

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    if(getEventSource() == tree)
		continue;
	    if(tree.isSelectionSynchronized())
		tree.setSelectionPath(path);
	}
    }

    /**
     * Sets selection to paths.
     *
     * @param paths an array of TreePath to be set
     * as new selection
     */
    public void setSelectionPaths(TreePath[] paths)
    {
	if(trees == null)
	    return;

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    if(getEventSource() == tree)
		continue;
	    if(tree.isSelectionSynchronized())
		tree.setSelectionPaths(paths);
	}
    }

    /**
     * Adds paths to selection.
     *
     * @param paths an array of TreePath to be add
     * to selection
     */
    public void addSelectionPaths(TreePath[] paths)
    {
	if(trees == null)
	    return;

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    if(getEventSource() == tree)
		continue;
	    if(tree.isSelectionSynchronized())
		tree.addSelectionPaths(paths);
	}
    }

    /**
     * Removes paths from selection.
     *
     * @param paths an array of TreePath to be removed
     * from selection
     */
    public void removeSelectionPath(TreePath path)
    {
	if(trees == null)
	    return;

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    if(getEventSource() == tree)
		continue;
	    if(tree.isSelectionSynchronized())
		tree.removeSelectionPath(path);
	}
    }
    /**
     * Removes paths from selection.
     *
     * @param paths an array of TreePath to be removed
     * from selection
     */
    public void removeSelectionPaths(TreePath[] paths)
    {
	if(trees == null)
	    return;

	Iterator<AlignerTree> t = trees.iterator();
	while(t.hasNext()) {
	    AlignerTree tree = t.next();
	    if(getEventSource() == tree)
		continue;
	    if(tree.isSelectionSynchronized())
		tree.removeSelectionPaths(paths);
	}
    }

    public synchronized void setScrollSynchronize(boolean toSynchronize )
    {
	if(scrollSynchronize == toSynchronize)
	    return;

	scrollSynchronize = toSynchronize;
	/*
	if(viewports != null)
	    viewports.setScrollSynchronize(scrollSynchronize);
	*/
    }

    public boolean isScrollSynchronized()
    {
	return scrollSynchronize;
    }

}

redpajama_set_name: RedPajamaGithub


text:
title:  Iosif, stăpânul viselor
date:   04/06/2022
---

>
Textul de memorat

> "Ei au zis unul către altul: «_____________________
__________________________________________»" (Geneza 37:19).

Istoria lui Iosif (Geneza 37–50) acoperă ultima secțiune a cărții Geneza, de
la primele lui vise din Canaan (Geneza 37:1-11) până la moartea lui în Egipt
(Geneza 50:26). De fapt, Iosif ocupă mai mult spațiu din cartea Geneza decât
oricare alt patriarh. Deși este doar unul dintre fiii lui Iacov, Iosif este prezentat în Geneza ca un mare patriarh, așa cum sunt Avraam, Isaac și Iacov.

După cum vom vedea, și viața lui Iosif scoate în evidență două adevăruri
teologice importante: (1) Dumnezeu Își respectă promisiunile și (2) Dumnezeu
poate transforma răul în bine.

În studiul din această săptămână ne vom concentra asupra primei părți din
viața lui Iosif. El este fiul preferat al lui Iacov, poreclit ironic ba′al hakhalomot, "făuritorul de vise" (Geneza 37:19), care literal înseamnă "stăpânul viselor" (Geneza 37:19, NTR), sugerând că este expert în vise. Acest titlu i se potrivește foarte bine, pentru că el nu doar că primește, înțelege și interpretează visele profetice, ci le și împlinește în viața lui.

Vom vedea din nou în aceste capitole cum este confirmată providența lui
Dumnezeu, chiar și în ciuda răului și a ticăloșiei din inima omului.

**11 iunie – Dar proiecte speciale Conferinţe (colectă)**

**11 iunie – Ziua Misiunii Femeii**


text:
package com.evolveum.midpoint.schema;

import static com.evolveum.midpoint.schema.TestConstants.*;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.namespace.QName;

import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.Item;
import com.evolveum.midpoint.prism.PrismConstants;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismContainerValue;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PrismReference;
import com.evolveum.midpoint.prism.PrismReferenceValue;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExtensionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;

/**
 * @author semancik
 *
 */
public abstract class TestParseUser {

	@BeforeSuite
	public void setup() throws SchemaException, SAXException, IOException {
		PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
		PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
	}

	protected abstract String getSubdirName();

	protected abstract String getLanguage();

	protected abstract String getFilenameSuffix();

	protected File getCommonSubdir() {
		return new File(COMMON_DIR_PATH, getSubdirName());
	}

	protected File getFile(String baseName) {
		return new File(getCommonSubdir(), baseName+"."+getFilenameSuffix());
	}

	@Test
	public void testParseUserFile() throws Exception {
		final String TEST_NAME = "testParseUserFile";
		PrismTestUtil.displayTestTitle(TEST_NAME);

		// GIVEN
		PrismContext prismContext = PrismTestUtil.getPrismContext();

		// WHEN
		PrismObject<UserType> user = prismContext.parseObject(getFile(USER_FILE_BASENAME));
		// THEN
		System.out.println("Parsed user:");
		System.out.println(user.debugDump());

		String serialized = prismContext.serializeObjectToString(user, getLanguage());
		System.out.println("Serialized: \n" +serialized);

		PrismObject<UserType> reparsedUser = prismContext.parseObject(serialized);

		assertUser(user);
	}

	@Test
	public void testParseUserDom() throws Exception {
		final String TEST_NAME = "testParseUserDom";
		PrismTestUtil.displayTestTitle(TEST_NAME);

		// GIVEN
		PrismContext prismContext = PrismTestUtil.getPrismContext();

//		Document document = DOMUtil.parseFile(USER_FILE);
//		Element userElement = DOMUtil.getFirstChildElement(document);

		// WHEN
		PrismObject<UserType> user = prismContext.parseObject(getFile(USER_FILE_BASENAME));

		// THEN
		System.out.println("Parsed user:");
		System.out.println(user.debugDump());

		assertUser(user);
	}

	@Test
	public void testParseUserRoundTrip() throws Exception{
		final String TEST_NAME = "testParseUserRoundTrip";
		PrismTestUtil.displayTestTitle(TEST_NAME);

		// GIVEN
		PrismContext prismContext = PrismTestUtil.getPrismContext();

//		Document document = DOMUtil.parseFile(USER_FILE);
//		Element userElement = DOMUtil.getFirstChildElement(document);

		// WHEN
		PrismObject<UserType> user = prismContext.parseObject(getFile(USER_FILE_BASENAME));

		// THEN
		System.out.println("Parsed user:");
		System.out.println(user.debugDump());

		assertUser(user);

		String serializedUser = prismContext.serializeObjectToString(user, getLanguage());
		System.out.println("Serialized user:");
		System.out.println(serializedUser);

		// REPARSE
		PrismObject<UserType> reparsedUser = prismContext.parseObject(serializedUser);

		// THEN
		System.out.println("Parsed user:");
		System.out.println(reparsedUser.debugDump());

		assertUser(reparsedUser);

		// and some sanity checks

		assertTrue("User not equals", user.equals(reparsedUser));

		ObjectDelta<UserType> delta = user.diff(reparsedUser);
		assertTrue("Delta not empty", delta.isEmpty());

	}

	void assertUser(PrismObject<UserType> user) {
		user.checkConsistence();
		assertUserPrism(user);
		assertUserJaxb(user.asObjectable());

		user.checkConsistence(true, true);
	}

	void assertUserPrism(PrismObject<UserType> user) {

		assertEquals("Wrong oid", "2f9b9299-6f45-498f-bc8e-8d17c6b93b20", user.getOid());
//		assertEquals("Wrong version", "42", user.getVersion());
		PrismObjectDefinition<UserType> usedDefinition = user.getDefinition();
		assertNotNull("No user definition", usedDefinition);
		PrismAsserts.assertObjectDefinition(usedDefinition, new QName(SchemaConstantsGenerated.NS_COMMON, "user"),
				UserType.COMPLEX_TYPE, UserType.class);
		assertEquals("Wrong class in user", UserType.class, user.getCompileTimeClass());
		UserType userType = user.asObjectable();
		assertNotNull("asObjectable resulted in null", userType);

		assertPropertyValue(user, "name", PrismTestUtil.createPolyString("jack"));
		assertPropertyDefinition(user, "name", PolyStringType.COMPLEX_TYPE, 0, 1);
		assertPropertyValue(user, "fullName", new PolyString("Jack Sparrow", "jack sparrow"));
		assertPropertyDefinition(user, "fullName", PolyStringType.COMPLEX_TYPE, 0, 1);
		assertPropertyValue(user, "givenName", new PolyString("Jack", "jack"));
		assertPropertyDefinition(user, "givenName", PolyStringType.COMPLEX_TYPE, 0, 1);
		assertPropertyValue(user, "familyName", new PolyString("Sparrow", "sparrow"));
		assertPropertyDefinition(user, "familyName", PolyStringType.COMPLEX_TYPE, 0, 1);

		assertPropertyDefinition(user, "organizationalUnit", PolyStringType.COMPLEX_TYPE, 0, -1);
		assertPropertyValues(user, "organizationalUnit",
				new PolyString("Brethren of the Coast", "brethren of the coast"),
				new PolyString("Davie Jones' Locker", "davie jones locker"));

//		PrismContainer extension = user.getExtension();
//		assertContainerDefinition(extension, "extension", DOMUtil.XSD_ANY, 0, 1);
//		PrismContainerValue extensionValue = extension.getValue();
//		assertTrue("Extension parent", extensionValue.getParent() == extension);
//		assertNull("Extension ID", extensionValue.getId());

		ItemPath admStatusPath = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS);
		PrismProperty<ActivationStatusType> admStatusProperty1 = user.findProperty(admStatusPath);
		PrismAsserts.assertDefinition(admStatusProperty1.getDefinition(), ActivationType.F_ADMINISTRATIVE_STATUS, SchemaConstants.C_ACTIVATION_STATUS_TYPE, 0, 1);
		assertNotNull("Property "+admStatusPath+" not found", admStatusProperty1);
		PrismAsserts.assertPropertyValue(admStatusProperty1, ActivationStatusType.ENABLED);

//		PrismProperty validFromProperty = user.findProperty(new PropertyPath(UserType.F_ACTIVATION, ActivationType.F_VALID_FROM));
//		assertNotNull("Property "+ActivationType.F_VALID_FROM+" not found", validFromProperty);
//		PrismAsserts.assertPropertyValue(validFromProperty, USER_JACK_VALID_FROM);

		PrismContainer<AssignmentType> assignmentContainer = user.findContainer(UserType.F_ASSIGNMENT);
		PrismAsserts.assertDefinition(assignmentContainer.getDefinition(), UserType.F_ASSIGNMENT, AssignmentType.COMPLEX_TYPE, 0, -1);
		assertEquals("Wrong number of assignment values", 1, assignmentContainer.getValues().size());
		PrismContainerValue<AssignmentType> firstAssignmentValue = assignmentContainer.getValues().iterator().next();

		PrismContainer<Containerable> assignmentExtensionContainer = firstAssignmentValue.findContainer(AssignmentType.F_EXTENSION);
		PrismAsserts.assertDefinition(assignmentExtensionContainer.getDefinition(), AssignmentType.F_EXTENSION, ExtensionType.COMPLEX_TYPE, 0, 1);
		List<Item<?>> assignmentExtensionItems = assignmentExtensionContainer.getValue().getItems();
		assertNotNull("No assignment extension items", assignmentExtensionItems);
		assertEquals("Wrong number of assignment extension items", 1, assignmentExtensionItems.size());
		PrismProperty<String> firstAssignmentExtensionItem = (PrismProperty<String>) assignmentExtensionItems.get(0);
		PrismAsserts.assertDefinition(firstAssignmentExtensionItem.getDefinition(), EXTENSION_INT_TYPE_ELEMENT, DOMUtil.XSD_INT, 0, -1);
		PrismPropertyValue<String> firstValueOfFirstAssignmentExtensionItem = firstAssignmentExtensionItem.getValues().get(0);
		assertEquals("Wrong value of "+EXTENSION_INT_TYPE_ELEMENT+" in assignment extension", 42, firstValueOfFirstAssignmentExtensionItem.getValue());

		// TODO: check accountConstruction

		PrismReference accountRef = user.findReference(UserType.F_LINK_REF);
		assertEquals("Wrong number of accountRef values", 3, accountRef.getValues().size());
		PrismAsserts.assertReferenceValue(accountRef, USER_ACCOUNT_REF_1_OID);
		PrismAsserts.assertReferenceValue(accountRef, USER_ACCOUNT_REF_2_OID);
		PrismAsserts.assertReferenceValue(accountRef, USER_ACCOUNT_REF_3_OID);

		PrismReferenceValue accountRef1Val = accountRef.findValueByOid(USER_ACCOUNT_REF_1_OID);
		assertNotNull("No object in ref1 (prism)", accountRef1Val.getObject());
		assertNotNull("No object definition in ref1 (prism)", accountRef1Val.getObject().getDefinition());
		assertEquals("Wrong ref1 oid (prism)", USER_ACCOUNT_REF_1_OID, accountRef1Val.getOid());
		assertEquals("Wrong ref1 type (prism)", ShadowType.COMPLEX_TYPE, accountRef1Val.getTargetType());

		PrismReferenceValue accountRef3Val = accountRef.findValueByOid(USER_ACCOUNT_REF_3_OID);
		assertEquals("Wrong ref3 oid (prism)",  USER_ACCOUNT_REF_3_OID, accountRef3Val.getOid());
		assertEquals("Wrong ref3 type (prism)", ShadowType.COMPLEX_TYPE, accountRef3Val.getTargetType());
		assertEquals("Wrong ref3 description (prism)", "This is third accountRef", accountRef3Val.getDescription());
		SearchFilterType accountRef3ValFilterElement = accountRef3Val.getFilter();
		assertFilter("ref3", accountRef3ValFilterElement);
	}

	private void assertFilterElement(String message, Element filterElement) {
		assertNotNull("No "+message+" filter", filterElement);
		System.out.println("Filter element "+message);
		System.out.println(DOMUtil.serializeDOMToString(filterElement));
		assertEquals("Wrong "+message+" filter namespace", PrismConstants.NS_QUERY, filterElement.getNamespaceURI());
		assertEquals("Wrong "+message+" filter localName", "equal", filterElement.getLocalName());
	}

	private void assertFilter(String message, SearchFilterType filter) {
		assertNotNull("No "+message+" filter", filter);
	}

	private void assertUserJaxb(UserType userType) {
		assertEquals("Wrong name", PrismTestUtil.createPolyStringType("jack"), userType.getName());
		assertEquals("Wrong fullName (orig)", "Jack Sparrow", userType.getFullName().getOrig());
        assertEquals("Wrong fullName (norm)", "jack sparrow", userType.getFullName().getNorm());
		assertEquals("Wrong givenName (orig)", "Jack", userType.getGivenName().getOrig());
		assertEquals("Wrong givenName (norm)", "jack", userType.getGivenName().getNorm());
		assertEquals("Wrong familyName (orig)", "Sparrow", userType.getFamilyName().getOrig());
		assertEquals("Wrong familyName (norm)", "sparrow", userType.getFamilyName().getNorm());

		ActivationType activation = userType.getActivation();
		assertNotNull("No activation", activation);
		assertEquals("User not enabled", ActivationStatusType.ENABLED, activation.getAdministrativeStatus());

		List<ObjectReferenceType> accountRefs = userType.getLinkRef();
		assertNotNull("No accountRef list", accountRefs);
		assertEquals("Wrong number of list entries", 3, accountRefs.size());

		ObjectReferenceType ref1 = ObjectTypeUtil.findRef(USER_ACCOUNT_REF_1_OID, accountRefs);
		assertEquals("Wrong ref1 oid (jaxb)", USER_ACCOUNT_REF_1_OID, ref1.getOid());
		assertEquals("Wrong ref1 type (jaxb)", ShadowType.COMPLEX_TYPE, ref1.getType());

		ObjectReferenceType ref2 = ObjectTypeUtil.findRef(USER_ACCOUNT_REF_2_OID, accountRefs);
		assertEquals("Wrong ref2 oid (jaxb)", USER_ACCOUNT_REF_2_OID, ref2.getOid());
		assertEquals("Wrong ref2 type (jaxb)", ShadowType.COMPLEX_TYPE, ref2.getType());

		ObjectReferenceType ref3 = ObjectTypeUtil.findRef(USER_ACCOUNT_REF_3_OID, accountRefs);
		assertEquals("Wrong ref3 oid (jaxb)", USER_ACCOUNT_REF_3_OID, ref3.getOid());
		assertEquals("Wrong ref3 type (jaxb)", ShadowType.COMPLEX_TYPE, ref3.getType());
		SearchFilterType ref3Filter = ref3.getFilter();
		assertNotNull("No ref3 filter (jaxb,class)", ref3Filter);
		assertFilterElement("ref filter (jaxb)", ref3Filter.getFilterClause());
	}

	private void assertPropertyDefinition(PrismContainer<?> container, String propName, QName xsdType, int minOccurs,
			int maxOccurs) {
		QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName);
		PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs);
	}

	public static void assertPropertyValue(PrismContainer<?> container, String propName, Object propValue) {
		QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName);
		PrismAsserts.assertPropertyValue(container, propQName, propValue);
	}

	public static <T> void assertPropertyValues(PrismContainer<?> container, String propName, T... expectedValues) {
		QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName);
		PrismAsserts.assertPropertyValue(container, propQName, expectedValues);
	}

    @Test
    public void testPrismConsistency() throws Exception {

        System.out.println("===[ testPrismConsistency ]===");

        // GIVEN
        PrismContext ctx = PrismTestUtil.getPrismContext();
        PrismObjectDefinition<UserType> userDefinition = ctx.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class);

        // WHEN
        PrismObject<UserType> user = userDefinition.instantiate();
        user.setOid("12345");

        // THEN
        System.out.println("User:");
        System.out.println(user.debugDump());

        System.out.println("Checking consistency, 1st time.");
        user.checkConsistence();
        UserType userType = user.getValue().getValue();

        System.out.println("Checking consistency, 2nd time - after getValue().getValue().");
        user.checkConsistence();

        System.out.println("OK.");
    }

}


text:
package com.yan.leetcode;

/**
 * Path Sum
 *
 * @author jingyangyan
 * @version 1.0
 * @create 2016-09-06 16:36
 */
public class PathSum {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null)
            return false;
        if (root.left == null && root.right == null && root.val == sum)
            return true;
        else
            return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}


text:
<?php

/** @file
* @brief
*/

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

class ChangeTask extends CommonITILTask {

   static $rightname = 'task';

   /**
    * @since version 0.84
   **/
   static function getTypeName($nb=0) {
      return _n('Change task', 'Change tasks', $nb);
   }

   static function canCreate() {
      return Session::haveRight('change', UPDATE);
   }

   static function canView() {
      return Session::haveRightsOr('change', array(Change::READALL, Change::READMY));
   }

   static function canUpdate() {
      return Session::haveRight('change', UPDATE);
   }

   function canViewPrivates() {
      return true;
   }

   function canEditAll() {
      return Session::haveRightsOr('change', array(CREATE, UPDATE, DELETE, PURGE));
   }

   /**
    * Is the current user have right to show the current task ?
    *
    * @return boolean
   **/
   function canViewItem() {
      return parent::canReadITILItem();
   }

   /**
    * Is the current user have right to create the current task ?
    *
    * @return boolean
   **/
   function canCreateItem() {

      if (!parent::canReadITILItem()) {
         return false;
      }

      $change = new Change();

      if ($change->getFromDB($this->fields['changes_id'])) {
         return (Session::haveRight('change', UPDATE)
                 || (Session::haveRight('change', Change::READMY)
                     && ($change->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID())
                         || (isset($_SESSION["glpigroups"])
                             && $change->haveAGroup(CommonITILActor::ASSIGN,
                                                    $_SESSION['glpigroups'])))));
      }
      return false;

   }

   /**
    * Is the current user have right to update the current task ?
    *
    * @return boolean
   **/
   function canUpdateItem() {

      if (!parent::canReadITILItem()) {
         return false;
      }

      if (($this->fields["users_id"] != Session::getLoginUserID())
          && !Session::haveRight('change', UPDATE)) {
         return false;
      }

      return true;
   }

   /**
    * Is the current user have right to purge the current task ?
    *
    * @return boolean
   **/
   function canPurgeItem() {
      return $this->canUpdateItem();
   }

   /**
    * Populate the planning with planned ticket tasks
    *
    * @param $options array of possible options:
    *    - who ID of the user (0 = undefined)
    *    - who_group ID of the group of users (0 = undefined)
    *    - begin Date
    *    - end Date
    *
    * @return array of planning item
   **/
   static function populatePlanning($options=array()) {
      return parent::genericPopulatePlanning(__CLASS__, $options);
   }

   /**
    * Display a Planning Item
    *
    * @param $val array of the item to display
    *
    * @return Already planned information
   **/
   static function getAlreadyPlannedInformation($val) {
      return parent::genericGetAlreadyPlannedInformation(__CLASS__, $val);
   }

   /**
    * Display a Planning Item
    *
    * @param $val       array of the item to display
    * @param $who             ID of the user (0 if all)
    * @param $type            position of the item in the time block (in, through, begin or end)
    *                         (default '')
    * @param $complete        complete display (more details) (default 0)
    *
    * @return Nothing (display function)
   **/
   static function displayPlanningItem(array $val, $who, $type="", $complete=0) {
      return parent::genericDisplayPlanningItem(__CLASS__,$val, $who, $type, $complete);
   }

}
?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaeronaema comatum Ces.

### Remarks
null


text:
namespace Packets
{
    class CGChannelCreate : public Packet
    {
    public:
        CGChannelCreate( ){} ;
        virtual ~CGChannelCreate( ){} ;

        //公用继承接口
        virtual BOOL            Read( SocketInputStream& iStream ) ;
        virtual BOOL            Write( SocketOutputStream& oStream )const ;
        virtual UINT            Execute( Player* pPlayer ) ;

        virtual PacketID_t        GetPacketID()const { return PACKET_CG_CHANNELCREATE ; }
        virtual UINT            GetPacketSize()const { return sizeof(GUID_t) ; }

    public :

    public:
        //使用数据接口
        VOID                SetGUID( GUID_t guid ){    m_GUID = guid ; }
        GUID_t                GetGUID( ){ return m_GUID ; }

    private:
        //数据
        GUID_t                m_GUID ;

    };

    class CGChannelCreateFactory : public PacketFactory
    {
    public:
        Packet*        CreatePacket() { return new CGChannelCreate() ; }
        PacketID_t    GetPacketID()const { return PACKET_CG_CHANNELCREATE ; }
        UINT        GetPacketMaxSize()const { return sizeof(GUID_t) ; }
    };

    class CGChannelCreateHandler
    {
    public:
        static UINT Execute( CGChannelCreate* pPacket, Player* pPlayer ) ;
    };

};

using namespace Packets ;

#endif


text:
'use strict';

import * as assert from 'assert';
import { IHTMLContentElement } from 'vs/base/common/htmlContent';
import { IKeyboardMapper } from 'vs/workbench/services/keybinding/common/keyboardMapper';
import { Keybinding, ResolvedKeybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
import { TPromise } from 'vs/base/common/winjs.base';
import { readFile, writeFile } from 'vs/base/node/pfs';
import { OperatingSystem } from 'vs/base/common/platform';
import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
import { ScanCodeBinding } from 'vs/workbench/services/keybinding/common/scanCode';

export interface IResolvedKeybinding {
	label: string;
	labelWithoutModifiers: string;
	ariaLabel: string;
	ariaLabelWithoutModifiers: string;
	electronAccelerator: string;
	userSettingsLabel: string;
	isWYSIWYG: boolean;
	isChord: boolean;
	hasCtrlModifier: boolean;
	hasShiftModifier: boolean;
	hasAltModifier: boolean;
	hasMetaModifier: boolean;
	dispatchParts: [string, string];
}

function toIResolvedKeybinding(kb: ResolvedKeybinding): IResolvedKeybinding {
	return {
		label: kb.getLabel(),
		labelWithoutModifiers: kb.getLabelWithoutModifiers(),
		ariaLabel: kb.getAriaLabel(),
		ariaLabelWithoutModifiers: kb.getAriaLabelWithoutModifiers(),
		electronAccelerator: kb.getElectronAccelerator(),
		userSettingsLabel: kb.getUserSettingsLabel(),
		isWYSIWYG: kb.isWYSIWYG(),
		isChord: kb.isChord(),
		hasCtrlModifier: kb.hasCtrlModifier(),
		hasShiftModifier: kb.hasShiftModifier(),
		hasAltModifier: kb.hasAltModifier(),
		hasMetaModifier: kb.hasMetaModifier(),
		dispatchParts: kb.getDispatchParts(),
	};
}

export function assertResolveKeybinding(mapper: IKeyboardMapper, keybinding: Keybinding, expected: IResolvedKeybinding[]): void {
	let actual: IResolvedKeybinding[] = mapper.resolveKeybinding(keybinding).map(toIResolvedKeybinding);
	assert.deepEqual(actual, expected);
}

export function assertResolveKeyboardEvent(mapper: IKeyboardMapper, keyboardEvent: IKeyboardEvent, expected: IResolvedKeybinding): void {
	let actual = toIResolvedKeybinding(mapper.resolveKeyboardEvent(keyboardEvent));
	assert.deepEqual(actual, expected);
}

export function assertResolveUserBinding(mapper: IKeyboardMapper, firstPart: SimpleKeybinding | ScanCodeBinding, chordPart: SimpleKeybinding | ScanCodeBinding, expected: IResolvedKeybinding[]): void {
	let actual: IResolvedKeybinding[] = mapper.resolveUserBinding(firstPart, chordPart).map(toIResolvedKeybinding);
	assert.deepEqual(actual, expected);
}

function _htmlPieces(pieces: string[], OS: OperatingSystem): IHTMLContentElement[] {
	let children: IHTMLContentElement[] = [];
	for (let i = 0, len = pieces.length; i < len; i++) {
		if (i !== 0 && OS !== OperatingSystem.Macintosh) {
			children.push({ tagName: 'span', text: '+' });
		}
		children.push({ tagName: 'span', className: 'monaco-kbkey', text: pieces[i] });
	}
	return children;
}

export function simpleHTMLLabel(pieces: string[], OS: OperatingSystem): IHTMLContentElement {
	return {
		tagName: 'span',
		className: 'monaco-kb',
		children: _htmlPieces(pieces, OS)
	};
}

export function chordHTMLLabel(firstPart: string[], chordPart: string[], OS: OperatingSystem): IHTMLContentElement {
	return {
		tagName: 'span',
		className: 'monaco-kb',
		children: [].concat(
			_htmlPieces(firstPart, OS),
			[{ tagName: 'span', text: ' ' }],
			_htmlPieces(chordPart, OS)
		)
	};
}

export function readRawMapping<T>(file: string): TPromise<T> {
	return readFile(require.toUrl(`vs/workbench/services/keybinding/test/${file}.js`)).then((buff) => {
		let contents = buff.toString();
		let func = new Function('define', contents);
		let rawMappings: T = null;
		func(function (value) {
			rawMappings = value;
		});
		return rawMappings;
	});
}

export function assertMapping(writeFileIfDifferent: boolean, mapper: IKeyboardMapper, file: string, done: (err?: any) => void): void {
	const filePath = require.toUrl(`vs/workbench/services/keybinding/test/${file}`);

	readFile(filePath).then((buff) => {
		let expected = buff.toString();
		const actual = mapper.dumpDebugInfo();
		if (actual !== expected && writeFileIfDifferent) {
			writeFile(filePath, actual);
		}
		try {
			assert.deepEqual(actual, expected);
		} catch (err) {
			return done(err);
		}
		done();
	}, done);
}


text:
package stsc.stocks.repo;

import java.util.List;

import stsc.stocks.indexes.CountryMarketIndex;
import stsc.stocks.indexes.GlobalMarketIndex;
import stsc.stocks.indexes.RegionMarketIndex;

/**
 * {@link MetaIndicesRepository} is a repository for meta indices.
 */
public interface MetaIndicesRepository {

	public List<GlobalMarketIndex> getGlobalMarketIndices();

	public List<RegionMarketIndex> getRegionMarketIndices();

	public List<CountryMarketIndex> getCountryMarketIndices();

}


text:
require 'rails_helper'

feature 'FOI Case creation by a manager' do

  given!(:responder)       { find_or_create(:foi_responder) }
  given!(:responding_team) { create :responding_team, responders: [responder] }
  given(:manager)         { find_or_create :disclosure_bmt_user }
  given(:managing_team)   { create :managing_team, managers: [manager] }

  background do
    find_or_create :team_dacu_disclosure
    login_as manager
    cases_page.load
  end

  scenario 'creating a case that does not need clearance', js: true do
    kase = create_foi_case_step flag_for_disclosure: false
    expect(assignments_new_page).to be_displayed(case_id: kase.id)

    assign_case_step business_unit: responder.responding_teams.first
  end

  scenario 'creating a case that needs clearance' do
    create_foi_case_step flag_for_disclosure: true

    new_case = Case::Base.last
    expect(new_case.requires_clearance?).to be true
  end

  scenario 'creating a case being sent by post with request attachments', js: true  do
    request_attachment = Rails.root.join('spec', 'fixtures', 'request-1.pdf')

    create_foi_case_step delivery_method: :sent_by_post,
                         uploaded_request_files: [request_attachment]

    new_case = Case::Base.last
    request_attachment = new_case.attachments.request.first
    expect(request_attachment.key).to match %{/request-1.pdf$}
  end

  scenario 'creating a case being sent by email with request attachments', js: true  do
    request_attachment = Rails.root.join('spec', 'fixtures', 'request-1.pdf')

    create_foi_case_step delivery_method: :sent_by_email,
                         uploaded_request_files: [request_attachment]

    new_case = Case::Base.last
    request_attachment = new_case.attachments.request.first
    expect(request_attachment.key).to match %{/request-1.pdf$}
  end

  scenario 'non-standard cases are auto-flagged for disclosure specialists', js: true do
    create_foi_case_auto_flagged_step type: 'compliancereview'

    new_case = Case::Base.last
    expect(new_case.flagged_for_disclosure_specialist_clearance?).to be true
  end
end


text:
/**
 *
 */
package com.thinkbiganalytics.metadata.modeshape.common;

/*-
 * #%L
 * thinkbig-metadata-modeshape
 * %%
 * Copyright (C) 2017 ThinkBig Analytics
 * %%
 * 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.
 * #L%
 */

import com.thinkbiganalytics.metadata.modeshape.support.JcrUtil;

import java.nio.file.Path;

/**
 * Defines and resolves paths of users and user groups within the JCR repository.
 */
public interface UsersPaths {

    public static final Path USERS = JcrUtil.path("users");
    public static final Path GROUPS = JcrUtil.path("groups");

    static Path userPath(String name) {
        return USERS.resolve(name);
    }

    static Path groupPath(String name) {
        return GROUPS.resolve(name);
    }
}


text:
AcceptedOfferListPage::AcceptedOfferListPage(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AcceptedOfferListPage),
    model(0),
    optionsModel(0)
{
    ui->setupUi(this);

    //buttons get created

#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
    ui->copyOffer->setIcon(QIcon());
    ui->exportButton->setIcon(QIcon());
#endif

    ui->labelExplanation->setText(tr("These are your accepted Syscoin offers."));

    // Context menu actions
    QAction *copyOfferAction = new QAction(ui->copyOffer->text(), this);
    QAction *copyOfferValueAction = new QAction(tr("Copy Va&lue"), this);

    // Build context menu
    contextMenu = new QMenu();
    contextMenu->addAction(copyOfferAction);
    contextMenu->addAction(copyOfferValueAction);

    // Connect signals for context menu actions
    connect(copyOfferAction, SIGNAL(triggered()), this, SLOT(on_copyOffer_clicked()));
    connect(copyOfferValueAction, SIGNAL(triggered()), this, SLOT(onCopyOfferValueAction()));

    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));

}

AcceptedOfferListPage::~AcceptedOfferListPage()
{
    delete ui;
}

void AcceptedOfferListPage::setModel(OfferTableModel *model)
{
    this->model = model;
    if(!model) return;

    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(model);
    proxyModel->setDynamicSortFilter(true);
    proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
	proxyModel->setFilterRole(OfferTableModel::TypeRole);
    proxyModel->setFilterFixedString(OfferTableModel::Offer);
    ui->tableView->setModel(proxyModel);
    ui->tableView->sortByColumn(0, Qt::AscendingOrder);

    // Set column widths
#if QT_VERSION < 0x050000
    ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::Name, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::Category, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::Title, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::Price, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::Quantity, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::ExpirationDepth, QHeaderView::ResizeToContents);
	ui->tableView->horizontalHeader()->setResizeMode(OfferTableModel::Description, QHeaderView::ResizeToContents);
#else
    ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::Name, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::Category, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::Title, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::Price, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::Quantity, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::ExpirationDepth, QHeaderView::ResizeToContents);
	ui->tableView->horizontalHeader()->setSectionResizeMode(OfferTableModel::Description, QHeaderView::ResizeToContents);
#endif

    connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(selectionChanged()));

    selectionChanged();
}

void AcceptedOfferListPage::setOptionsModel(OptionsModel *optionsModel)
{
    this->optionsModel = optionsModel;
}

void AcceptedOfferListPage::on_copyOffer_clicked()
{
    GUIUtil::copyEntryData(ui->tableView, OfferTableModel::Name);
}

void AcceptedOfferListPage::onCopyOfferValueAction()
{
    GUIUtil::copyEntryData(ui->tableView, OfferTableModel::Title);
}

void AcceptedOfferListPage::selectionChanged()
{
    // Set button states based on selected tab and selection
    QTableView *table = ui->tableView;
    if(!table->selectionModel())
        return;

    if(table->selectionModel()->hasSelection())
    {
        ui->copyOffer->setEnabled(true);
    }
    else
    {
        ui->copyOffer->setEnabled(false);
    }
}

void AcceptedOfferListPage::on_exportButton_clicked()
{
    // CSV is currently the only supported format
    QString filename = GUIUtil::getSaveFileName(
            this,
            tr("Export Offer Data"), QString(),
            tr("Comma separated file (*.csv)"));

    if (filename.isNull()) return;

    CSVModelWriter writer(filename);

    // name, column, role
    writer.setModel(proxyModel);
    writer.addColumn("Offer", OfferTableModel::Name, Qt::EditRole);
    writer.addColumn("Category", OfferTableModel::Category, Qt::EditRole);
    writer.addColumn("Title", OfferTableModel::Title, Qt::EditRole);
    writer.addColumn("Price", OfferTableModel::Price, Qt::EditRole);
    writer.addColumn("Quantity", OfferTableModel::Quantity, Qt::EditRole);
    writer.addColumn("Expiration Depth", OfferTableModel::ExpirationDepth, Qt::EditRole);
	writer.addColumn("Description", OfferTableModel::Description, Qt::EditRole);
    if(!writer.write())
    {
        QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
                              QMessageBox::Abort, QMessageBox::Abort);
    }
}

void AcceptedOfferListPage::contextualMenu(const QPoint &point)
{
    QModelIndex index = ui->tableView->indexAt(point);
    if(index.isValid()) {
        contextMenu->exec(QCursor::pos());
    }
}
bool AcceptedOfferListPage::handleURI(const QString& strURI, COffer* offerOut)
{
	return false;
}


text:
import React from 'react';
import axios from 'axios';

class LogIn extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      username: '',
      password: ''
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
  }

  handleSubmit(event) {
    // Attempt login
    axios.post('auth/users/logIn/', this.state)
      .then((response) => {
        // Clear input fields
        this.setState({username: '', password: ''});
        console.log(response.data.message);
      })
      .catch((error) => {
        console.log(error);
      });

    event.preventDefault();
  }

  handleUsernameChange(event) {
    this.setState({username: event.target.value});
  }

  handlePasswordChange(event) {
    this.setState({password: event.target.value});
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <h3> LogIn </h3>
        <label>
          <input
            type="text"
            name="username"
            placeholder="Username..."
            value={this.state.username}
            onChange={this.handleUsernameChange}
          />
          <input
            type="password"
            name="password"
            placeholder="Password..."
            value={this.state.password}
            onChange={this.handlePasswordChange}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default LogIn;


text:
Uživatelská příručka

Veřejný obsah

Nepřihlášený uživatel si může prohlížet písně a zpěvníky, které byly vlastníkem označeny
        jako veřejné. Může si číst i jejich hodnocení
        a komentáře,
        ale nemůže hodnocení ani komentář přidat.

Registrace a přihlášení

Aplikace kytarový zpěvník je běžná aplikace pracující na zavedených standardech.
        Registrace a přihlášení fungují zcela intuitivně tak, jak je uživatel zvyklý například z
        webových portálů emailových služeb.

Zapomenuté heslo

Při zapomenutí hesla si můžete na Váš email nechat poslat zprávu,
        ve které bude odkaz na nastavení nového hesla.

Procházení obsahu

Procházení obsahu funguje také stejným způsobem, na který je každý uživatel webových služeb zvyklý.
        Procházet lze pouze veřejný či svůj vlastní nebo převzatý
        obsah. Písně i zpěvníky je možné si zobrazit ve výpisu, kde se dají filrovat a řadit. Z tohoto výpisu
        je pak možné se prokliknout na detail písně či zpěvníku, nebo vytvořit nový obsah. Každý přihlášený
        uživatel může okomentovat libovolnou píseň či zpěvník,
        ke kterým má přístup.

Písně

Detail písně

Vlatník písně má možnost ji upravit či smazat, opatřit libovolným počtem soukromých tagů a přidat do zpěvníku.
        Pokud je píseň soukromá, může ji také nasdílet
        jinému uživateli. Jakýkoli jiný uživatel, který má k písni přístup, ji může
        ohodnotit a v případě, že ho zaujme, ji může
        převzít
        či zkopírovat.

Tvorba a úprava písně

Při přidávání nové písně či změně nějaké stávající má uživatel možnost nastavit její atributy
        popsané v následujícím odstavci.

Vlastnosti jako je název, autor, album a mnohé další, včetně
                tagů.
                Těchto vlastností je využíváno při vyhledávání a filtrování písní.

Nastavení, zda je píseň veřejná (uvidí ji všichni uživatelé), nebo soukromá.

Text písně a akordy je možné přidat několika způsoby. Buď lze využít importu
                ve formátu agama či s akordy v závorkách, nebo vložit samotný text (např. zkopírovaný
                z jiné stránky) a k nému následně přidat v editoru akordy. Ty lze přidat nad
                jakýkoliv znak (písmeno, mezeru, pomlčku) a je možné napsat jich více za sebou oddělené
                 mezerami, např. "E A D E". Tyto způsoby je možné kombinovat - když vložíte text
                např. ve fomátu agama, můžete následně upravit pozice jednotlivých akordů v editoru.

Transpozice písně

Píseň lze při zobrazení libovolně transponovat pomocí tlačítek + a -. Transponují se všechny akordy,
        které jsou správě napsané. Toto platí pouze pro aktuální zobrazení.
        Pro permanetní transpozici je potřeba upravit píseň samotnou, resp. její akordy.

Zpěvníky

Detail zpěvníku

Vlatník zpěvníku má možnost jej upravit či smazat, opatřit libovolným počtem soukromých tagů a přidat do něj
        písně. Pokud je zpěvník soukromý, může jej také nasdílet
        jinému uživateli. Jakýkoli jiný uživatel, který má ke zpěvníku přístup, jej může
        ohodnotit a v případě, že ho zaujme,
        ji může převzít
        či zkopírovat.

Tvorba zpěvníku

Při přidávání nového zpěvníku či změně nějakého stávajícího má uživatel možnost nastavit jeho atributy
        popsané v následujícím odstavci.

Název zpěvníku a tagy.
                Těchto vlastností je využíváno při vyhledávání a filtrování písní.

Nastavení, zda je zpěvník veřejný (uvidí ho všichni uživatelé), nebo soukromý.

Řazení písní do zpěvníku

Při práci s detailem zpěvníku má uživatel možnost do něj přidat libovolný počet vlastních či
        převzatých písní. Také je možné vytvořit píseň přímo
        ve zpěvníku. Každou píseň lze zařadit do libovolného počtu zpěvníků.
        Každá nově přidaná píseň je zařazena na konec zpěvníku.
        Uživatel má však možnost pořadí písní ve zpěvníku změnit podle svých potřeb.

Tagy

Základní atributy písně lze doplnit o veřejné či soukromé tagy.

Veřejné tagy se zobrazují každému, kdo má k danému obsahu přístup a může je přidávat pouze
                vlastník. Slouží především k dospecifikování dalších vlastností, jako je žánr apod.

Soukromé tagy se zobrazí pouze uživateli, kterému patří. Může je přidat vlastník nebo uživatel,
                který daný obsah převzal.
                Je možné je využít k jakémukoli soukromému označení obsahu.

Sdílení

Uživatel se může rozhodnout sdílet svůj soukromý obsah s jiným uživatelem.
        Pro tohoto uživatele se pak bude takto sdílená píseň či zpěvník chovat, jako by se jednalo o veřejný obsah.
        Cílový uživatel je o sdílení informován pomocí notifikace.

Převzetí

Jakýkoli veřejný či nasdílený obsah je možné převzít.
        Tato funkce umožňuje uživateli, který obsah převzal, opatřovat jej vlastními soukromými
        tagy a v případě písní také řadit do vlastních zpěvníků.
        Nemá však žádnou kontrolu nad obsahem převzaté písně či zpěvníku. Vlastník je o převzetí informován pomocí
        notifikace.
        V případě, že je převzatá píseň smazána či upravena, je na to uživatel upozorněn
        pomocí notifikace
        a má možnost si původní verzi písně zobrazit a případně zkopírovat.

Kopírování

Jakýkoli veřejný, nasdílený či už
        převzatý obsah je možné zkopírovat. Tím se vytvoří nová
        kopie dané písně či zpěvníku se stejnými základními atributy. Pokud uživatel zkopíruje obsah, který předtím
        převzal, převzetí se zruší a zkopírují se také soukromé tagy
        tohoto uživatele a v případě písní i příslušnost k jeho zpěvníkům. Se zkopírovaným obsahem uživatel zachází
        stejně, jako s vlastním. Vlastník je o vytvoření kopie informován pomocí
        notifikace.

Komentáře

Každou píseň a zpěvník, ke kterým má uživatel přístup, lze komentovat. Komentář lze upravit či smazat.
        Administrátor může komentář pro nevhodnost odstranit. Vlastník je o novém komentáři informován pomocí
        notifikace.

Hodnocení

Každou píseň a zpěvník, ke kterým má uživatel přístup, lze hodnotit. Hodnotí se počtem hvězdiček (1-5)
        a slovním komentářem. Hodnotit lze pouze jednou, je však možné své hodnocení upravit či smazat. Nelze
        hodnotit vlastní obsah. Administrátor může hodnocení pro nevhodnost komentáře odstranit. Vlastník je o novém
        hodnocení informován pomocí notifikace.

Přání

Uživatel si müže do svého seznamu přání přidávat záznamy o písních, které by si rád zařadil do zpěvníku,
        ale ještě nejsou v databázi. Při vzniku cizí veřejné písně, která se shoduje s jeho požadavky, je uživatel
        informován pomocí notifikace a následně může tuto
        píseň převzít
        či zkopírovat.
        Přání zůstává aktivní, dokud jej uživatel nasmaže.

Upozornění

Při každé akci, která se daného uživatele týká, je uživatel informován upozorněním. Všechna nepřečtená
        upozornění se zobrazují na hlavní liště. Upozornění se považují za nepřečtená, dokud je uživatel neproklikne
        nebo je všechná neoznačí jako přečtená.


text:
(function() {
    'use strict';

    angular
        .module('visualizer2App')
        .config(stateConfig);

    stateConfig.$inject = ['$stateProvider'];

    function stateConfig($stateProvider) {
        $stateProvider
        .state('file', {
            parent: 'entity',
            url: '/file?page&sort&search',
            data: {
                authorities: ['ROLE_USER'],
                pageTitle: 'Files'
            },
            views: {
                'content@': {
                    templateUrl: 'app/entities/file/files.html',
                    controller: 'FileController',
                    controllerAs: 'vm'
                }
            },
            params: {
                page: {
                    value: '1',
                    squash: true
                },
                sort: {
                    value: 'id,asc',
                    squash: true
                },
                search: null
            },
            resolve: {
                pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) {
                    return {
                        page: PaginationUtil.parsePage($stateParams.page),
                        sort: $stateParams.sort,
                        predicate: PaginationUtil.parsePredicate($stateParams.sort),
                        ascending: PaginationUtil.parseAscending($stateParams.sort),
                        search: $stateParams.search
                    };
                }],
            }
        })
        .state('file-detail', {
            parent: 'file',
            url: '/file/{id}',
            data: {
                authorities: ['ROLE_USER'],
                pageTitle: 'File'
            },
            views: {
                'content@': {
                    templateUrl: 'app/entities/file/file-detail.html',
                    controller: 'FileDetailController',
                    controllerAs: 'vm'
                }
            },
            resolve: {
                entity: ['$stateParams', 'File', function($stateParams, File) {
                    return File.get({id : $stateParams.id}).$promise;
                }],
                previousState: ["$state", function ($state) {
                    var currentStateData = {
                        name: $state.current.name || 'file',
                        params: $state.params,
                        url: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        })
        .state('file-detail.edit', {
            parent: 'file-detail',
            url: '/detail/edit',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/file/file-dialog.html',
                    controller: 'FileDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: ['File', function(File) {
                            return File.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('^', {}, { reload: false });
                }, function() {
                    $state.go('^');
                });
            }]
        })
        .state('file.new', {
            parent: 'file',
            url: '/new',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/file/file-dialog.html',
                    controller: 'FileDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: function () {
                            return {
                                type: null,
                                name: null,
                                shared: false,
                                id: null
                            };
                        }
                    }
                }).result.then(function() {
                    $state.go('file', null, { reload: 'file' });
                }, function() {
                    $state.go('file');
                });
            }]
        })
        .state('file.edit', {
            parent: 'file',
            url: '/{id}/edit',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/file/file-dialog.html',
                    controller: 'FileDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: ['File', function(File) {
                            return File.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('file', null, { reload: 'file' });
                }, function() {
                    $state.go('^');
                });
            }]
        })
        .state('file.delete', {
            parent: 'file',
            url: '/{id}/delete',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/file/file-delete-dialog.html',
                    controller: 'FileDeleteController',
                    controllerAs: 'vm',
                    size: 'md',
                    resolve: {
                        entity: ['File', function(File) {
                            return File.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('file', null, { reload: 'file' });
                }, function() {
                    $state.go('^');
                });
            }]
        });
    }

})();


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Client extends CI_Controller{
    const client_id = 'demoapp';
    const client_secret = 'demopass';
    function index()
    {
        $redirect_uri = urlencode('http://ci-oauth2.pigai.org/');//最后的反斜杠必不可少
        $data = compact('redirect_uri');
        $this->load->view('demo/header.html');
        $this->load->view('demo/index', $data);
        $this->load->view('demo/footer.html');
    }
    function receive_authcode()
    {
        $code = $this->input->get('code');
        $state = $this->input->get('state');
        $error = $this->input->get('error');
        $error_description = $this->input->get('error_description');

        $redirect_uri = 'http://ci-oauth2.pigai.org/client/receive_authcode';
        $redirect_uri = urlencode($redirect_uri);
        $this->load->view('demo/header.html');
        if($error AND $error_description){
            $data = compact('error_description');
        }else{
            $data = compact('code', 'redirect_uri');
        }
        $this->load->view('demo/receive_authcode', $data);
        $this->load->view('demo/footer.html');
    }
    function request_token(){
        //1.authorization code 2.user_credentials 3.refresh_token
        $grant_type = $this->input->get('grant_type');
        switch($grant_type){
            case 'authorization_code':
                $code = $this->input->get('code');
                $redirect_uri = $this->input->get('redirect_uri');
                $token = $this->getValidAccessTokenByCode($code, $redirect_uri);
                break;
            case 'client_credentials':
                $access_token = $this->get_token_by_client();
                $token = (object)array('access_token'=>$access_token, 'expires_in'=>7200);
                break;
            case 'password'://user_credentials
                $this->load->library('MY_Curl', '', 'curl');
                $data = array(
                    'grant_type'=>'password',
                    'client_id'=>'demoapp',
                    'client_secret'=>'demopass',
                    'username'=>'demouser',
                    'password'=>'testpass'
                );
                $this->curl->post(API_URI.'oauth2/access_token', $data);
                $token = $this->curl->response;
                break;
            case 'refresh_token':
                break;
            default:
                die('others');
                break;
        }
        $data = compact('token');
        $this->load->view('demo/header.html');
        $this->load->view('demo/request_token', $data);
        $this->load->view('demo/footer.html');
    }

    function receive_implicit_token()
    {
        $this->load->view('demo/header.html');
        $this->load->view('demo/receive_implicit_token');
        $this->load->view('demo/footer.html');
    }
    function request_resource()
    {
        $access_token = $this->input->get('token');
        $resource_api = API_URI.'users/friends?access_token='.$access_token;
        $res = $this->curl_getApi($resource_api);

        $data = compact('res', 'resource_api');
        $this->load->view('demo/header.html');
        $this->load->view('demo/request_resource', $data);
        $this->load->view('demo/footer.html');
    }
    //client_credentials方式获取token
    function demo_all_json()
    {
        $access_token = $this->get_token_by_client();
        $data = compact('access_token');
        $this->load->view('demo_all_json', $data);
    }
    private function get_token_by_client()
    {
        if(0){
            $token = $this->getValidAccessToken();
            $access_token = $token->access_token;
        }else{
            //cache token
            $this->load->driver('cache');
            if ( ! $access_token = $this->cache->file->get('access_token'))
            {
                $this->load->library('MY_Curl', '', 'curl');
                $this->curl->setBasicAuthentication(self::client_id, self::client_secret);
                $data = array(
                    'grant_type'=>'client_credentials'
                );
                $this->curl->post(API_URI.'oauth2/access_token', $data);
                $token = $this->curl->response;

                $this->cache->file->save('access_token', $token->access_token, $token->expires_in-60);
            }
        }
        return $access_token;
    }

    //-----------curl获取access_token----------------//
    /**
     * Set Basic Authentication
     *
     * @access public
     * @param  $username
     * @param  $password
     */
    function setBasicAuthentication($ch, $username, $password)
    {
        curl_setopt ($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt ($ch, CURLOPT_USERPWD, $username . ':' . $password);
    }

    /*
    * 从接口获取json数据
    *
    * $api - 远程url
    * return - array
    */
    function curl_getApi($api, $httpAuth=array())
    {
        if (!function_exists('curl_init')) {
            throw new Exception('server not install curl');
        }
        $ch = curl_init($api);//初始化一个cURL对象
        $timeout = 5;
        if(isset($httpAuth['username']) AND isset($httpAuth['password'])){
            setBasicAuthentication($ch, $httpAuth['username'], $httpAuth['password']);
        }
        curl_setopt ($ch, CURLOPT_URL, $api);//设置你需要抓取的url
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);//设置cURL参数,要求结果保存到字符串中还是输出到屏幕上
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $fileContents = curl_exec($ch);//运行cURL,请求网页,返回结果集或false
        curl_close($ch);//关闭URL请求
        return json_decode($fileContents);
    }

    /*
    * 向接口POST数据
    *
    * $api - 远程url
    * $data - 如:$data = 'pNUMBER='. urlencode(1391234).'&MESSAGE='.urlencode('curl and php').'&SUBMIT=Send';
    */
    function curl_postApi($api,$data, $httpAuth=array())
    {
        if (!function_exists('curl_init')) {
            throw new Exception('server not install curl');
        }
        $curlPost = $data;
        $timeout = 5;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api);
        //curl_setopt($ch, CURLOPT_HEADER, false);//是否显示header
        if(isset($httpAuth['username']) AND isset($httpAuth['password'])){
            $this->setBasicAuthentication($ch, $httpAuth['username'], $httpAuth['password']);
        }
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);//设置HTTP协议的POST方法
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);//设置POST的数据(可以为字符串或一维数组)
        $data = curl_exec($ch);
        curl_close($ch);
        return json_decode($data);
    }

    function setOpt()
    {
        $headr = array();
        $headr[] = 'Authorization: '.$douban_user_name.' '.$accesstoken;
        curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
    }

    /**
    *获取有效的access_token
    * @notice:1.新建空的access_token.txt文件,2.写入的内容格式:第一行为时间戳,第二行为有效的access_token
    *
    */
    function getValidAccessToken()
    {
        $dirname = __DIR__;
        $basename = 'access_token.txt';
        $filename = $dirname.'/'.$basename;

        $arr = file_exists($filename)? file($filename) : array();
        foreach($arr as $k=>$v){
            $arr[$k] = str_replace("\n",'',$v);
        }//替换换行符
        if($arr and $arr[0]){
            //有access_token,直接读取
            //判断token是否过期(提前15s)
            $diff = time()-$arr[0]+15;
            if($diff > $arr[2]){
                //更新access_token
                $accessToken = $this->updateAccessToken($filename);
                //echo "token已过期,已重新更新\n";
            }else{
                $accessToken = (object)array(
                    'access_token' => $arr[1],
                    'expires_in' => $arr[2],
                    'from_cache' => true,
                    'expires_rest' => $arr[2]-(time()-$arr[0])
                );
                //echo "直接从文件读取token\n";
            }
        }else{
            //无access_token,调微信接口生成新的,存入(/home/xfs/access_token.txt)
            $accessToken = $this->updateAccessToken($filename);
            //echo "首次生成token\n";
        }
        return $accessToken;
    }
    function getValidAccessTokenByCode($code, $redirect_uri)
    {
        //获取access_token
        //$api = 'http://oauth2.pigai.org/token.php?grant_type=client_credential';
        //$api = 'http://oauth2.pigai.org/token.php';
        $api = 'http://ci-oauth2.pigai.org/oauth2/access_token';
        $param = 'grant_type=authorization_code&code='.$code.'&redirect_uri='.urlencode($redirect_uri);
        $httpAuth = array(
            'username'=>'demoapp',
            'password'=>'demopass'
        );
        //$obj = curl_getApi($api, $httpAuth);
        $obj =$this->curl_postApi($api, $param, $httpAuth);
        if(!$obj) die('调用api超时');
        return $obj;
        if(isset($obj->access_token) AND isset($obj->expires_in)){
            $time = time();
            $accessToken = $obj->access_token;
            //TODO - expires_in 如何应对有效时间的调整?
            echo '过期时间:'.$obj->expires_in."\n";
        }else{
            //echo $obj->errcode.'错误:'.$obj->errmsg;
            echo $obj->error.'错误:'.$obj->error_description;
            echo "\n";exit;
        }
        return $accessToken;
    }
    //更新txt文件中access token
    function updateAccessToken($filename){
        //获取access_token
        //$api = 'http://oauth2.pigai.org/token.php?grant_type=client_credential';
        //$api = 'http://oauth2.pigai.org/token.php';
        $api = API_URI.'oauth2/access_token';
        $param = 'grant_type=client_credentials';
        $httpAuth = array(
            'username'=>'demoapp',
            'password'=>'demopass'
        );
        //$obj = curl_getApi($api, $httpAuth);
        $obj =$this->curl_postApi($api, $param, $httpAuth);
        if(!$obj) die('调用api超时');
        if(isset($obj->access_token) AND isset($obj->expires_in)){
            $time = time();
            $accessToken = $obj->access_token;
            //TODO - expires_in 如何应对有效时间的调整?
            //echo '过期时间:'.$obj->expires_in."\n";
            $writeIn = time()."\n".$accessToken."\n".$obj->expires_in;
            file_put_contents($filename,$writeIn);
        }
        return $obj;
    }
}


text: from hub import ThreadedHub


text:
void *linnea_core_malloc(size_t size);
void linnea_core_init(int argc, char **argv);
void linnea_core_print_diagnostics(struct state *state, const char * restrict format, ...);
void linnea_core_listen(struct state *state);
void linnea_core_accept_loop(struct state *state);
void *linnea_core_connection_start(void *arg);
void linnea_core_connection_recv(struct state *state, struct connection *connection);

#endif


text:
$:.unshift File.expand_path('../../lib', __FILE__)
require 'chef'
require 'chef/knife/sl_server_list'


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Markdownj" do
  it "converts strings to markdown" do
    Markdownj.to_html("a").should == "
a
\n"
  end
end


text:
module Fog
  module Compute
    class Google
      class Mock
        def set_target_https_proxy_url_map(_proxy_name, _url_map)
          # :no-coverage:
          Fog::Mock.not_implemented
          # :no-coverage:
        end
      end

      class Real
        def set_target_https_proxy_url_map(proxy_name, url_map)
          @compute.set_target_https_proxy_url_map(
            @project, proxy_name,
            ::Google::Apis::ComputeV1::UrlMapReference.new(
              url_map: url_map.class == String ? url_map : url_map.self_link
            )
          )
        end
      end
    end
  end
end


text:
module RapidApi
  module Auth
    module Concerns

      module JWTHelpers
        extend ActiveSupport::Concern

        included do

        end

        def jwt_encode(payload)
          Support::JWT.encode(payload)
        end

        def jwt_decode(token)
          Support::JWT.decode(token)
        end

      end

    end
  end
end


text:
<title>Architecture-Specific Protocol Details - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Remote-Protocol.html#Remote-Protocol" title="Remote Protocol">
<link rel="prev" href="General-Query-Packets.html#General-Query-Packets" title="General Query Packets">
<link rel="next" href="Tracepoint-Packets.html#Tracepoint-Packets" title="Tracepoint Packets">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Tracepoint Packets,
Previous: General Query Packets,
Up: Remote Protocol

E.5 Architecture-Specific Protocol Details

This section describes how the remote protocol is applied to specific
target architectures.  Also see Standard Target Features, for
details of XML target descriptions for each architecture.

ARM-Specific Protocol Details

MIPS-Specific Protocol Details


text:
module Spree
  module Stock
    class Coordinator
      attr_reader :order

      def initialize(order)
        @order = order
      end

      def packages
        packages = build_packages
        packages = prioritize_packages(packages)
        packages = estimate_packages(packages)
      end

      # Build packages as per stock location
      #
      # It needs to check whether each stock location holds at least one stock
      # item for the order. In case none is found it wouldn't make any sense
      # to build a package because it would be empty. Plus we avoid errors down
      # the stack because it would assume the stock location has stock items
      # for the given order
      #
      # Returns an array of Package instances
      def build_packages(packages = Array.new)
        StockLocation.active.each do |stock_location|
          next unless order.line_items.any? do |item|
            stock_location.stock_item(item.variant)
          end

          packer = build_packer(stock_location, order)
          packages += packer.packages
        end
        packages
      end

      private
      def prioritize_packages(packages)
        prioritizer = Prioritizer.new(order, packages)
        prioritizer.prioritized_packages
      end

      def estimate_packages(packages)
        estimator = Estimator.new(order)
        packages.each do |package|
          package.shipping_rates = estimator.shipping_rates(package)
        end
        packages
      end

      def build_packer(stock_location, order)
        Packer.new(stock_location, order, splitters(stock_location))
      end

      def splitters(stock_location)
        # extension point to return custom splitters for a location
        Rails.application.config.spree.stock_splitters
      end
    end
  end
end


text: Detects new posts to QC


text:
using SampleSystemWebAppIntegrationTest = ash::SystemWebAppIntegrationTest;

// Test that the Sample System Web App installs and launches correctly. Runs
// some spot checks on the manifest.
IN_PROC_BROWSER_TEST_P(SampleSystemWebAppIntegrationTest, SampleSystemWebApp) {
  const GURL url(ash::kChromeUISampleSystemWebAppURL);
  EXPECT_NO_FATAL_FAILURE(ExpectSystemWebAppValid(
      ash::SystemWebAppType::SAMPLE, url, "Sample System Web App"));
}

INSTANTIATE_SYSTEM_WEB_APP_MANAGER_TEST_SUITE_REGULAR_PROFILE_P(
    SampleSystemWebAppIntegrationTest);


text:
using System.ComponentModel.DataAnnotations;
namespace Sistem.Web.Models.ViewModel.Managements.MenuSection
{
    public class ProductProcessModel
    {
        [Required]
        public string ProductName { get; set; }
    }
}


text:
var LabelTestLayer = cc.Layer.extend({});

LabelTestLayer.create = function(){
    var retLayer = new LabelTestLayer();
    if(retLayer && retLayer.init()){
        return retLayer;
    }
    return null;
};

var LabelTestLayerLoader = cc.LayerLoader.extend({
    _createCCNode:function(parent,ccbReader){
        return LabelTestLayer.create();
    }
});


text:
using System;
using System.IO;
using Magix.Core;
using Magix.UX.Widgets;

namespace Magix.forms
{
	/*
	 * contains the label control
	 */
    internal sealed class LabelController : AttributeControlController
	{
		/*
		 * creates label control
		 */
		[ActiveEvent(Name = "magix.forms.controls.label")]
		private void magix_forms_controls_label(object sender, ActiveEventArgs e)
		{
            Node ip = Ip(e.Params);
			if (ShouldInspect(ip))
			{
				Inspect(ip);
				return;
			}

			Label ret = new Label();
            FillOutParameters(e.Params, ret);

            Node node = ip["_code"].Get<Node>();

            if (node.ContainsValue("value"))
				ret.Value = node["value"].Get<string>();

            if (node.ContainsValue("tag"))
				ret.Tag = node["tag"].Get<string>();

            if (node.ContainsValue("for"))
				ret.For = node["for"].Get<string>();

            ip["_ctrl"].Value = ret;
		}

		protected override void Inspect (Node node)
		{
            AppendInspectFromResource(
                node["inspect"],
                "Magix.forms",
                "Magix.forms.hyperlisp.inspect.hl",
                "[magix.forms.label-dox-start].value");
            AppendCodeFromResource(
                node,
                "Magix.forms",
                "Magix.forms.hyperlisp.inspect.hl",
                "[magix.forms.label-sample-start]");
            base.Inspect(node["magix.forms.create-web-part"]["controls"]["label"]);
            AppendInspectFromResource(
                node["inspect"],
                "Magix.forms",
                "Magix.forms.hyperlisp.inspect.hl",
                "[magix.forms.label-dox-end].value",
                true);
            AppendCodeFromResource(
                node["magix.forms.create-web-part"]["controls"]["label"],
                "Magix.forms",
                "Magix.forms.hyperlisp.inspect.hl",
                "[magix.forms.label-sample-end]");
		}
	}
}


text:
TrayNotificationWidget::TrayNotificationWidget(QPixmap pixmapIcon, QString headerText, QString messageText) : QWidget(0)
{
    setWindowFlags(
        #ifdef Q_WS_MAC
            Qt::SubWindow | // This type flag is the second point
        #else
            Qt::Tool |
        #endif
            Qt::FramelessWindowHint |
            Qt::WindowSystemMenuHint |
            Qt::WindowStaysOnTopHint
        );
    setAttribute(Qt::WA_NoSystemBackground, true);
    // set the parent widget's background to translucent
    setAttribute(Qt::WA_TranslucentBackground, true);

    //setAttribute(Qt::WA_ShowWithoutActivating, true);
    setFixedWidth(310);
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    // create a display widget for displaying child widgets
    QWidget* displayWidget = new QWidget;
    displayWidget->setStyleSheet(".QWidget { background-color: rgba(0, 0, 0, 75%); border-width: 1px; border-style: solid; border-radius: 10px; border-color: #555555; } .QWidget:hover { background-color: rgba(68, 68, 68, 75%); border-width: 2px; border-style: solid; border-radius: 10px; border-color: #ffffff; }");
    displayWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);

    QLabel* icon = new QLabel;
    icon->setPixmap(pixmapIcon);
    icon->setMaximumSize(32, 32);
    QLabel* header = new QLabel;
    header->setStyleSheet("QLabel { color: #ffffff; font-weight: bold; font-size: 12px; }");
    header->setText(headerText);
    header->setFixedWidth(200);
    header->setWordWrap(true);
    header->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    QTextEdit *message = new QTextEdit;
    message->setReadOnly(true);
    message->setFrameStyle(QFrame::NoFrame);
    message->setLineWrapMode(QTextEdit::WidgetWidth);
    message->setWordWrapMode(QTextOption::WrapAnywhere);
    QPalette pal = palette();
    pal.setColor(QPalette::Base, Qt::transparent);
    message->setPalette(pal);
    message->setStyleSheet("QTextEdit { color: #ffffff; font-size: 10px; }");
    message->setText(messageText);
    message->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    QVBoxLayout* vl = new QVBoxLayout;
    vl->addWidget(header);
    vl->addWidget(message);
    QHBoxLayout* displayMainLayout = new QHBoxLayout;
    displayMainLayout->addWidget(icon);
    displayMainLayout->addLayout(vl);

    displayWidget->setLayout(displayMainLayout);
    QHBoxLayout* containerLayout = new QHBoxLayout;
    containerLayout->addWidget(displayWidget);
    setLayout(containerLayout);
    show();
    resize(this->size().width(), (int)((message->document()->size().height() + header->height()) +70));

    timeout = new QTimer(this);
    connect(timeout, SIGNAL(timeout()), this, SLOT(fadeOut()));
    timeout->start(3000);
}

void TrayNotificationWidget::fadeOut()
{
    emit deleted(this);
    this->hide();
}


text:
define(["jquery", "mithril", 'models/agents/environments', "views/agents/environments_list_widget", "foundation.dropdown"], function ($, m, Environments, EnvironmentsListWidget) {
  describe("Environments List Widget", function () {
    var $root = $(  '#mithril-mount-point'), root = $root.get(0);

    beforeAll(function () {
      jasmine.Ajax.install();
      jasmine.Ajax.stubRequest(/\/api\/admin\/internal\/environments/).andReturn({
        "responseText": JSON.stringify(['Dev', 'Build', 'Testing', 'Deploy']),
        "status":       200
      });
      jasmine.Ajax.stubRequest(/\/api\/agents/).andReturn({"status": 304});

      var selectedAgents = [
        {
          uuid:         '1',
          environments: function () {
            return ['Dev', 'Testing'];
          }
        },
        {
          uuid:         '2',
          environments: function () {
            return ['Build', 'Testing'];
          }
        }
      ];
      Environments.init(selectedAgents);

      mount();
    });

    afterAll(function () {
      jasmine.Ajax.uninstall();
      unmount();
    });

    it('should contain all the environments checkbox', function () {
      var allEnvironments = $.find('.resources-items :checkbox');
      expect(allEnvironments).toHaveLength(4);
      expect(allEnvironments[0]).toHaveValue('Build');
      expect(allEnvironments[1]).toHaveValue('Deploy');
      expect(allEnvironments[2]).toHaveValue('Dev');
      expect(allEnvironments[3]).toHaveValue('Testing');
    });

    it('should check environments that are present on all the agents', function () {
      var allEnvironments = $.find('.resources-items :checkbox');
      expect(allEnvironments[3]).toHaveValue('Testing');
      expect(allEnvironments[3]).toBeChecked();
    });

    it('should select environments as indeterminate that are present on some of the agents', function () {
      var allEnvironments = $.find('.resources-items :checkbox');
      expect(allEnvironments[2]).toHaveValue('Dev');
      expect(allEnvironments[2].indeterminate).toBe(true);

      expect(allEnvironments[0]).toHaveValue('Build');
      expect(allEnvironments[0].indeterminate).toBe(true);
    });

    it('should uncheck environments that are not present on any the agents', function () {
      var allEnvironments = $.find('.resources-items :checkbox');
      expect(allEnvironments[1]).toHaveValue('Deploy');
      expect(allEnvironments[1]).not.toBeChecked();
      expect(allEnvironments[1].indeterminate).toBe(false);
    });

    var mount = function () {
      m.mount(root,
          m.component(EnvironmentsListWidget, {
            hideDropDown:         hideDropDown,
            dropDownReset:        dropDownReset,
            onEnvironmentsUpdate: onEnvironmentsUpdate,
          })
      );
      m.redraw(true);
    };

    var hideDropDown  = function () {
    };
    var dropDownReset = function () {
    };
    var onEnvironmentsUpdate = function () {
    };

    var unmount = function () {
      m.mount(root, null);
      m.redraw(true);
    };

  });
});


text:
CMCXmlParser._FilePathToXmlStringMap.Add(
	'glossary',
	'<?xml version=\"1.0\" encoding=\"utf-8\"?>' +
	'' +
	'    ' +
	'        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />' +
	'        <link href=\"SkinSupport/MadCap.css\" rel=\"stylesheet\" type=\"text/css\" />' +
	'        <title>Glossary</title>' +
	'        <link href=\"resources/stylesheets/webmodern.css\" rel=\"stylesheet\" type=\"text/css\" />' +
	'        ' +
	'    ' +
	'    ' +
	'
' +
	'
' +
	'
' +
	'                    My Term' +
	'                    ' +
	'                    ' +
	'
' +
	'
My definition
' +
	'
' +
	'
' +
	'

' +
	'        ' +
	'    ' +
	''
);


text:
package br.com.cmabreu.webomt.persistence.services;

import java.util.List;

import br.com.cmabreu.webomt.persistence.entity.Federation;
import br.com.cmabreu.webomt.persistence.entity.User;
import br.com.cmabreu.webomt.persistence.exceptions.DatabaseConnectException;
import br.com.cmabreu.webomt.persistence.exceptions.InsertException;
import br.com.cmabreu.webomt.persistence.exceptions.NotFoundException;
import br.com.cmabreu.webomt.persistence.exceptions.UpdateException;
import br.com.cmabreu.webomt.persistence.repository.FederationRepository;

public class FederationService {
	private FederationRepository rep;

	public FederationService() throws DatabaseConnectException {
		this.rep = new FederationRepository();
	}

	public void newTransaction() {
		if( !rep.isOpen() ) {
			rep.newTransaction();
		}
	}

	public int insertFederation(Federation federation) throws InsertException {
		return rep.insertFederation( federation );
	}

	public void insertFederationList( List<Federation> federations ) throws InsertException {
		rep.insertFederationList( federations );
	}

	public List<Federation> getList( User owner ) throws NotFoundException {
		List<Federation> federations = rep.getList( owner );
		return federations;
	}

	public Federation getFederation( int idFederation ) throws NotFoundException {
		return rep.getFederation(idFederation);
	}

	public void updateFederation( Federation federation ) throws UpdateException, NotFoundException {
		rep.updateFederation(federation);
	}

}


text:
// +build !experimental

package experimental

type MyInterface interface {
	BaseInterface
}


text:
{% extends "frontend/base.html" %}
{% block title %} new tripcode keypair {% endblock %}
{% block content %}
<pre class="tripcode-outer">public key: {{pk}}
secret key: {{sk}}
</pre>
{% endblock %}


text:
// Copyright 2017 The Bazel Authors. 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.
package com.google.devtools.build.lib.analysis;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.stringtemplate.ExpansionException;
import com.google.devtools.build.lib.analysis.stringtemplate.TemplateContext;
import com.google.devtools.build.lib.analysis.stringtemplate.TemplateExpander;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.shell.ShellUtils;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;

/**
 * Expansion of strings and string lists by replacing make variables and $(location) functions.
 */
public final class Expander {

  private final RuleContext ruleContext;
  private final TemplateContext templateContext;
  @Nullable ImmutableMap<Label, ImmutableCollection<Artifact>> labelMap;

  Expander(RuleContext ruleContext, TemplateContext templateContext) {
    this(ruleContext, templateContext, /* labelMap= */ null);
  }

  Expander(
      RuleContext ruleContext,
      TemplateContext templateContext,
      @Nullable ImmutableMap<Label, ImmutableCollection<Artifact>> labelMap) {
    this.ruleContext = ruleContext;
    this.templateContext = templateContext;
    this.labelMap = labelMap;
  }

  /**
   * Returns a new instance that also expands locations using the default configuration of {@link
   * LocationTemplateContext}.
   */
  private Expander withLocations(boolean execPaths, boolean allowData) {
    TemplateContext newTemplateContext =
        new LocationTemplateContext(
            templateContext, ruleContext, labelMap, execPaths, allowData, false);
    return new Expander(ruleContext, newTemplateContext, labelMap);
  }

  /**
   * Returns a new instance that also expands locations, passing {@code allowData} to the underlying
   * {@link LocationTemplateContext}.
   */
  public Expander withDataLocations() {
    return withLocations(false, true);
  }

  /**
   * Returns a new instance that also expands locations, passing {@code allowData} and {@code
   * execPaths} to the underlying {@link LocationTemplateContext}.
   */
  public Expander withDataExecLocations() {
    return withLocations(true, true);
  }

  /**
   * Returns a new instance that also expands locations, passing the given location map, as well as
   * {@code execPaths} to the underlying {@link LocationTemplateContext}.
   */
  public Expander withExecLocations(
      ImmutableMap<Label, ImmutableCollection<Artifact>> locations, boolean windowsPath) {
    TemplateContext newTemplateContext =
        new LocationTemplateContext(
            templateContext, ruleContext, locations, true, false, windowsPath);
    return new Expander(ruleContext, newTemplateContext);
  }

  public Expander withExecLocations(ImmutableMap<Label, ImmutableCollection<Artifact>> locations) {
    return withExecLocations(locations, false);
  }

  /**
   * Expands the given value string, tokenizes it, and then adds it to the given list. The attribute
   * name is only used for error reporting.
   */
  public void tokenizeAndExpandMakeVars(
      List<String> result,
      String attributeName,
      String value) {
    expandValue(result, attributeName, value, /* shouldTokenize */ true);
  }

  /** Expands make variables and $(location) tags in value, and optionally tokenizes the result. */
  private void expandValue(
      List<String> tokens, String attributeName, String value, boolean shouldTokenize) {
    value = expand(attributeName, value);
    if (shouldTokenize) {
      try {
        ShellUtils.tokenize(tokens, value);
      } catch (ShellUtils.TokenizationException e) {
        ruleContext.attributeError(attributeName, e.getMessage());
      }
    } else {
      tokens.add(value);
    }
  }

  /**
   * Returns the string "expression" after expanding all embedded references to
   * "Make" variables.  If any errors are encountered, they are reported, and
   * "expression" is returned unchanged.
   *
   * @param attributeName the name of the attribute
   * @return the expansion of "expression".
   */
  public String expand(String attributeName) {
    return expand(attributeName, ruleContext.attributes().get(attributeName, Type.STRING));
  }

  /**
   * Returns the string "expression" after expanding all embedded references to
   * "Make" variables.  If any errors are encountered, they are reported, and
   * "expression" is returned unchanged.
   *
   * @param attributeName the name of the attribute from which "expression" comes;
   *     used for error reporting.
   * @param expression the string to expand.
   * @return the expansion of "expression".
   */
  public String expand(@Nullable String attributeName, String expression) {
    try {
      return TemplateExpander.expand(expression, templateContext);
    } catch (ExpansionException e) {
      if (attributeName == null) {
        ruleContext.ruleError(e.getMessage());
      } else {
        ruleContext.attributeError(attributeName, e.getMessage());
      }
      return expression;
    }
  }

  /**
   * Expands all the strings in the given list, optionally tokenizing them after expansion. The
   * attribute name is only used for error reporting.
   */
  private ImmutableList<String> expandAndTokenizeList(
      String attrName, List<String> values, boolean shouldTokenize) {
    List<String> variables = new ArrayList<>();
    for (String variable : values) {
      expandValue(variables, attrName, variable, shouldTokenize);
    }
    return ImmutableList.copyOf(variables);
  }

  /**
   * Obtains the value of the attribute, expands all values, and returns the resulting list. If the
   * attribute does not exist or is not of type {@link Type#STRING_LIST}, then this method throws
   * an error.
   */
  public ImmutableList<String> list(String attrName) {
    return list(attrName, ruleContext.attributes().get(attrName, Type.STRING_LIST));
  }

  /**
   * Expands all the strings in the given list. The attribute name is only used for error reporting.
   */
  public ImmutableList<String> list(String attrName, List<String> values) {
    return expandAndTokenizeList(attrName, values, /* shouldTokenize */ false);
  }

  /**
   * Obtains the value of the attribute, expands, and tokenizes all values. If the attribute does
   * not exist or is not of type {@link Type#STRING_LIST}, then this method throws an error.
   */
  public ImmutableList<String> tokenized(String attrName) {
    return tokenized(attrName, ruleContext.attributes().get(attrName, Type.STRING_LIST));
  }

  /**
   * Expands all the strings in the given list, and tokenizes them after expansion. The attribute
   * name is only used for error reporting.
   */
  public ImmutableList<String> tokenized(String attrName, List<String> values) {
    return expandAndTokenizeList(attrName, values, /* shouldTokenize */ true);
  }

  /**
   * If the string consists of a single variable, returns the expansion of that variable. Otherwise,
   * returns null. Syntax errors are reported.
   *
   * @param attrName the name of the attribute from which "expression" comes; used for error
   *     reporting.
   * @param expression the string to expand.
   * @return the expansion of "expression", or null.
   */
  @Nullable
  public String expandSingleMakeVariable(String attrName, String expression) {
    try {
      return TemplateExpander.expandSingleVariable(expression, templateContext);
    } catch (ExpansionException e) {
      ruleContext.attributeError(attrName, e.getMessage());
      return expression;
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
     <dimen name="media_screen_thumb_size">115dp</dimen>

    <dimen name="media_screen_filter_photo_video_width">84dp</dimen>
    <dimen name="media_screen_filter_photo_width">42dp</dimen>
</resources>


text:
<?php
class Database
{
	private static $dbName = 'myapp';
	private static $dbHost = 'localhost';
	private static $dbUsername = 'myuser';
	private static $dbUserPassword = 'myuser';

	private static $cont  = null;

	public function __construct() {
		exit('Init function is not allowed');
	}

	public static function connect()
	{
	     // One connection through whole application
       if (self::$cont == null)
       {
        try
        {
          self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
        }
        catch(PDOException $e)
        {
          die($e->getMessage());
        }
       }
       return self::$cont;
	}

	public static function disconnect()
	{
		self::$cont = null;
	}
}
?>


text:
package mmm.comercial.centro.pojo;

public class Empleado extends Usuario {

	private int id;

	public Empleado() {
		super();
		super.setRole("EMP");
		super.setRuta_imagen("resources/images/empleado/default.png");
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}