text:
package org.dcm4chex.archive.ejb.entity;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.RemoveException;

import org.apache.log4j.Logger;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmDecodeParam;
import org.dcm4che.dict.Tags;
import org.dcm4cheri.util.DatasetUtils;
import org.dcm4cheri.util.StringUtils;
import org.dcm4chex.archive.ejb.interfaces.InstanceLocal;
import org.dcm4chex.archive.ejb.interfaces.StudyLocal;

/**

/**
 * @ejb.bean
 *  name="Series"
 *  type="CMP"
 *  view-type="local"
 *  primkey-field="pk"
 *  local-jndi-name="ejb/Series"
 *
 * @jboss.container-configuration
 *  name="Standard CMP 2.x EntityBean with cache invalidation"
 *
 * @ejb.transaction
 *  type="Required"
 *
 * @ejb.persistence
 *  table-name="series"
 *
 * @jboss.entity-command
 *  name="hsqldb-fetch-key"
 *
 * @ejb.finder
 *  signature="Collection findAll()"
 *  query="SELECT OBJECT(a) FROM Series AS a"
 *  transaction-type="Supports"
 *
 * @ejb.finder
 *  signature="org.dcm4chex.archive.ejb.interfaces.SeriesLocal findBySeriesIuid(java.lang.String uid)"
 *  query="SELECT OBJECT(a) FROM Series AS a WHERE a.seriesIuid = ?1"
 *  transaction-type="Supports"
 *
 * @author Gunter Zeilinger
 *
 */
public abstract class SeriesBean implements EntityBean {

    private static final Logger log = Logger.getLogger(SeriesBean.class);
    private Set retrieveAETSet;

    /**
     * Auto-generated Primary Key
     *
     * @ejb.interface-method
     * @ejb.pk-field
     * @ejb.persistence
     *  column-name="pk"
     * @jboss.persistence
     *  auto-increment="true"
     *
     */
    public abstract Integer getPk();

    public abstract void setPk(Integer pk);

    /**
     * Series Instance UID
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="series_iuid"
     */
    public abstract String getSeriesIuid();

    public abstract void setSeriesIuid(String uid);

    /**
     * Series Number
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="series_no"
     */
    public abstract String getSeriesNumber();

    public abstract void setSeriesNumber(String no);

    /**
     * Modality
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="modality"
     */
    public abstract String getModality();

    public abstract void setModality(String md);

    /**
     * PPS Start Datetime
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="pps_start"
     */
    public abstract java.util.Date getPpsStartDateTime();

    /**
     * Number Of Series Related Instances
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="num_instances"
     *
     */
    public abstract int getNumberOfSeriesRelatedInstances();

    public abstract void setNumberOfSeriesRelatedInstances(int num);

    public abstract void setPpsStartDateTime(java.util.Date datetime);

    /**
     * Encoded Series Dataset
     *
     * @ejb.persistence
     *  column-name="series_attrs"
     *
     */
    public abstract byte[] getEncodedAttributes();

    public abstract void setEncodedAttributes(byte[] attr);

    /**
     * Retrieve AETs
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="retrieve_aets"
     */
    public abstract String getRetrieveAETs();

    public abstract void setRetrieveAETs(String aets);

    /**
     * Instance Availability
     *
     * @ejb.interface-method
     * @ejb.persistence
     *  column-name="availability"
     */
    public abstract int getAvailability();

    public abstract void setAvailability(int availability);

    /**
     * @ejb.relation
     *  name="study-series"
     *  role-name="series-of-study"
     *  cascade-delete="yes"
     *
     * @jboss:relation
     *  fk-column="study_fk"
     *  related-pk-field="pk"
     *
     * @param study study of this series
     */
    public abstract void setStudy(StudyLocal study);

    /**
     * @ejb.interface-method view-type="local"
     *
     * @return study of this series
     */
    public abstract StudyLocal getStudy();

    /**
     * @ejb.interface-method view-type="local"
     *
     * @param series all instances of this series
     */
    public abstract void setInstances(java.util.Collection series);

    /**
     * @ejb.interface-method view-type="local"
     * @ejb.relation
     *  name="series-instance"
     *  role-name="series-has-instance"
     *
     * @return all instances of this series
     */
    public abstract java.util.Collection getInstances();

    public void ejbLoad() {
        retrieveAETSet = null;
    }

    /**
     * Create series.
     *
     * @ejb.create-method
     */
    public Integer ejbCreate(Dataset ds, StudyLocal study)
        throws CreateException {
        retrieveAETSet = null;
        setAttributes(ds);
        return null;
    }

    public void ejbPostCreate(Dataset ds, StudyLocal study)
        throws CreateException {
        setStudy(study);
        study.addModalityInStudy(getModality());
        study.incNumberOfStudyRelatedSeries(1);
        log.info("Created " + prompt());
    }

    public void ejbRemove() throws RemoveException {
        log.info("Deleting " + prompt());
        StudyLocal study = getStudy();
        if (study != null) {
            // study.updateModalitiesInStudy();?
            study.incNumberOfStudyRelatedSeries(-1);
            study.incNumberOfStudyRelatedInstances(
                -getNumberOfSeriesRelatedInstances());
        }
    }

    /**
     *
     * @ejb.interface-method
     */
    public void setAttributes(Dataset ds) {
        setSeriesIuid(ds.getString(Tags.SeriesInstanceUID));
        setSeriesNumber(ds.getString(Tags.SeriesNumber));
        setModality(ds.getString(Tags.Modality));
        setPpsStartDateTime(
            ds.getDateTime(Tags.PPSStartDate, Tags.PPSStartTime));
        setEncodedAttributes(
            DatasetUtils.toByteArray(ds, DcmDecodeParam.EVR_LE));
    }

    /**
     * @ejb.interface-method
     */
    public Dataset getAttributes() {
        return DatasetUtils.fromByteArray(
            getEncodedAttributes(),
            DcmDecodeParam.EVR_LE);
    }

    /**
     * @ejb.interface-method
     */
    public void incNumberOfSeriesRelatedInstances(int inc) {
        setNumberOfSeriesRelatedInstances(
            getNumberOfSeriesRelatedInstances() + inc);
        getStudy().incNumberOfStudyRelatedInstances(inc);
    }

    /**
     * @ejb.interface-method
     */
    public Set getRetrieveAETSet() {
        return Collections.unmodifiableSet(retrieveAETSet());
    }

    private Set retrieveAETSet() {
        if (retrieveAETSet == null) {
            retrieveAETSet = new HashSet();
            String aets = getRetrieveAETs();
            if (aets != null) {
                retrieveAETSet.addAll(
                    Arrays.asList(StringUtils.split(aets, '\\')));
            }
        }
        return retrieveAETSet;
    }

    /**
     * @ejb.interface-method
     */
    public boolean addRetrieveAET(String aet) {
        log.debug(
            "series[pk="
                + getPk()
                + "]: update retrieveAETs "
                + getRetrieveAETs()
                + " with "
                + aet);
        if (retrieveAETSet().contains(aet)) {
            log.debug(
                "series[pk="
                    + getPk()
                    + "]: no update of retrieveAETs "
                    + retrieveAETSet()
                    + " necessary");
            return false;
        }
        if (!areAllInstancesRetrieveableFrom(aet)) {
            log.debug(
                "series[pk="
                    + getPk()
                    + "]: not all Instances retrieveable from "
                    + aet);
            return false;
        }
        retrieveAETSet().add(aet);
        String prev = getRetrieveAETs();
        if (prev == null || prev.length() == 0) {
            setRetrieveAETs(aet);
        } else {
            setRetrieveAETs(prev + '\\' + aet);
        }
        log.debug(
            "series[pk="
                + getPk()
                + "]: updated retrieveAETs to "
                + getRetrieveAETs());
        return true;
    }

    private boolean areAllInstancesRetrieveableFrom(String aet) {
        Collection c = getInstances();
        for (Iterator it = c.iterator(); it.hasNext();) {
            InstanceLocal instance = (InstanceLocal) it.next();
            if (!instance.getRetrieveAETSet().contains(aet)) {
                return false;
            }
        }
        return true;
    }

    /**
     *
     * @ejb.interface-method
     */
    public boolean updateAvailability() {
        Collection c = getInstances();
        int availability = 0;
        for (Iterator it = c.iterator(); it.hasNext();) {
            InstanceLocal instance = (InstanceLocal) it.next();
            availability = Math.max(availability, instance.getAvailability());
        }
        if (availability != getAvailability()) {
            return false;
        }
        return true;
    }

    /**
     *
     * @ejb.interface-method
     */
    public String asString() {
        return prompt();
    }

    private String prompt() {
        return "Series[pk="
            + getPk()
            + ", uid="
            + getSeriesIuid()
            + ", study->"
            + getStudy()
            + "]";
    }

}


text:
//$Id: CompositeIdTest.java 6791 2005-05-16 02:19:13Z oneovthafew $
package org.hibernate.test.cid;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.test.TestCase;

/**
 * @author Gavin King
 */
public class CompositeIdTest extends TestCase {

	public CompositeIdTest(String str) {
		super(str);
	}

	public void testQuery() {
		Session s = openSession();
		Transaction t = s.beginTransaction();
		s.createQuery("from LineItem ol where ol.order.id.customerId = 'C111'").list();
		t.commit();
		s.close();
	}

	public void testCompositeIds() {
		Session s = openSession();
		Transaction t = s.beginTransaction();

		Product p = new Product();
		p.setProductId("A123");
		p.setDescription("nipple ring");
		p.setPrice( new BigDecimal(1.0) );
		p.setNumberAvailable(1004);
		s.persist(p);

		Product p2 = new Product();
		p2.setProductId("X525");
		p2.setDescription("nose stud");
		p2.setPrice( new BigDecimal(3.0) );
		p2.setNumberAvailable(105);
		s.persist(p2);

		Customer c = new Customer();
		c.setAddress("St Kilda Rd, MEL, 3000");
		c.setName("Virginia");
		c.setCustomerId("C111");
		s.persist(c);

		Order o = new Order(c);
		o.setOrderDate( Calendar.getInstance() );
		LineItem li = new LineItem(o, p);
		li.setQuantity(2);

		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		o = (Order) s.get( Order.class, new Order.Id("C111", 0) );
		assertEquals( o.getTotal().intValue(), 2 );
		o.getCustomer().getName();
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		s.createQuery("from Customer c left join fetch c.orders o left join fetch o.lineItems li left join fetch li.product p").list();
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		s.createQuery("from Order o left join fetch o.lineItems li left join fetch li.product p").list();
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		Iterator iter = s.createQuery("select o.id, li.id from Order o join o.lineItems li").list().iterator();
		while ( iter.hasNext() ) {
			Object[] stuff = (Object[]) iter.next();
			assertTrue(stuff.length==2);
		}
		iter = s.createQuery("from Order o join o.lineItems li").iterate();
		while ( iter.hasNext() ) {
			Object[] stuff = (Object[]) iter.next();
			assertTrue(stuff.length==2);
		}
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		c = (Customer) s.get( Customer.class, "C111" );
		Order o2 = new Order(c);
		o2.setOrderDate( Calendar.getInstance() );
		s.flush();
		LineItem li2 = new LineItem(o2, p2);
		li2.setQuantity(5);
		List bigOrders = s.createQuery("from Order o where o.total>10.0").list();
		assertEquals( bigOrders.size(), 1 );
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		s.createQuery("delete from LineItem").executeUpdate();
		s.createQuery("delete from Order").executeUpdate();
		s.createQuery("delete from Customer").executeUpdate();
		s.createQuery("delete from Product").executeUpdate();
		t.commit();
		s.close();
	}

	public void testNonLazyFetch() {
		Session s = openSession();
		Transaction t = s.beginTransaction();

		Product p = new Product();
		p.setProductId("A123");
		p.setDescription("nipple ring");
		p.setPrice( new BigDecimal(1.0) );
		p.setNumberAvailable(1004);
		s.persist(p);

		Product p2 = new Product();
		p2.setProductId("X525");
		p2.setDescription("nose stud");
		p2.setPrice( new BigDecimal(3.0) );
		p2.setNumberAvailable(105);
		s.persist(p2);

		Customer c = new Customer();
		c.setAddress("St Kilda Rd, MEL, 3000");
		c.setName("Virginia");
		c.setCustomerId("C111");
		s.persist(c);

		Order o = new Order(c);
		o.setOrderDate( Calendar.getInstance() );
		LineItem li = new LineItem(o, p);
		li.setQuantity(2);

		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		o = (Order) s.get( Order.class, new Order.Id("C111", 0) );
		assertEquals( o.getTotal().intValue(), 2 );
		o.getCustomer().getName();
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		o = (Order) s.createQuery("from Order o left join fetch o.lineItems li left join fetch li.product p").uniqueResult();
		assertTrue( Hibernate.isInitialized( o.getLineItems() ) );
		li = (LineItem) o.getLineItems().iterator().next();
		assertTrue( Hibernate.isInitialized( li ) );
		assertTrue( Hibernate.isInitialized( li.getProduct() ) );
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		o = (Order) s.createQuery("from Order o").uniqueResult();
		assertTrue( Hibernate.isInitialized( o.getLineItems() ) );
		li = (LineItem) o.getLineItems().iterator().next();
		assertTrue( Hibernate.isInitialized( li ) );
		assertFalse( Hibernate.isInitialized( li.getProduct() ) );
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		s.createQuery("delete from LineItem").executeUpdate();
		s.createQuery("delete from Order").executeUpdate();
		s.createQuery("delete from Customer").executeUpdate();
		s.createQuery("delete from Product").executeUpdate();
		t.commit();
		s.close();

	}

	public void testMultipleCollectionFetch() {
		Session s = openSession();
		Transaction t = s.beginTransaction();

		Product p = new Product();
		p.setProductId("A123");
		p.setDescription("nipple ring");
		p.setPrice( new BigDecimal(1.0) );
		p.setNumberAvailable(1004);
		s.persist(p);

		Product p2 = new Product();
		p2.setProductId("X525");
		p2.setDescription("nose stud");
		p2.setPrice( new BigDecimal(3.0) );
		p2.setNumberAvailable(105);
		s.persist(p2);

		Customer c = new Customer();
		c.setAddress("St Kilda Rd, MEL, 3000");
		c.setName("Virginia");
		c.setCustomerId("C111");
		s.persist(c);

		Order o = new Order(c);
		o.setOrderDate( Calendar.getInstance() );
		LineItem li = new LineItem(o, p);
		li.setQuantity(2);
		LineItem li2 = new LineItem(o, p2);
		li2.setQuantity(3);

		Order o2 = new Order(c);
		o2.setOrderDate( Calendar.getInstance() );
		LineItem li3 = new LineItem(o2, p);
		li3.setQuantity(1);
		LineItem li4 = new LineItem(o2, p2);
		li4.setQuantity(1);

		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		c = (Customer) s.createQuery("from Customer c left join fetch c.orders o left join fetch o.lineItems li left join fetch li.product p").uniqueResult();
		assertTrue( Hibernate.isInitialized( c.getOrders() ) );
		assertEquals( c.getOrders().size(), 2 );
		assertTrue( Hibernate.isInitialized( ( (Order) c.getOrders().get(0) ).getLineItems() ) );
		assertTrue( Hibernate.isInitialized( ( (Order) c.getOrders().get(1) ).getLineItems() ) );
		assertEquals( ( (Order) c.getOrders().get(0) ).getLineItems().size(), 2 );
		assertEquals( ( (Order) c.getOrders().get(1) ).getLineItems().size(), 2 );
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		s.createQuery("delete from LineItem").executeUpdate();
		s.createQuery("delete from Order").executeUpdate();
		s.createQuery("delete from Customer").executeUpdate();
		s.createQuery("delete from Product").executeUpdate();
		t.commit();
		s.close();
	}

	protected String[] getMappings() {
		return new String[] {
				"cid/Customer.hbm.xml",
				"cid/Order.hbm.xml",
				"cid/LineItem.hbm.xml",
				"cid/Product.hbm.xml"
		};
	}

	public static Test suite() {
		return new TestSuite(CompositeIdTest.class);
	}

}

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json.Linq;
using System.Linq;

namespace EDDiscovery.EliteDangerous.JournalEvents
{
    //When Written: when repairing the ship
    //Parameters:
    //•	Item: all, wear, hull, paint, or name of module
    //•	Cost: cost of repair
    public class JournalRepairAll : JournalEntry
    {
        public JournalRepairAll(JObject evt) : base(evt, JournalTypeEnum.RepairAll)
        {
            Cost = JSONHelper.GetLong(evt["Cost"]);

        }
        public long Cost { get; set; }

        public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.repairall; } }

        public void Ledger(EDDiscovery2.DB.MaterialCommoditiesLedger mcl, DB.SQLiteConnectionUser conn)
        {
            mcl.AddEvent(Id, EventTimeUTC, EventTypeID, "", -Cost);
        }

    }
}


text:
<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

    <style name="FixedHeightBox">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:minHeight">@dimen/demo_view_height</item>
        <item name="android:layout_margin">@dimen/demo_view_margin</item>
        <item name="android:gravity">left|center_vertical</item>
        <item name="android:padding">@dimen/demo_view_margin</item>
        <item name="android:text">@string/bacon</item>
    </style>

</resources>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. K. Ned. Akad. Wet. , Ser. C, Biol. Med. Sci. 69: 350 (1966)

#### Original name
Stemonitis inconspicua Nann.-Bremek., 1966

### Remarks
null


text:
$(function() {
    $('.collapse').on('shown.bs.collapse', function() {
         $(this).parent().find(".glyphicon-chevron-left").removeClass("glyphicon-chevron-left").addClass("glyphicon-chevron-down");

    }).on('hidden.bs.collapse', function() {
	$(this).parent().find(".glyphicon-chevron-down").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-left");
    });

//    $('#vesselModal').bind("DOMSubtreeModified",function() {
	 // alert('changed');

//       $('#id_predefined_conditions').on('click', function() {
//          alert('fff');
//       });
//    });
});
function select_condition(input_id) {

     var input_value = $('#'+input_id).val();

     $.ajax({url: "/condition-predefined/"+input_value+"/", contentType: "application/json", dataType: "json", success: function(result) {
         $('#id_condition').val(result['0']['fields']['condition']);
     }});

     $('#'+input_id).val('');

}

function close_popup() {
   $('#overtop').hide();

}

function download_table_as_csv(table_id, separator = ',') {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
            // Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
            data = data.replace(/"/g, '""');
            // Push escaped string
            row.push('"' + data + '"');
        }
        csv.push(row.join(separator));
    }
    var csv_string = csv.join('\n');
    // Download it
    var filename = 'csv_export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}


text:
using namespace System;

namespace Examples {
  class Program {
  public:
    // The main entry point for the application.
    static void Main() {
      Console::WriteLine("The number of processors on this computer is {0}.", Environment::ProcessorCount);
    }
  };
}

startup_(Examples::Program);

// This example produces results similar to the following:
//
// The number of processors on this computer is 8.


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

    <title>All Classes</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

CBAnalytics

CBAnalytics.CBCustomEventType

CBAnalytics.CBIAPPurchaseInfo

CBAnalytics.CBIAPType

CBAnalytics.CBLevelType

CBAnalytics.CBMiscRevenueGeneratingEventType

CBError

CBError.CBClickError

CBError.CBImpressionError

CBError.CBInternalError

CBImpressionActivity

CBInPlay

CBLocation

Chartboost

Chartboost.CBFramework

Chartboost.CBMediation

ChartboostActivity

ChartboostDelegate


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Aspose.Cells.Examples.CSharp.Articles.ManagingWorkbooksWorksheets
{
    public class CheckIfPasswordProtected
    {
        public static void Run()
        {
            //Source directory
            string sourceDir = RunExamples.Get_SourceDirectory();

            // Create an instance of Workbook and load a spreadsheet
            var book = new Workbook(sourceDir + "sampleCheckIfPasswordProtected.xlsx");

            // Access the protected Worksheet
            var sheet = book.Worksheets[0];

            // Check if Worksheet is password protected
            if (sheet.Protection.IsProtectedWithPassword)
            {
                Console.WriteLine("Worksheet is Password Protected");
            }
            else
            {
                Console.WriteLine("Worksheet is Not Password Protected");
            }

            Console.WriteLine("CheckIfPasswordProtected executed successfully.");
        }
    }
}


text:
@interface MenuButton : ToolbarButton {
 @private
  base::scoped_nsobject<NSMenu> attachedMenu_;
  BOOL openMenuOnClick_;
  BOOL openMenuOnRightClick_;
  base::scoped_nsobject<NSPopUpButtonCell> popUpCell_;
}

// The menu to display. Note that it should have no (i.e., a blank) title and
// that the 0-th entry should be blank (and won't be displayed). (This is
// because we use a pulldown list, for which Cocoa uses the 0-th item as "title"
// in the button. This might change if we ever switch to a pop-up. Our direct
// use of the given NSMenu object means that the one can set and use NSMenu's
// delegate as usual.)
@property(retain, nonatomic) IBOutlet NSMenu* attachedMenu;

// Whether or not to open the menu when the button is clicked. Otherwise, the
// menu will only be opened when clicked and held.
@property(assign, nonatomic) BOOL openMenuOnClick;

// Whether or not to open the menu when the right button is clicked.
@property(assign, nonatomic) BOOL openMenuOnRightClick;

// Returns the rectangle that menus are anchored at. Can be overridden by
// subclasses, returns -bounds by default.
- (NSRect)menuRect;

@end  // @interface MenuButton

// Available for subclasses.
@interface MenuButton (Protected)
- (void)configureCell;
@end

#endif  // CHROME_BROWSER_UI_COCOA_MENU_BUTTON_H_


text:
require 'securerandom'

module WebPay::Mock::FakeEntity
  include WebPay::Mock::Util

  def charge_from(params, overrides = {}, base = {})
    Charge.new(base).set_params(params).override(overrides).build
  end

  def customer_from(params, overrides = {}, base = {})
    Customer.new(base).set_params(params).override(overrides).build
  end

  def recursion_from(params, overrides = {}, base = {})
    Recursion.new(base).set_params(params).override(overrides).build
  end

  def token_from(params, overrides = {})
    Token.new.set_params(params).override(overrides).build
  end

  def fake_event(overrides = {})
    Event.new.override(overrides).build
  end

  def fake_account(overrides = {})
    Account.new.override(overrides).build
  end

  def fake_list(path, proc)
    {
      'object' => 'list',
      'url' => '/v1' + path,
      'count' => 3,
      'data' => [proc.call, proc.call, proc.call]
    }
  end

  def card_from(params, overrides = {})
    Card.new.set_params(params).override(overrides).build
  end

  def fake_card
    Card.new.build
  end

  def fake_fingerprint
    SecureRandom.hex(20)[0...40]
  end
end

require 'webpay/mock/fake_entity/base'
require 'webpay/mock/fake_entity/card'
require 'webpay/mock/fake_entity/charge'
require 'webpay/mock/fake_entity/customer'
require 'webpay/mock/fake_entity/recursion'
require 'webpay/mock/fake_entity/token'
require 'webpay/mock/fake_entity/event'
require 'webpay/mock/fake_entity/account'


text:
import { Component }       from '@angular/core'

import {ProjectSvc} from '../../../service/project'
import {Status} from '../../../service/status'

@Component({
  selector: 'task-header',
  template: require('./task-header.cmp.html')
})
export class TaskHeaderCmp {
  constructor(private projectSvc: ProjectSvc) {
  }
}


text:
Lang
====

Lang is a small library that adds some core language extensions to Dart.

It's more of a language extension because the methods are important for development purposes across libraries and also because the methods are added to the outer scope.

==============

The inspect method was inspired by Ruby's own version of it. The main idea is that the String returned by it is more detailed. The String wraps content into their appropriate formats so they help to tell a more complete story about their actual content. Say if the String has just spaces, but if it comes between delimiters, we can tell where the spaces are, otherwise we'd have to try to guess it.

```dart
String inspect(v)

void printInspect(v)

void p(v)
```

A simple test for them:

```dart
import "../lib/lang.dart";

main() {
  var s = "   ", a = ["   ", "bee", "   "]; // Only spaces
  print("'s' using just the print command: ${s}");
  print("'s' using inspect within the print command: ${inspect(s)}");
  print("'a' using just the print command:");
  print(a);
  print("'a' using the p (printInspect) command:");
  p(a);
}
```

It prints this once run:

```
's' using just the print command:
's' using inspect within the print command: "   "
'a' using just the print command:
[   , bee,    ]
'a' using the p (printInspect) command:
["   ", "bee", "   "]
```

One anecdote about the "p" command in Ruby is that some core Ruby developer said he was hooked into Ruby because of it.

In Ruby "p" also prints inspect details about instances and so on without us having to give them proper "toString()" support. In Dart it's less straightforward.

RespondTo was born from a need to check whether some instance had some method when I converted a library of mine from JavaScript to Dart. In JavaScript that kind of checking doesn't result in an exception.

```dart
bool respondTo(fn())
```

A test with respondTo:

```dart
import "../lib/lang.dart";

class A {

  var names, moreInfo;

  A() {
    names = ["Ella", "Junior"];
    moreInfo = {"Ella": {"email": "foo@gmail.com"},
      "Junior": {"email": "bar@gmail.com"}};
  }

}

main() {
  var a = new A();
  p("Respond to moreInfo? ${respondTo(() => a.moreInfo)}");
  p("Respond to muchMoreInfo? ${respondTo(() => a.muchMoreInfo)}");
  p(a.names);
  p(a.moreInfo);
}
```

Once run it prints:

```
"Respond to moreInfo? true"
"Respond to muchMoreInfo? false"
["Ella", "Junior"]
{"Ella": {"email": "foo@gmail.com"}, "Junior": {"email": "bar@gmail.com"}}
```

As Dart doesn't have support for variadic number of arguments, one trick is to create a literal list or array yourself for the arguments. Like so:

```dart
p(["description", vFoo, sBar]);
```

I often use this trick when debugging. But I also use a higher level version of "p" that prints content on the web page in a debugging window created with a div. This other method is short enough called "DR.p", though it's not part of this Lang library as it's more dependent on the browser.

The Lang library is useful for either browser or command-line programming.


text:
package com.intellij.openapi.components.impl;

import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.components.ComponentConfig;
import com.intellij.openapi.components.ComponentManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public abstract class PlatformComponentManagerImpl extends ComponentManagerImpl {
  private boolean myHandlingInitComponentError;

  protected PlatformComponentManagerImpl(ComponentManager parent) {
    super(parent);
  }

  protected PlatformComponentManagerImpl(ComponentManager parent, @NotNull String name) {
    super(parent, name);
  }

  @Override
  protected void handleInitComponentError(@NotNull Throwable ex, @Nullable String componentClassName, @Nullable ComponentConfig config) {
    if (!myHandlingInitComponentError) {
      myHandlingInitComponentError = true;
      try {
        PluginManager.handleComponentError(ex, componentClassName, config);
      }
      finally {
        myHandlingInitComponentError = false;
      }
    }
  }
}


text:
/******************************************************************************
 *
 * This demo is described on the following web page:
 * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT_SL/Demos/File_System_Win32_Simulator_demo.shtml
 *
 ******************************************************************************/

/* Standard includes. */
#include <stdio.h>
#include <stdint.h>

/* FreeRTOS includes. */
#include <FreeRTOS.h>
#include "task.h"
#include "queue.h"
#include "semphr.h"

/* File system includes. */
#include "config_fat_sl.h"

/* Priorities at which the tasks are created. */
#define mainUDP_CLI_TASK_PRIORITY			( tskIDLE_PRIORITY )

/*-----------------------------------------------------------*/

/*
 * Register the generic commands that can be used with FreeRTOS+CLI.
 */
extern void vRegisterSampleCLICommands( void );

/*
 * Register the file system commands that can be used with FreeRTOS+CLI.
 */
extern void vRegisterFileSystemCLICommands( void );

/*
 * The task that implements the UDP command interpreter using FreeRTOS+CLI.
 */
extern void vUDPCommandInterpreterTask( void *pvParameters );

/*
 * Creates and verifies different files on the volume, demonstrating the use of
 * various different API functions.
 */
extern void vCreateAndVerifySampleFiles( void );

/*-----------------------------------------------------------*/

/******************************************************************************
 *
 * This demo is described on the following web page:
 * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT_SL/Demos/File_System_Win32_Simulator_demo.shtml
 *
 ******************************************************************************/

int main( void )
{
const uint32_t ulLongTime_ms = 250UL;

	/* If the file system is only going to be accessed from one task then
	F_FS_THREAD_AWARE can be set to 0 and the set of example files are created
	before the RTOS scheduler is started.  If the file system is going to be
	access from more than one task then F_FS_THREAD_AWARE must be set to 1 and
	the	set of sample files are created from the idle task hook function
	vApplicationIdleHook() - which is defined in this file. */
	#if F_FS_THREAD_AWARE == 0
	{
		/* Initialise the drive and file system, then create a few example
		files.  The output from this function just goes to the stdout window,
		allowing the output to be viewed when the UDP command console is not
		connected. */
		vCreateAndVerifySampleFiles();
	}
	#endif

	/* Register generic commands with the FreeRTOS+CLI command interpreter. */
	vRegisterSampleCLICommands();

	/* Register file system related commands with the FreeRTOS+CLI command
	interpreter. */
	vRegisterFileSystemCLICommands();

	/* Create the task that handles the CLI on a UDP port.  The port number
	is set using the configUDP_CLI_PORT_NUMBER setting in FreeRTOSConfig.h. */
	xTaskCreate( vUDPCommandInterpreterTask, 	/* The function that implements the command interpreter IO handling. */
				"CLI", 							/* The name of the task - just to assist debugging. */
				configMINIMAL_STACK_SIZE, NULL, /* The size of the stack allocated to the task. */
				mainUDP_CLI_TASK_PRIORITY, 		/* The priority at which the task will run. */
				NULL );							/* A handle to the task is not required, so NULL is passed. */

	/* Start the RTOS scheduler. */
	vTaskStartScheduler();

	/* If all is well, the scheduler will now be running, and the following
	line will never be reached.  If the following line does execute, then
	there was insufficient FreeRTOS heap memory available for the idle and/or
	timer tasks	to be created.  See the memory management section on the
	FreeRTOS web site for more details (this is standard text that is not not
	really applicable to the Win32 simulator port). */
	for( ;; )
	{
		Sleep( ulLongTime_ms );
	}
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook( void )
{
const unsigned long ulMSToSleep = 5;

	/* If the file system is only going to be accessed from one task then
	F_FS_THREAD_AWARE can be set to 0 and the set of example files is created
	before the RTOS scheduler is started.  If the file system is going to be
	access from more than one task then F_FS_THREAD_AWARE must be set to 1 and
	the	set of sample files are created from the idle task hook function. */
	#if F_FS_THREAD_AWARE == 1
	{
		static BaseType_t xCreatedSampleFiles = pdFALSE;

		/* Initialise the drive and file system, then create a few example
		files.  The output from this function just goes to the stdout window,
		allowing the output to be viewed when the UDP command console is not
		connected. */
		if( xCreatedSampleFiles == pdFALSE )
		{
			vCreateAndVerifySampleFiles();
			xCreatedSampleFiles = pdTRUE;
		}
	}
	#endif

	/* This function is called on each cycle of the idle task if
	configUSE_IDLE_HOOK is set to 1 in FreeRTOSConfig.h.  Sleep to reduce CPU
	load. */
	Sleep( ulMSToSleep );
}
/*-----------------------------------------------------------*/

void vAssertCalled( const char *pcFile, unsigned long ulLine )
{
	printf( "ASSERT FAILED: File %s, line %u\r\n", pcFile, ulLine );
}
/*-----------------------------------------------------------*/

void vApplicationMallocFailedHook( void )
{
	/* vApplicationMallocFailedHook() will only be called if
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h.  It is a hook
	function that will get called if a call to pvPortMalloc() fails.
	pvPortMalloc() is called internally by the kernel whenever a task, queue,
	timer or semaphore is created.  It is also called by various parts of the
	demo application.  If heap_1.c, heap_2.c or heap_4.c are used, then the
	size of the heap available to pvPortMalloc() is defined by
	configTOTAL_HEAP_SIZE in FreeRTOSConfig.h, and the xPortGetFreeHeapSize()
	API function can be used to query the size of free heap space that remains
	(although it does not provide information on how the remaining heap might
	be fragmented). */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}


text:
<nav-bar></nav-bar>
<md-content>
    <landing-page-container></landing-page-container>
    <game-content></game-content>
</md-content>
<footer page-footer></footer>


text:
<?php

namespace Prezent\Soap\Client\Event;

use Symfony\Contracts\EventDispatcher\Event;

/**
 * RequestEvent
 *
 * @see Event
 * @author Sander Marechal
 */
class RequestEvent extends Event
{
    /**
     * @var \DOMDocument
     */
    private $request;

    /**
     * @var string
     */
    private $requestHeaders;

    /**
     * @var string
     */
    private $location;

    /**
     * @var string
     */
    private $action;

    /**
     * @var int
     */
    private $version;

    /**
     * @var bool
     */
    private $oneWay;

    /**
     * @var string
     */
    private $response;

    /**
     * @var string
     */
    private $responseHeaders;

    /**
     * Constructor
     *
     * @param \DOMDocument $request
     * @param string $location
     * @param string $action
     * @param int $version
     * @param bool $oneWay
     */
    public function __construct(\DOMDocument $request, $location, $action, $version, $oneWay = false)
    {
        $this->request = $request;
        $this->location = $location;
        $this->action = $action;
        $this->version = $version;
        $this->oneWay = $oneWay;
    }

    /**
     * Get request
     *
     * @return \DOMDocument
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Set request
     *
     * @param \DOMDocument $request
     * @return self
     */
    public function setRequest($request)
    {
        $this->request = $request;
        return $this;
    }

    /**
     * Get requestHeaders
     *
     * @return string
     */
    public function getRequestHeaders()
    {
        return $this->requestHeaders;
    }

    /**
     * Set requestHeaders
     *
     * @param string $requestHeaders
     * @return self
     */
    public function setRequestHeaders($requestHeaders)
    {
        $this->requestHeaders = $requestHeaders;
        return $this;
    }

    /**
     * Get location
     *
     * @return string
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * Set location
     *
     * @param string $location
     * @return self
     */
    public function setLocation($location)
    {
        $this->location = $location;
        return $this;
    }

    /**
     * Get action
     *
     * @return string
     */
    public function getAction()
    {
        return $this->action;
    }

    /**
     * Set action
     *
     * @param string $action
     * @return self
     */
    public function setAction($action)
    {
        $this->action = $action;
        return $this;
    }

    /**
     * Get version
     *
     * @return int
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Set version
     *
     * @param int $version
     * @return self
     */
    public function setVersion($version)
    {
        $this->version = $version;
        return $this;
    }

    /**
     * Is oneWay
     *
     * @return bool
     */
    public function isOneWay()
    {
        return $this->oneWay;
    }

    /**
     * Set oneWay
     *
     * @param bool $oneWay
     * @return self
     */
    public function setOneWay($oneWay = true)
    {
        $this->oneWay = $oneWay;
        return $this;
    }

    /**
     * Get response
     *
     * @return string
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * Set response
     *
     * @param string $response
     * @return self
     */
    public function setResponse($response)
    {
        $this->response = $response;
        return $this;
    }

    /**
     * Get responseHeaders
     *
     * @return string
     */
    public function getResponseHeaders()
    {
        return $this->responseHeaders;
    }

    /**
     * Set responseHeaders
     *
     * @param string $responseHeaders
     * @return self
     */
    public function setResponseHeaders($responseHeaders)
    {
        $this->responseHeaders = $responseHeaders;
        return $this;
    }
}


text:
sectionid: processors
sectionclass: h2
parent-id: hardware
title: Processors
number: 2300
---
### Moore's law
{: .h3}

Lithography, junctures, 3D-junctures, what's beyond 10 nm.

Single-core clock speed, CPU growth towards multiple cores.

Watts per unit of work.

### Concurrency
{: .h3}

Multiple processors per computer.

Multiple cores per processor.

Multiple thread contexts (hyperthreading) per core.

Access to L2/L3 cache. Interprocessor interrupts, cache lines, invalidation.

### Firmware and microcode
{: .h3}

How to apply processor bug fixes on the fly.

### Mainstream x64 vs. ARM vs. SPARC
{: .h3}

https://en.wikipedia.org/wiki/Complex_instruction_set_computing

### Systems on Chip (SOC)
{: .h3}

IoT processors with integrated memory and storage such as Intel Edison.


text:
package de.saxsys.mvvmfx.utils.notifications;

/**
 * Observer for getting notifications.
 *
 * @author sialcasa
 *
 */
@FunctionalInterface
public interface NotificationObserver {
	/**
	 * Handle the Notification which is passed by the NotificationCenter. An @Object[] could be shipped.
	 *
	 * @param key
	 *            notification name
	 * @param payload
	 *            which are passed
	 */
	void receivedNotification(String key, Object... payload);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DoVuiHaiNao.Data;
using DoVuiHaiNao.Services;
using Microsoft.EntityFrameworkCore;

namespace DoVuiHaiNao.Controllers
{
    public class SitemapController : Controller
    {
        private readonly ApplicationDbContext _blogService;
        public SitemapController(ApplicationDbContext blogService)
        {
            _blogService = blogService;
        }

        [Route("sitemap.xml")]
        public async Task<ActionResult> Sitemap()
        {
            string scheme = HttpContext.Request.Scheme;
            string host = HttpContext.Request.Host.Host;
            string port = HttpContext.Request.Host.Port.ToString();
            string root = string.Format("{0}://{1}", scheme, host);

            // get last modified date of the home page
            var siteMapBuilder = new SitemapBuilder();

            // add the home page to the sitemap
            siteMapBuilder.AddUrl(root, modified: DateTime.UtcNow, changeFrequency: ChangeFrequency.Weekly, priority: 1.0);
            // get a list of published articles
            var images = await _blogService.Images.ToListAsync();

            string picFull = root+ "/images/";
            string pic640x480 = root + "/images/640x480/";

            // add the blog posts to the sitemap
            foreach (var item in images)
            {
                siteMapBuilder.AddUrl(picFull + item.Name, modified: item.CreateDT, changeFrequency: null, priority: 0.9);
                siteMapBuilder.AddUrl(pic640x480 + item.Name, modified: item.CreateDT, changeFrequency: null, priority: 0.9);
            }

            var singlePuzzles = await _blogService.SinglePuzzle
                .Where(p => !p.IsMMultiPuzzle && p.Approved == "A" && !p.IsDeleted)
                .Where(p => p.CreateDT < DateTime.Now)
                .ToListAsync();
            string singlePuzzlesRoot = root + "/cau-do-moi-ngay/";
            foreach (var item in singlePuzzles)
            {
                siteMapBuilder.AddUrl(singlePuzzlesRoot + item.Slug, modified: item.CreateDT, changeFrequency: null, priority: 0.9);
            }

            var multiPuzzles = await _blogService.MultiPuzzle
                .Where(p => p.Approved == "A" && !p.IsDeleted)
                .Where(p => p.CreateDT < DateTime.Now)
                .ToListAsync();
            string multiPuzzlesRoot = root + "/cau-do-dac-biet/";
            foreach (var item in multiPuzzles)
            {
                siteMapBuilder.AddUrl(multiPuzzlesRoot + item.Slug, modified: item.CreateDT, changeFrequency: null, priority: 0.9);
            }

            var blogs = await _blogService.Post
                .Where(p => p.Approved == "A" && !p.IsDeleted)
                .Where(p => p.CreateDT < DateTime.Now)
                .ToListAsync();
            string blogRoot = root + "/blogs/";
            foreach (var item in blogs)
            {
                siteMapBuilder.AddUrl(blogRoot + item.Slug, modified: item.CreateDT, changeFrequency: null, priority: 0.9);
            }

            var tags = await _blogService.Tag
                .Where(p => p.CreateDT < DateTime.Now)
                .ToListAsync();
            string tagsRoot = root + "/the/";
            foreach (var item in tags)
            {
                 siteMapBuilder.AddUrl(tagsRoot + item.Slug, modified: item.CreateDT, changeFrequency: null, priority: 0.9);
            }

            // generate the sitemap xml
            string xml = siteMapBuilder.ToString();
            return Content(xml, "text/xml");
        }
    }
}


text:
import os
import sys
from unittest.mock import MagicMock, Mock

sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('..'))

on_rtd = os.environ.get('READTHEDOCS') == 'True'

# -- Project information -----------------------------------------------------

project = 'piqs'
copyright = '2018, Nathan Shammah, Shahnawaz Ahmed'
author = 'Nathan Shammah, Shahnawaz Ahmed'

# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = '1.2'

# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx.ext.doctest',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',
    'sphinx.ext.githubpages',
    'sphinx.ext.mathjax',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ['.rst', '.md']

source_parsers = {
   '.md': 'recommonmark.parser.CommonMarkParser',
}

# The master toctree document.
master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'python'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself.  Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}

# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'piqsdoc'

# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'piqs.tex', 'piqs Documentation',
     'Nathan Shammah, Shahnawaz Ahmed', 'manual'),
]

# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'piqs', 'piqs Documentation',
     [author], 1)
]

# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'piqs', 'piqs Documentation',
     author, 'piqs', 'One line description of project.',
     'Miscellaneous'),
]

# -- Extension configuration -------------------------------------------------

# -- Options for intersphinx extension ---------------------------------------

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

napoleon_google_docstring = False
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True

# ============================================================================
if on_rtd:
    class Mock(MagicMock):
        @classmethod
        def __getattr__(cls, name):
            return MagicMock()

    MOCK_MODULES = ['numpy', 'cython', 'scipy', 'qutip', 'qutip.solver',
                    'scipy.sparse', 'scipy.integrate']
    sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)


text:
![Drawing by Genzo20 on Wikimedia Commons http://commons.wikimedia.org/wiki/File:Gnomo.jpg](https://raw.githubusercontent.com/Aqwis/nisse/master/nisse.png)

# Nisse

A simple bookmarking IRC bot written in JavaScript, using node.js. Copy settings.js.example to settings.js and modify it to suit your needs, then run the bot with one of the modes defined in settings.js as the first argument. Nisse uses a simple SQLite3 database to store bookmarks and channel history; the filename of this database can also be set in settings.js.

## Commands

* ```.bookmark <keyword> <text>``` (adds bookmark)
* ```.unmark <keyword>``` (removes bookmark)
* ```.search <keyword>``` (searches for bookmarks)
* ```^n``` (repeats line current-n)
* ```.login <password>``` (log in as administrator or superuser -- see below)
* ```.logout``` (log out)

## Administration

Nisse has several administration commands that you can use once logged in as an administrator. To begin with, define a username and password for the superuser in settings.js. Keep in mind that the username you set must match your username on IRC -- you can't log in using an arbitrary username. You can then log in as this superuser by typing

* ```.login <password>```

It is recommended that you don't continue to use the superuser account, as the password to this account is exposed in plaintext in settings.js. Instead, create an administrator account for yourself using

* ```@addAdmin <username> <password>```

while logged in as superuser. You can then safely remove the superuser account by setting the username and password to empty strings in settings.js. The next time you want to use one of the administrator commands, you can log into your administrator account in the same way as you logged in as superuser. Once logged in as administrator, you have access to the following administration commands:

* ```@lock <bookmark>``` (prevent users from editing a bookmark)
* ```@unlock <bookmark>``` (allow users to edit bookmark)
* ```@ban <regex>``` (prevent a user, given by hostname regex, from creating or altering bookmarks)
* ```@unban <regex>``` (remove ban regex)
* ```@listBans``` (list all active bans)
* ```@addAdmin <username> <password>``` (create administrator user)
* ```@removeAdmin <username> <password>``` (remove administrator user)
* ```@changePassword <password>``` (change your own administrator password)

Note that all commands that require you to be logged in are prefixed with ```@```.

## Bookmark formatting

Use ```<br>``` within a bookmark to add a newline to the bookmark output. Similarly, use ```<b>``` and ```</b>``` to make the text within the tags bold and ```<i>``` and ```</i>``` to make the text italic. Bold and italic are only supported in some IRC clients, and individual networks or channels may choose to remove formatting from messages.


text:
#include "library/trace.h"
#include "library/vm/vm_list.h"
#include "library/tactic/tactic_state.h"

namespace lean {
expr revert(environment const & env, options const & opts, metavar_context & mctx, expr const & mvar, buffer<expr> & locals,
            bool preserve_locals_order) {
    optional<metavar_decl> g   = mctx.find_metavar_decl(mvar);
    lean_assert(g);
    type_context_old ctx           = mk_type_context_for(env, opts, mctx, g->get_context(), transparency_mode::All);
    expr val                   = ctx.revert(locals, mvar, preserve_locals_order);
    expr new_g                 = get_app_fn(val);
    mctx                       = ctx.mctx();
    return new_g;
}

tactic_state revert(buffer<expr> & locals, tactic_state const & s, bool preserve_locals_order) {
    lean_assert(s.goals());
    metavar_context mctx = s.mctx();
    expr new_g = revert(s.env(), s.get_options(), mctx, head(s.goals()), locals, preserve_locals_order);
    return set_mctx_goals(s, mctx, cons(new_g, tail(s.goals())));
}

vm_obj revert(list<expr> const & ls, tactic_state const & s, bool preserve_locals_order) {
    try {
        optional<metavar_decl> g   = s.get_main_goal_decl();
        if (!g) return mk_no_goals_exception(s);
        local_context lctx         = g->get_context();
        buffer<expr> locals;
        for (expr const & l : ls) {
            if (lctx.find_local_decl(l)) {
                locals.push_back(l);
            } else {
                return tactic::mk_exception(sstream() << "revert tactic failed, unknown '"
                                            << mlocal_pp_name(l) << "' hypothesis", s);
            }
        }
        tactic_state new_s = revert(locals, s, preserve_locals_order);
        return tactic::mk_success(mk_vm_nat(locals.size()), new_s);
    } catch (exception & ex) {
        return tactic::mk_exception(ex, s);
    }
}

vm_obj tactic_revert_lst(vm_obj const & ns, vm_obj const & s) {
    bool preserve_locals_order = false;
    return revert(to_list_expr(ns), tactic::to_state(s), preserve_locals_order);
}

void initialize_revert_tactic() {
    DECLARE_VM_BUILTIN(name({"tactic", "revert_lst"}), tactic_revert_lst);
}

void finalize_revert_tactic() {
}
}


text:
package org.comtel2000.opcua.client.presentation.events;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

import javax.inject.Inject;
import javax.xml.stream.XMLStreamException;

import org.comtel2000.opcua.client.presentation.binding.StatusBinding;
import org.comtel2000.opcua.client.service.OpcUaClientConnector;
import org.comtel2000.opcua.client.service.OpcUaConverter;
import org.eclipse.milo.opcua.stack.core.serialization.xml.XmlDecoder;
import org.eclipse.milo.opcua.stack.core.serialization.xml.XmlEncoder;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.structured.ReferenceDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.effect.BlendMode;
import javafx.scene.input.TransferMode;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;

public class EventsViewPresenter implements Initializable {

  private static final Logger logger = LoggerFactory.getLogger(EventsViewPresenter.class);

  @Inject
  OpcUaClientConnector connection;

  @Inject
  StatusBinding state;

  private final ObservableList<MonitoredEvent> monitoredItems = FXCollections.observableArrayList();

  @FXML
  private TableView<MonitoredEvent> table;

  @FXML
  private TableColumn<MonitoredEvent, String> id;

  @FXML
  private TableColumn<MonitoredEvent, String> mode;

  @FXML
  private TableColumn<MonitoredEvent, String> lasterror;

  @FXML
  private TableColumn<MonitoredEvent, String> variable;

  @FXML
  private TableColumn<MonitoredEvent, Double> samplingrate;

  @FXML
  private TableColumn<MonitoredEvent, String> value;

  @FXML
  private TableColumn<MonitoredEvent, String> quality;

  @FXML
  private TableColumn<MonitoredEvent, String> timestamp;

  @FXML
  private MenuItem showItem;

  @FXML
  private MenuItem removeItem;

  @FXML
  private MenuItem removeAllItem;

  @FXML
  private MenuItem exportItem;

  @FXML
  private MenuItem importItem;

  ResourceBundle rb;

  @Override
  public void initialize(URL url, ResourceBundle rb) {
    this.rb = rb;

    table.setRowFactory(new MonitoredEventRowFactory<MonitoredEvent>());

    id.setCellValueFactory(p -> new ReadOnlyStringWrapper(
        String.format("%s (%s)", p.getValue().getSubscription().getSubscriptionId(), p.getValue().getMonitoredItem().getMonitoredItemId())));

    mode.setCellValueFactory(p -> new ReadOnlyStringWrapper(p.getValue().getMonitoredItem().getMonitoringMode().toString()));

    variable.setCellValueFactory(p -> p.getValue().nameProperty());

    value.setCellValueFactory(p -> p.getValue().valueProperty());

    samplingrate.setCellValueFactory(p -> new ReadOnlyObjectWrapper<Double>(p.getValue().getSubscription().getRevisedPublishingInterval()));

    quality.setCellValueFactory(p -> new ReadOnlyStringWrapper(OpcUaConverter.toString(p.getValue().getMonitoredItem().getStatusCode())));

    timestamp.setCellValueFactory(p -> p.getValue().timestampProperty());

    lasterror.setCellValueFactory(p -> p.getValue().lasterrorProperty());

    table.setItems(monitoredItems);

    table.setOnDragOver(event -> {
      event.acceptTransferModes(TransferMode.COPY);
      event.consume();
    });

    table.setOnDragEntered(event -> {
      if (event.getDragboard().hasString()) {
        table.setBlendMode(BlendMode.DARKEN);
      }
    });
    table.setOnDragExited(event -> {
      if (event.getDragboard().hasString()) {
        table.setBlendMode(null);
      }
    });
    table.setOnDragDropped(event -> {
      if (event.getDragboard().hasString()) {
        table.setBlendMode(null);
        event.acceptTransferModes(TransferMode.COPY);
        state.subscribeTreeItemList().add(state.selectedTreeItemProperty().get());
        event.setDropCompleted(true);
      }
    });

    table.setOnMousePressed(event -> {
      if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
        MonitoredEvent item = table.getSelectionModel().getSelectedItem();
        if (item != null) {
          state.showAttributeItemProperty().set(item.getReferenceDescription());
        }
      }

    });
    state.subscribeTreeItemList().addListener((ListChangeListener.Change<? extends ReferenceDescription> c) -> {
      while (c.next()) {
        if (c.wasAdded()) {
          c.getAddedSubList().stream().forEach(this::subscribe);
        }
      }
    });
    bindContextMenu();

    state.connectedProperty().addListener((l, a, b) -> {
      if (b && !monitoredItems.isEmpty()) {
        List<ReferenceDescription> items = monitoredItems.stream().map(MonitoredEvent::getReferenceDescription).collect(Collectors.toList());
        monitoredItems.clear();
        subscribe(items);
      }
    });
  }

  private void subscribe(ReferenceDescription rd) {
    if (rd == null || !rd.getNodeId().isLocal()) {
      return;
    }
    state.subscribeTreeItemList().remove(rd);
    try {
      connection.subscribe(rd.getNodeId().local().get()).whenCompleteAsync((s, t) -> {
        if (t != null) {
          logger.error(t.getMessage(), t);
        }
        if (s != null) {
          monitoredItems.add(new MonitoredEvent(rd, s.v1, s.v2));
        }
      }, Platform::runLater);

    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  private void subscribe(List<ReferenceDescription> references) {
    if (references == null || references.isEmpty()) {
      return;
    }
    if (!state.connectedProperty().get()) {
      state.statusTextProperty().set("subscribe failed: not connected");
      return;
    }
    state.subscribeTreeItemList().removeAll(references);

    try {
      List<NodeId> nodes = references.stream().map(ReferenceDescription::getNodeId).map(e -> e.local().get()).collect(Collectors.toList());
      connection.subscribe(nodes).whenCompleteAsync((s, t) -> {
        if (t != null) {
          logger.error(t.getMessage(), t);
        }
        if (s != null && s.v2.size() == references.size()) {
          for (int i = 0; i < references.size(); i++) {
            monitoredItems.add(new MonitoredEvent(references.get(i), s.v1, s.v2.get(i)));
          }
        }
      }, Platform::runLater);

    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  private void bindContextMenu() {
    showItem.disableProperty().bind(table.getSelectionModel().selectedItemProperty().isNull());
    removeItem.disableProperty().bind(table.getSelectionModel().selectedItemProperty().isNull());
    removeAllItem.disableProperty().bind(Bindings.isEmpty(table.getItems()));
    exportItem.disableProperty().bind(Bindings.isEmpty(table.getItems()));
    importItem.disableProperty().bind(state.connectedProperty().not());

  }

  @FXML
  void exportFile() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle(rb.getString("events.export.title"));
    fileChooser.setInitialDirectory(Paths.get(System.getProperty("user.home")).toFile());
    fileChooser.getExtensionFilters().addAll(new ExtensionFilter("XML Files", "*.xml"));
    fileChooser.setInitialFileName("subscriptions.xml");
    File file = fileChooser.showSaveDialog(table.getScene().getWindow());
    if (file != null) {
      exportItems(file);
    }
  }

  @FXML
  void importFile() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle(rb.getString("events.import.title"));
    fileChooser.setInitialDirectory(Paths.get(System.getProperty("user.home")).toFile());
    fileChooser.getExtensionFilters().addAll(new ExtensionFilter("XML Files", "*.xml"));

    File file = fileChooser.showOpenDialog(table.getScene().getWindow());
    if (file != null) {
      importItems(file);
    }
  }

  @FXML
  void showAttributes() {
    MonitoredEvent item = table.getSelectionModel().getSelectedItem();
    if (item == null) {
      return;
    }
    state.showAttributeItemProperty().set(item.getReferenceDescription());
  }

  @FXML
  void removeAllItems() {
    if (!table.isFocused()) {
      return;
    }
    connection.unsubscribeAll().whenCompleteAsync((s, t) -> monitoredItems.clear(), Platform::runLater);
  }

  @FXML
  void removeItem() {
    if (!table.isFocused()) {
      return;
    }
    MonitoredEvent item = table.getSelectionModel().getSelectedItem();
    if (item == null) {
      return;
    }
    connection.unsubscribe(item.getSubscription().getSubscriptionId(), item.getMonitoredItem()).whenCompleteAsync((s, t) -> monitoredItems.remove(item),
        Platform::runLater);
  }

  private void exportItems(File file) {

    try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
      XmlEncoder encoder = new XmlEncoder();
      encoder.setOutput(writer);
      monitoredItems.stream().map(MonitoredEvent::getReferenceDescription).forEach(rd -> {
        try {
          writer.write("<ReferenceDescription>");
          ReferenceDescription.encode(rd, encoder);
          writer.write("</ReferenceDescription>");
          writer.write(System.lineSeparator());
        } catch (IOException e) {
          logger.error(e.getMessage(), e);
        }
      });
      writer.flush();
    } catch (IOException | XMLStreamException e) {
      logger.error(e.getMessage(), e);
    }
  }

  private void importItems(File file) {

    List<ReferenceDescription> references = new ArrayList<>();
    try (BufferedReader reader = Files.newBufferedReader(file.toPath())) {
      reader.lines().filter(l -> l.startsWith("<ReferenceDescription>")).map(StringReader::new).forEach(r -> {
        try {
          XmlDecoder decoder = new XmlDecoder(r);
          decoder.skipElement();
          references.add(ReferenceDescription.decode(decoder));
        } catch (Exception e) {
          logger.error(e.getMessage(), e);
        }
      });
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
    }

    subscribe(references);
  }
}


text:
using System.Web.Mvc;

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


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace Framework.Domain.Mapping
{
    ///-------------------------------------------------------------------------------------------------
    /// <summary>
    ///     Service entity mapping.
    /// </summary>
    ///
    /// <typeparam name="T">
    ///     Generic type parameter.
    /// </typeparam>
    ///-------------------------------------------------------------------------------------------------

    public abstract class ServiceEntityMapping<T, V> : EntityMapping<T, V>
        where T : ServiceEntity<V>
    {
    }
}


text:
package org.gradle.play;

import org.gradle.api.Incubating;
import org.gradle.internal.HasInternalProtocol;
import org.gradle.model.Managed;
import org.gradle.platform.base.ApplicationSpec;

/**
 * Definition of a Play Framework software component that is built by Gradle.
 */
@Managed
@Incubating
@HasInternalProtocol
public interface PlayApplicationSpec extends ApplicationSpec, PlayPlatformAwareComponentSpec {

    /**
     * Specifies a {@link org.gradle.play.platform.PlayPlatform} with a given set of requirements that this
     * component should be built be for.  Can accept a map of play, scala and/or java requirements or a string
     * representation of the desired play platform.
     *

     *     model {
     *          components {
     *              play {
     *                  platform 'play-2.3.9'
     *                  platform play: '2.3.2'
     *                  platform play: '2.3.6', scala: '2.10'
     *                  platform play: '2.3.7', scala: '2.11', java: '1.8'
     *              }
     *          }
     *      }
     *

     * @param platformRequirements Map of Play requirements or the name of an Play platform.
     */
    @Override
    void platform(Object platformRequirements);

    /**
     * Configures the style of router to use with this application.
     *
     *

     * By default, a static routes generator is used to generate a singleton router.  This requires that all the actions
     * that the router invokes on the application's controllers are either Scala singleton objects, or Java static methods.
     *

     *
     *

     * In Play 2.4+, a injected routes generator is recommended.  This requires that the router declares its
     * dependencies to the application's controllers in its constructor.  The controllers methods need to be instance methods.
     *

     *
     * @param injectedRoutesGenerator false if a static router should be generated (default).
     * true if an injected router should be generated.
     */
    void setInjectedRoutesGenerator(boolean injectedRoutesGenerator);

    /**
     * Will an injected router be generated for this application?
     *
     * @return false if a static router will be generated for the application,
     * true if an injected router will be generated.
     */
    boolean getInjectedRoutesGenerator();
}


text:
package io.fabric8.openshift.client.server.mock;

import io.fabric8.openshift.api.model.machine.v1beta1.MachineSet;
import io.fabric8.openshift.api.model.machine.v1beta1.MachineSetBuilder;
import io.fabric8.openshift.api.model.machine.v1beta1.MachineSetList;
import io.fabric8.openshift.api.model.machine.v1beta1.MachineSetListBuilder;
import io.fabric8.openshift.client.OpenShiftClient;
import org.junit.jupiter.api.Test;

import java.net.HttpURLConnection;

import static org.assertj.core.api.Assertions.assertThat;

@EnableOpenShiftMockClient
class MachineSetTest {
  private OpenShiftClient client;
  private OpenShiftMockServer server;

  @Test
  void get() {
    // Given
    server.expect().get().withPath("/apis/machine.openshift.io/v1beta1/namespaces/ns1/machinesets/test-get")
        .andReturn(HttpURLConnection.HTTP_OK, createNewMachineSet("test-get"))
        .once();

    // When
    MachineSet machineSet = client.machine().machineSets().inNamespace("ns1").withName("test-get").get();

    // Then
    assertThat(machineSet)
        .isNotNull()
        .hasFieldOrPropertyWithValue("metadata.name", "test-get");
  }

  @Test
  void list() {
    // Given
    server.expect().get().withPath("/apis/machine.openshift.io/v1beta1/namespaces/ns1/machinesets")
        .andReturn(HttpURLConnection.HTTP_OK, new MachineSetListBuilder()
            .addToItems(createNewMachineSet("test-list"))
            .build())
        .once();

    // When
    MachineSetList machineSetList = client.machine().machineSets().inNamespace("ns1").list();

    // Then
    assertThat(machineSetList).isNotNull();
    assertThat(machineSetList.getItems()).hasSize(1);
    assertThat(machineSetList.getItems().get(0))
        .hasFieldOrPropertyWithValue("metadata.name", "test-list");
  }

  @Test
  void delete() {
    // Given
    server.expect().delete().withPath("/apis/machine.openshift.io/v1beta1/namespaces/ns1/machinesets/cluster")
        .andReturn(HttpURLConnection.HTTP_OK, createNewMachineSet("cluster"))
        .once();

    // When
    boolean isDeleted = client.machine().machineSets().inNamespace("ns1").withName("cluster").delete().size() == 1;

    // Then
    assertThat(isDeleted).isTrue();
  }

  private MachineSet createNewMachineSet(String name) {
    return new MachineSetBuilder()
        .withNewMetadata().withName(name).endMetadata()
        .withNewSpec()
        .withReplicas(2)
        .withNewSelector()
        .addToMatchLabels("machine.openshift.io/cluster-api-machineset", "worker")
        .endSelector()
        .withNewTemplate()
        .withNewMetadata()
        .addToLabels("machine.openshift.io/cluster-api-machineset", "worker")
        .endMetadata()
        .endTemplate()
        .endSpec()
        .build();
  }
}


text:
# Using the CMake tools to create the file arma_config.hpp, which contains
# information on the Armadillo configuration when mlpack was compiled.  This
# assumes ${ARMADILLO_INCLUDE_DIR} is set.  In addition, we must be careful to
# avoid overwriting arma_config.hpp with the exact same information, because
# this may trigger a new complete rebuild, which is undesired.
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/mlpack/core/util/arma_config.hpp")
  file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/mlpack/core/util/arma_config.hpp"
      OLD_FILE_CONTENTS)
else()
  set(OLD_FILE_CONTENTS "")
endif()

# If we are using Armadillo 5+, ARMA_64BIT_WORD is implicitly enabled.
set(ARMA_HAS_64BIT_WORD 0) # This may be unnecessary.
if(NOT (${ARMADILLO_VERSION_MAJOR} LESS 5))
  # ARMA_64BIT_WORD is only set if we are on a 64-bit system.
  if (CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(ARMA_HAS_64BIT_WORD 1)
  else ()
    set(ARMA_HAS_64BIT_WORD 0)
  endif ()
else()
  # Otherwise, we'll need to open the config.hpp we are using and inspect the
  # setting of ARMA_64BIT_WORD.
  if(EXISTS "${ARMADILLO_INCLUDE_DIR}/armadillo_bits/config.hpp")
    file(READ "${ARMADILLO_INCLUDE_DIR}/armadillo_bits/config.hpp"
        ARMA_CONFIG)

    # Extract ARMA_64BIT_WORD.
    string(REGEX MATCH
        "[\r\n][ ]*#define ARMA_64BIT_WORD"
        ARMA_HAS_64BIT_WORD_PRE
        "${ARMA_CONFIG}")

    string(LENGTH "${ARMA_HAS_64BIT_WORD_PRE}" ARMA_HAS_64BIT_WORD)
  else()
    # Assumes ARMA_64BIT_WORD is not set.
    message(WARNING "Armadillo configuration file
        (${ARMADILLO_INCLUDE_DIR}/armadillo_bits/config.hpp) does not exist!")
  endif()
endif()

# Now use the value we gathered to generate the new file contents.
if(ARMA_HAS_64BIT_WORD EQUAL 0)
  set(ARMA_64BIT_WORD_DEFINE "#define MLPACK_ARMA_NO64BIT_WORD")
else()
  set(ARMA_64BIT_WORD_DEFINE "#define MLPACK_ARMA_64BIT_WORD")
endif()

set(NEW_FILE_CONTENTS
"/**
 * @file arma_config.hpp
 *
 * This is an autogenerated file which contains the configuration of Armadillo
 * at the time mlpack was built.  If you modify anything in here by hand, your
 * warranty is void, your house may catch fire, and we're not going to call the
 * police when your program segfaults so hard that robbers come to your house
 * and take everything you own.  If you do decide, against better judgment, to
 * modify anything at all in this file, and you are reporting a bug, be
 * absolutely certain to mention that you've done something stupid in this file
 * first.
 *
 * In short: don't touch this file.
 */
#ifndef MLPACK_CORE_UTIL_ARMA_CONFIG_HPP
#define MLPACK_CORE_UTIL_ARMA_CONFIG_HPP

${ARMA_64BIT_WORD_DEFINE}

#endif
")

# Did the contents of the file change at all?  If not, don't write it.
if(NOT "${OLD_FILE_CONTENTS}" STREQUAL "${NEW_FILE_CONTENTS}")
  # We have a reason to write the new file.
  message(STATUS "Regenerating arma_config.hpp.")
  file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/src/mlpack/core/util/arma_config.hpp")
  file(WRITE "${CMAKE_CURRENT_SOURCE_DIR}/src/mlpack/core/util/arma_config.hpp"
      "${NEW_FILE_CONTENTS}")
endif()


text:
package fr.minibilles.basics.ui.field;

import fr.minibilles.basics.ui.BasicsUI;
import fr.minibilles.basics.ui.dialog.FieldDialog;
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.eclipse.swt.graphics.Image;

/**
 * Simple {@link FieldDialog} with one {@link TreeField} showing file system.
 * @author Jean-Charles Roger
 */
public class TreeFieldDialog1 {

	public static void main(String[] args) {

		final TreeField<File> treeField = new TreeField<File>("Files", BasicsUI.NONE) {

			private DateFormat format = DateFormat.getDateTimeInstance();

			@Override
			public String getText(File element) {
				if ( element.isDirectory() ) {
					StringBuilder text = new StringBuilder();
					text.append(element.getName());
					text.append("/");
					return text.toString();
				}
				return element.getName();
			}

			@Override
			public Image getImage(File element) {
				if ( element.isDirectory() ) {
					return getResources().getImage("eclipse/fldr_obj.gif");
				}
				String name = element.getName();
				int index = name.lastIndexOf('.');
				if ( index != -1 ) {
					return getResources().getProgramIcon(name.substring(index+1));

				}
				return null;
			}

			@Override
			public File getParent(File element) {
				return element.getParentFile();
			}

			@Override
			public List<File> getChildren(File element) {
				File [] files = element.listFiles();
				if ( files != null ) {
					List<File> result = new ArrayList<File>();
					for ( File child : files ) {
						if ( !child.isHidden() ) result.add(child);
					}
					return result;
				}
				return Collections.emptyList();
			}

			@Override
			public String getTooltip() {
				File selected = getSingleSelection();
				if ( selected != null ) {
					StringBuilder tooltip = new StringBuilder();
					tooltip.append(selected.getAbsolutePath());
					tooltip.append("\n");
					tooltip.append("Modified : ");
					tooltip.append(format.format(new Date(selected.lastModified())));
					return tooltip.toString();
				}
				return null;
			}
		};

		treeField.setValue(Arrays.asList(File.listRoots()));

		FieldDialog dialog = new FieldDialog("Test", "TreeFieldDialog1", BasicsUI.SHOW_HINTS, new CompositeField(treeField));
		int resultButton = dialog.open();

		System.out.println("Button index is " + resultButton);
	}

}


text:
File Versions

Display all the versions except for the current one.

                            Version Id
                            Modified At

                            {{versionFile.id}}
                            {{versionFile.modified_at}}

            <button class="btn btn-success btn-lg" ng-click="modalDone()">Done</button>


text:
import { Component, EventEmitter, Output } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

import { ConfirmationMessage } from './confirmation-message';
import { ConfirmationAcknowledgement } from './confirmation-state-message';
import { ConfirmationState, ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const';

import { CONFIRMATION_DIALOG_TEMPLATE } from './confirmation-dialog.component.html';
import { CONFIRMATION_DIALOG_STYLE } from './confirmation-dialog.component.css';

@Component({
    selector: 'confirmation-dialog',
    template: CONFIRMATION_DIALOG_TEMPLATE,
    styles: [ CONFIRMATION_DIALOG_STYLE ]
})

export class ConfirmationDialogComponent {
    opened: boolean = false;
    dialogTitle: string = "";
    dialogContent: string = "";
    message: ConfirmationMessage;
    buttons: ConfirmationButtons;

    @Output() confirmAction = new EventEmitter<ConfirmationAcknowledgement>();
    @Output() cancelAction = new EventEmitter<ConfirmationAcknowledgement>();

    constructor(
        private translate: TranslateService) {}

    open(msg: ConfirmationMessage): void {
        this.dialogTitle = msg.title;
        this.dialogContent = msg.message;
        this.message = msg;
        this.translate.get(this.dialogTitle).subscribe((res: string) => this.dialogTitle = res);
        this.translate.get(this.dialogContent, { 'param': msg.param }).subscribe((res: string) => this.dialogContent = res);
        //Open dialog
        this.buttons = msg.buttons;
        this.opened = true;
    }

    close(): void {
        this.opened = false;
    }

    cancel(): void {
        if(!this.message){//Inproper condition
            this.close();
            return;
        }

        let data: any = this.message.data ? this.message.data : {};
        let target = this.message.targetId ? this.message.targetId : ConfirmationTargets.EMPTY;
        this.cancelAction.emit(new ConfirmationAcknowledgement(
            ConfirmationState.CANCEL,
            data,
            target
        ));
        this.close();
    }

    confirm(): void {
        if(!this.message){//Inproper condition
            this.close();
            return;
        }

        let data: any = this.message.data ? this.message.data : {};
        let target = this.message.targetId ? this.message.targetId : ConfirmationTargets.EMPTY;
        let message = new ConfirmationAcknowledgement(
            ConfirmationState.CONFIRMED,
            data,
            target
        );
        this.confirmAction.emit(message);
        this.close();
    }
}


text:
/// <summary>
/// Xcode PBX support library.  This is from the Unity open source.
/// https://bitbucket.org/Unity-Technologies/xcodeapi/overview
/// </summary>
///
/// The MIT License (MIT)

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

  class PBXElement
  {
    protected PBXElement() {}

    // convenience methods
    public string AsString() { return ((PBXElementString)this).value; }
    public PBXElementArray AsArray() { return (PBXElementArray)this; }
    public PBXElementDict AsDict()   { return (PBXElementDict)this; }

    public PBXElement this[string key]
    {
      get { return AsDict()[key]; }
      set { AsDict()[key] = value; }
    }
  }

  class PBXElementString : PBXElement
  {
    public PBXElementString(string v) { value = v; }

    public string value;
  }

  class PBXElementDict : PBXElement
  {
    public PBXElementDict() : base() {}

    private Dictionary<string, PBXElement> m_PrivateValue = new Dictionary<string, PBXElement>();
    public IDictionary<string, PBXElement> values { get { return m_PrivateValue; }}

    new public PBXElement this[string key]
    {
      get {
        if (values.ContainsKey(key))
          return values[key];
        return null;
      }
      set { this.values[key] = value; }
    }

    public bool Contains(string key)
    {
      return values.ContainsKey(key);
    }

    public void Remove(string key)
    {
      values.Remove(key);
    }

    public void SetString(string key, string val)
    {
      values[key] = new PBXElementString(val);
    }

    public PBXElementArray CreateArray(string key)
    {
      var v = new PBXElementArray();
      values[key] = v;
      return v;
    }

    public PBXElementDict CreateDict(string key)
    {
      var v = new PBXElementDict();
      values[key] = v;
      return v;
    }
  }

  class PBXElementArray : PBXElement
  {
    public PBXElementArray() : base() {}
    public List<PBXElement> values = new List<PBXElement>();

    // convenience methods
    public void AddString(string val)
    {
      values.Add(new PBXElementString(val));
    }

    public PBXElementArray AddArray()
    {
      var v = new PBXElementArray();
      values.Add(v);
      return v;
    }

    public PBXElementDict AddDict()
    {
      var v = new PBXElementDict();
      values.Add(v);
      return v;
    }
  }

}
#endif


text:
<resources>
    <string name="app_name">Slides</string>

    <string name="action_pairing">Myo Pairing</string>
    <string name="action_overview">Overview</string>
    <string name="action_previous">Previous</string>
    <string name="action_next">Next</string>
</resources>


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Landingpage = mongoose.model('Landingpage'),
	_ = require('lodash');

exports.upload = function(req, res){

	var serverPath = 'public/images/'+req.files.file.name;

    require('fs').rename(
		req.files.file.path,
		serverPath,

		function(error) {

	        if(error) {
				res.send({
	               error: 'Ah crap! Something bad happened'
				});

	        	return;
	        }

	        res.send({
				fileName: req.files.file.originalFilename
	        });
		}
    );

};

exports.deleteImagem = function(req, res){

	console.log('service', req.image);

	var serverPath = 'public/images/'+req.image;

	console.log('serverPath', req.image);

 /*
    require('fs').rmdir(
		serverPath,

		function(error) {

	        if(error) {
				res.send({
	               error: 'Ah crap! Something bad happened'
				});

	        	return;
	        }

	        res.send({
				fileName: req.files.file.originalFilename
	        });
		}
    );*/

};

/**
 * Create a Landingpage
 */
exports.create = function(req, res) {

	var landingpage = new Landingpage(req.body);
	landingpage.user = req.user;

	landingpage.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(landingpage);
		}
	});
};

/**
 * Show the current Landingpage
 */
exports.read = function(req, res) {
	res.jsonp(req.landingpage);
};

/**
 * Update a Landingpage
 */
exports.update = function(req, res) {

	var landingpage = req.landingpage;

	landingpage = _.extend(landingpage , req.body);

	landingpage.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(landingpage);
		}
	});
};

/**
 * Delete an Landingpage
 */
exports.delete = function(req, res) {

    var landingpage = req.landingpage ;

	landingpage.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(landingpage);
		}
	});
};

/**
 * List of Landingpages
 */
exports.list = function(req, res) { Landingpage.find().sort('-created').populate('user', 'displayName').exec(function(err, landingpages) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(landingpages);
		}
	});
};

/**
 * Landingpage middleware
 */
exports.landingpageByID = function(req, res, next, id) {

	Landingpage.findById(id).populate('user', 'displayName').exec(function(err, landingpage) {
		if (err) return next(err);
		if (! landingpage) return next(new Error('Failed to load Landingpage ' + id));
		req.landingpage = landingpage ;
		next();
	});
};

/**
 * Landingpage authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.landingpage.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
import BranchContainer from "../../public/js/containers/BranchContainer";
import BranchWindow from "../../public/js/components/BranchWindow";
// Setting up Mock Store
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";

const middlewares = [thunk];
const mockStore = configureStore(middlewares);

describe("BranchContainer", () => {
    describe("renders", () => {
        it("a BranchWindow", () => {
            const initialState = {};
            const store = mockStore(initialState);
            const wrapper = shallow(
                <BranchContainer store={store} />
            ).shallow();
            expect(wrapper.find("BranchWindow")).to.have.length(1);
        });
    });
});

describe("BranchWindow", () => {
    describe("renders", () => {
        it("a MapContainer", () => {
            const initialState = {};
            const store = mockStore(initialState);
            const wrapper = shallow(<BranchWindow />);
            expect(wrapper.find("Connect(MapContainer)")).to.have.length(1);
        });
    });
});


text:
var filter = require('amp-filter');
var identity = function (val) { return val; };

module.exports = function compact(arr) {
    return filter(arr, identity);
};


text:
import * as React from 'react';
import { observer } from 'mobx-react-lite';

import {
  StyledNewsItem,
  Img,
  Info,
  Title,
  Footer,
  Source,
  Fill,
  Description,
} from './style';
import { INewsItem } from '~/interfaces/news-item';

export const NewsItem = observer(({ item }: { item: INewsItem }) => {
  // eslint-disable-next-line prefer-const
  let [img, setImg] = React.useState('');

  const image = new Image();
  const src = item.urlToImage;

  image.onload = () => {
    setImg(src);
  };
  image.src = src;

  if (image.complete) {
    img = src;
  }

  return (

  );
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/chipman-john-j" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/chipman-john-j</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Chipman, John J.</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/chipman-john-j</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/chipman-john-j</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
function isSpecificValue(val) {
  return (
    val instanceof Buffer
    || val instanceof Date
    || val instanceof RegExp
  ) ? true : false;
}

function cloneSpecificValue(val): any {
  if (val instanceof Buffer) {
    var x = new Buffer(val.length);
    val.copy(x);
    return x;
  } else if (val instanceof Date) {
    return new Date(val.getTime());
  } else if (val instanceof RegExp) {
    return new RegExp(val);
  } else {
    throw new Error('Unexpected situation');
  }
}

/**
 * Recursive cloning array.
 */
function deepCloneArray(arr): any {
  var clone = [];
  arr.forEach(function (item, index) {
    if (typeof item === 'object' && item !== null) {
      if (Array.isArray(item)) {
        clone[index] = deepCloneArray(item);
      } else if (isSpecificValue(item)) {
        clone[index] = cloneSpecificValue(item);
      } else {
        clone[index] = deepExtend({}, item);
      }
    } else {
      clone[index] = item;
    }
  });
  return clone;
}

/**
 * Extending object that entered in first argument.
 *
 * Returns extended object or false if have no target object or incorrect type.
 *
 * If you wish to clone source object (without modify it), just use empty new
 * object as first argument, like this:
 *   deepExtend({}, yourObj_1, [yourObj_N]);
 */
export const deepExtend = function (...objects): any {
  if (arguments.length < 1 || typeof arguments[0] !== 'object') {
    return false;
  }

  if (arguments.length < 2) {
    return arguments[0];
  }

  var target = arguments[0];

  // convert arguments to array and cut off target object
  var args = Array.prototype.slice.call(arguments, 1);

  var val, src, clone;

  args.forEach(function (obj) {
    // skip argument if it is array or isn't object
    if (typeof obj !== 'object' || Array.isArray(obj)) {
      return;
    }

    Object.keys(obj).forEach(function (key) {
      src = target[key]; // source value
      val = obj[key]; // new value

      // recursion prevention
      if (val === target) {
        return;

        /**
         * if new value isn't object then just overwrite by new value
         * instead of extending.
         */
      } else if (typeof val !== 'object' || val === null) {
        target[key] = val;
        return;

        // just clone arrays (and recursive clone objects inside)
      } else if (Array.isArray(val)) {
        target[key] = deepCloneArray(val);
        return;

        // custom cloning and overwrite for specific objects
      } else if (isSpecificValue(val)) {
        target[key] = cloneSpecificValue(val);
        return;

        // overwrite by new value if source isn't object or array
      } else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
        target[key] = deepExtend({}, val);
        return;

        // source value and new value is objects both, extending...
      } else {
        target[key] = deepExtend(src, val);
        return;
      }
    });
  });

  return target;
};

export class Deferred {

  promise: Promise<any>;

  resolve: any;
  reject: any;

  constructor () {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    })
  }
}

// getDeepFromObject({result: {data: 1}}, 'result.data', 2); // returns 1
export function getDeepFromObject(object = {}, name: string, defaultValue?: any) {
  let keys = name.split('.');
  // clone the object
  let level = deepExtend({}, object);
  keys.forEach((k) => {
    if (level && typeof level[k] !== 'undefined') {
      level = level[k];
    }
  });

  return typeof level === 'undefined' ? defaultValue : level;
}


text:
/* Common interface to throttle the AP */

#ifndef __CROS_EC_THROTTLE_AP_H
#define __CROS_EC_THROTTLE_AP_H

/**
 * Level of throttling desired.
 */
enum throttle_level {
	THROTTLE_OFF = 0,
	THROTTLE_ON,
};

/**
 * Types of throttling desired. These are independent.
 */
enum throttle_type {
	THROTTLE_SOFT = 0,			/* for example, host events */
	THROTTLE_HARD,				/* for example, PROCHOT */
	NUM_THROTTLE_TYPES
};

/**
 * Possible sources for CPU throttling requests.
 */
enum throttle_sources {
	THROTTLE_SRC_THERMAL = 0,
	THROTTLE_SRC_POWER,
};

/**
 * Enable/disable CPU throttling.
 *
 * This is a virtual "OR" operation. Any caller can enable CPU throttling of
 * any type, but all callers must agree in order to disable that type.
 *
 * @param level         Level of throttling desired
 * @param type          Type of throttling desired
 * @param source        Which task is requesting throttling
 */
#ifdef CONFIG_TEMP_SENSOR
void throttle_ap(enum throttle_level level,
		 enum throttle_type type,
		 enum throttle_sources source);

#else
static inline void throttle_ap(enum throttle_level level,
			       enum throttle_type type,
			       enum throttle_sources source)
{}
#endif

#endif	/* __CROS_EC_THROTTLE_AP_H */


text:
<?php

namespace spec\PhpSpec\Util;

use PhpSpec\Exception\Example\SkippingException;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ReservedWordsMethodNameCheckerSpec extends ObjectBehavior
{
    function it_is_restriction_provider()
    {
        $this->shouldHaveType('PhpSpec\Util\NameChecker');
    }

    function it_returns_true_for_not_php_restricted_name()
    {
        $this->isNameValid('foo')->shouldReturn(true);
    }

    function it_returns_false_for_php_restricted_name()
    {
        $this->skipIfPhp7();
        $this->isNameValid('function')->shouldReturn(false);
    }

    function it_returns_false_for_php_predefined_constant()
    {
        $this->skipIfPhp7();
        $this->isNameValid('__CLASS__')->shouldReturn(false);
    }

    function it_returns_false_for_php_restricted_name_case_insensitive()
    {
        $this->skipIfPhp7();
        $this->isNameValid('instanceof')->shouldReturn(false);
        $this->isNameValid('instanceOf')->shouldReturn(false);
    }

    function it_returns_false_for___halt_compiler_function()
    {
        $this->isNameValid('__halt_compiler')->shouldReturn(false);
    }

    private function skipIfPhp7()
    {
        if (\PHP_VERSION_ID >= 70000) {
            throw new SkippingException('Reserved keywords list in PHP 7 does not include most of PHP 5.6 keywords');
        }
    }

}


text:
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import JobMediator from '~/jobs/job_details_mediator';
import job from '../mock_data';

describe('JobMediator', () => {
  let mediator;
  let mock;

  beforeEach(() => {
    mediator = new JobMediator({ endpoint: 'jobs/40291672.json' });
    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    mock.restore();
  });

  it('should set defaults', () => {
    expect(mediator.store).toBeDefined();
    expect(mediator.service).toBeDefined();
    expect(mediator.options).toEqual({ endpoint: 'jobs/40291672.json' });
    expect(mediator.state.isLoading).toEqual(false);
  });

  describe('request and store data', () => {
    beforeEach(() => {
      mock.onGet().reply(200, job, {});
    });

    it('should store received data', (done) => {
      mediator.fetchJob();
      setTimeout(() => {
        expect(mediator.store.state.job).toEqual(job);
        done();
      }, 0);
    });
  });
});