text:
package org.kuali.rice.krms.api.repository.type;

import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.core.api.exception.RiceIllegalStateException;
import org.kuali.rice.krms.api.KrmsConstants;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.List;

@WebService(name = "KRMSTypeService", targetNamespace = KrmsConstants.Namespaces.KRMS_NAMESPACE_2_0)
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public interface KrmsTypeRepositoryService {

    /**
     * This will create a {@link KrmsTypeDefinition} exactly like the parameter passed in.
     *
     * @param krmsType - KrmsType
     * @throws IllegalArgumentException if the krmsType is
     * +
     * @throws IllegalStateException if the KrmsType already exists in the system
     */
    @WebMethod(operationName="createKrmsType")
    @WebResult(name = "krmsType")
    @CacheEvict(value={KrmsTypeDefinition.Cache.NAME}, allEntries = true)
    KrmsTypeDefinition createKrmsType(@WebParam(name = "krmsType") KrmsTypeDefinition krmsType)
        throws RiceIllegalArgumentException, RiceIllegalStateException;

    /**
     * This will update an existing {@link KrmsTypeDefinition}
     *
     * @param krmsType - KrmsType
     * @throws IllegalArgumentException if the krmsType is null
     * @throws IllegalStateException if the KrmsType does not exist in the system
     */
    @WebMethod(operationName="updateKrmsType")
    @WebResult(name = "krmsType")
    @CacheEvict(value={KrmsTypeDefinition.Cache.NAME}, allEntries = true)
    KrmsTypeDefinition updateKrmsType(@WebParam(name = "krmsType") KrmsTypeDefinition krmsType)
        throws RiceIllegalArgumentException, RiceIllegalStateException;

    /**
     * Lookup a krms type based on the given id.
     *
     * @param id the given KRMS type id
     * @return a KRMS KrmsType object with the given id.  A null reference is returned if an invalid or
     *         non-existant id is supplied.
     */
    @WebMethod(operationName = "getTypeById")
    @WebResult(name = "type")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'id=' + #p0")
    KrmsTypeDefinition getTypeById(@WebParam(name = "id") String id)
        throws RiceIllegalArgumentException;

    /**
     * Get a krms type object based on name and namespace
     *
     * @param namespaceCode the given type namespace
     * @param name the given type name
     *
     * @return A krms type object with the given namespace and name if one with that name and namespace
     *         exists.  Otherwise, null is returned.
     *
     * @throws IllegalArgumentException if the given namespaceCode or name is a null or blank value
     * @throws IllegalStateException if multiple krms types exist with the same name and namespace
     */
    @WebMethod(operationName = "getTypeByName")
    @WebResult(name = "type")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'namespaceCode=' + #p0 + '|' + 'name=' + #p1")
    KrmsTypeDefinition getTypeByName(
            @WebParam(name = "namespaceCode") String namespaceCode,
            @WebParam(name = "name") String name)
        throws RiceIllegalArgumentException, RiceIllegalStateException;

   /**
     * Returns all KRMS types that for a given namespace.
     *
     * @return all KRMS types for a namespace
     * @throws IllegalArgumentException if the given namespaceCode is a null or blank value
     */
    @WebMethod(operationName = "findAllTypesByNamespace")
    @XmlElementWrapper(name = "namespaceTypes", required = true)
    @XmlElement(name = "namespaceType", required = false)
    @WebResult(name = "namespaceTypes")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'allByNamespaceCode=' + #p0")
    List<KrmsTypeDefinition> findAllTypesByNamespace(
    		@WebParam(name = "namespaceCode") String namespaceCode)
        throws RiceIllegalArgumentException;

    /**
     * Returns all KRMS types
     *
     * @return all KRMS types
     */
    @WebMethod(operationName = "findAllTypes")
    @XmlElementWrapper(name = "types", required = true)
    @XmlElement(name = "type", required = false)
    @WebResult(name = "types")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'all'")
    List<KrmsTypeDefinition> findAllTypes();

    /**
     * Returns all agenda types for the given contextId.
     *
     * @param contextId the id of the context
     * @return all agenda types for the given contextId
     * @throws IllegalArgumentException if the given contextId is a null or blank value
     */
    @WebMethod(operationName = "findAllAgendaTypesByContextId")
    @XmlElementWrapper(name = "agendaTypes", required = true)
    @XmlElement(name = "agendaType", required = false)
    @WebResult(name = "agendaTypes")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'{AgendaType}contextId=' + #p0")
    List<KrmsTypeDefinition> findAllAgendaTypesByContextId(
            @WebParam(name="contextId") String contextId)
        throws RiceIllegalArgumentException;

    /**
     * Return the agenda type by agendaItemId for the given contextId.
     *
     * @param agendaTypeId the id of the agendaType
     * @param contextId the id of the context
     * @return agendaType or null if none is found
     * @throws IllegalArgumentException if the given agendaTypeId or contextId is a null or blank value
     */
    @WebMethod(operationName = "getAgendaTypeByAgendaTypeIdAndContextId")
    @WebResult(name = "type")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'agendaTypeId=' + #p0 + '|' + 'contextId=' + #p1")
    KrmsTypeDefinition getAgendaTypeByAgendaTypeIdAndContextId(
            @WebParam(name="agendaTypeId") String agendaTypeId,
            @WebParam(name="contextId") String contextId)
        throws RiceIllegalArgumentException;

    /**
     * Returns all rule types for the given contextId.
     *
     * @param contextId the id of the context
     * @return all rule types for the given contextId
     * @throws IllegalArgumentException if the given contextId is a null or blank value
     */
    @WebMethod(operationName = "findAllRuleTypesByContextId")
    @XmlElementWrapper(name = "ruleTypes", required = true)
    @XmlElement(name = "ruleType", required = false)
    @WebResult(name = "ruleTypes")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'{RuleType}contextId=' + #p0")
    List<KrmsTypeDefinition> findAllRuleTypesByContextId(
            @WebParam(name="contextId") String contextId)
        throws RiceIllegalArgumentException;

    /**
     * Return the rule type by ruleItemId for the given contextId.
     *
     * @param ruleTypeId the id of the ruleType
     * @param contextId the id of the context
     * @return ruleType or null if none is found
     * @throws IllegalArgumentException if the given ruleTypeId or contextId is a null or blank value
     */
    @WebMethod(operationName = "getRuleTypeByRuleTypeIdAndContextId")
    @WebResult(name = "ruleType")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'ruleTypeId=' + #p0 + '|' + 'contextId=' + #p1")
    KrmsTypeDefinition getRuleTypeByRuleTypeIdAndContextId(
            @WebParam(name="ruleTypeId") String ruleTypeId,
            @WebParam(name="contextId") String contextId)
        throws RiceIllegalArgumentException;

    /**
     * Returns all action types for the given contextId.
     *
     * @param contextId the id of the context
     * @return all action types for the given contextId
     * @throws IllegalArgumentException if the given contextId is a null or blank value
     */
    @WebMethod(operationName = "findAllActionTypesByContextId")
    @XmlElementWrapper(name = "actionTypes", required = true)
    @XmlElement(name = "actionType", required = false)
    @WebResult(name = "actionTypes")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'{ActionType}contextId=' + #p0")
    List<KrmsTypeDefinition> findAllActionTypesByContextId(
            @WebParam(name="contextId") String contextId)
        throws RiceIllegalArgumentException;

    /**
     * Return the action type by actionItemId for the given contextId.
     *
     * @param actionTypeId the id of the actionType
     * @param contextId the id of the context
     * @return actionType or null if none is found
     * @throws IllegalArgumentException if the given actionTypeId or contextId is a null or blank value
     */
    @WebMethod(operationName = "getActionTypeByActionTypeIdAndContextId")
    @WebResult(name = "actionType")
    @Cacheable(value= KrmsTypeDefinition.Cache.NAME, key="'actionTypeId=' + #p0 + '|' + 'contextId=' + #p1")
    KrmsTypeDefinition getActionTypeByActionTypeIdAndContextId(
            @WebParam(name="actionTypeId") String actionTypeId,
            @WebParam(name="contextId") String contextId)
        throws RiceIllegalArgumentException;

    /**
     * Retrieves an attribute definition for the given id.
     *
     * @param attributeDefinitionId the id of the attribute definition to retrieve
     *
     * @return the attribute definition matching the given id, or null if no corresponding attribute definition could
     * be found with the given id value
     * @throws IllegalArgumentException if the given attributeDefinitionId is a null or blank value
     */
    @WebMethod(operationName = "getAttributeDefinitionById")
    @WebResult(name = "attribute")
    @Cacheable(value= KrmsAttributeDefinition.Cache.NAME, key="'attributeDefinitionId=' + #p0")
    KrmsAttributeDefinition getAttributeDefinitionById(@WebParam(name = "attributeDefinitionId") String attributeDefinitionId)
            throws RiceIllegalArgumentException;

    /**
     * Retrieves an attribute definition for the given namespace code and name.
     *
     * @param namespaceCode the namespace under which to locate the attribute definition
     * @param name the name of the attribute definition to retrieve
     *
     * @return the attribute definition matching the give namespace code and name, or null if no corresponding attribute
     * definition could be located
     *
     * @throws RiceIllegalArgumentException if the given namespaceCode or name is a null or blank value
     */
    @WebMethod(operationName = "getAttributeDefinitionByName")
    @WebResult(name = "attribute")
    @Cacheable(value= KrmsAttributeDefinition.Cache.NAME, key="'namespaceCode=' + #p0 + '|' + 'name=' + #p1")
    KrmsAttributeDefinition getAttributeDefinitionByName(
            @WebParam(name = "namespaceCode") String namespaceCode,
            @WebParam(name = "name") String name
    ) throws RiceIllegalArgumentException;
}


text:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMdiSubWindow>
#include <cartotype_framework.h>

namespace Ui
    {
    class MainWindow;
    }

class MapForm;

class MainWindow: public QMainWindow
    {
    Q_OBJECT

    public:
    explicit MainWindow(QWidget* aParent = nullptr);
    ~MainWindow();

    void ShowError(const char* aMessage,int aErrorCode);
    void UpdateSaveAddedData();
    void UpdateFindNext();
    void UpdateNorthUp();
    void UpdateDeleteOrSaveRoute();
    void UpdateDeletePushpins();
    void UpdateRouteProfile();
    void UpdateGoToGridRef();
    void UpdateStyleSheet();
    std::shared_ptr<CartoType::CFrameworkEngine> Engine() const
        {
        return m_engine;
        }
    const CartoType::MString& DefaultStyleSheetPath() const
        {
        return m_default_style_sheet_path;
        }
    void OnMapFormDestroyed(MapForm* aMapForm);
    const CartoType::TRouteProfile& CustomRouteProfile() const { return m_custom_route_profile; }
    const std::string& CustomStyleSheet() const { return m_custom_style_sheet; }
    void SetCustomStyleSheet(const std::string& aStyleSheet);

    private slots:
    void on_actionOpen_triggered();
    void on_actionAbout_CartoType_Maps_triggered();
    void on_mdiArea_subWindowActivated(QMdiSubWindow* aSubWindow);
    void on_actionScale_changed();
    void on_actionLegend_changed();
    void on_actionRotator_changed();
    void on_actionRange_changed();
    void on_actionFind_triggered();
    void on_actionFind_Next_triggered();
    void on_actionNorth_Up_triggered();
    void on_actionDelete_Route_triggered();
    void on_actionDrive_triggered();
    void on_actionCycle_triggered();
    void on_actionWalk_triggered();
    void on_actionHike_triggered();
    void on_actionCustom_Profile_triggered();
    void on_actionSave_Route_Instructions_triggered();
    void on_actionSave_Route_triggered();
    void on_actionSave_Route_as_GPX_triggered();
    void on_actionLoad_Route_triggered();
    void on_actionSave_Image_as_PNG_triggered();
    void on_actionFind_Address_triggered();
    void on_actionSave_Added_Data_as_CTMS_triggered();
    void on_actionImport_Data_from_CTMS_triggered();
    void on_actionImport_Data_from_GPX_file_triggered();
    void on_actionSet_Scale_triggered();
    void on_actionGo_to_Location_triggered();
    void on_actionGo_to_Ordnance_Survey_grid_reference_triggered();
    void on_actionChoose_Style_Sheet_triggered();
    void on_actionReload_Style_Sheet_triggered();
    void on_actionEdit_Custom_Style_Sheet_triggered();
    void on_actionLayers_triggered();
    void on_actionPerspective_View_changed();
    void on_actionMetric_Units_changed();
    void on_actionView_Route_Instructions_triggered();
    void on_actionEdit_Custom_Route_Profile_triggered();
    void on_actionSave_Custom_Route_Profile_triggered();
    void on_actionLoad_Custom_Route_Profile_triggered();
    void on_actionUse_Custom_Style_Sheet_changed();
    void on_actionLoad_Custom_Style_Sheet_triggered();
    void on_actionSave_Custom_Style_Sheet_triggered();
    void on_actionDelete_Pushpins_triggered();
    void on_actionReverse_Route_triggered();
    void on_actionPrint_triggered();
    void on_actionPrint_Preview_triggered();

    /*
    This is a manually connected slot. I don't use the "on_" naming convention because
    it causes a message like "QMetaObject::connectSlotsByName: No matching signal for on_actionOpenRecentFile_triggered()";
    that is because Qt Creator looks for slot functions starting with "on_" and
    tries to connect them up.
    */
    void OpenRecentFileTriggered();

    private:
    static const int KMaxRecentFiles = 8;

    // from QWidget
    void closeEvent(QCloseEvent* aEvent) override;

    void EnableMenuItems();
    void GetFontPath(CartoType::CString& aPath,const char* aFontName);
    CartoType::TResult LoadFont(const char* aFontName);
    CartoType::TResult InitCartoType();
    void LoadMap(const QString& aPath);
    void UpdateRecentFiles(bool aRemoveNonExistentFiles = false);
    void UpdateCustomRouteProfile();

    Ui::MainWindow* m_ui;   // note: this can't be kept in a std::unique_ptr; if you do that Qt Creator can't create slots and actions
    QAction* m_print_separator;  // the menu separator before the Print action
    QAction* m_recent_file_separator;  // the menu separator before the list of recent files
    QAction* m_recent_file_action[KMaxRecentFiles];  // menu items for recent files
    MapForm* m_map_form;    // the current map form if any; not owned
    QString m_app_path;
    QString m_cartotype_source_path;
    std::shared_ptr<CartoType::CFrameworkEngine> m_engine;
    CartoType::CString m_default_style_sheet_path;
    CartoType::TRouteProfile m_custom_route_profile;
    std::string m_custom_style_sheet;
    };

#endif // MAINWINDOW_H

redpajama_set_name: RedPajamaGithub


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

namespace TelldusCoreWrapper.Entities
{
    public class Sensor : Device
    {
        public IEnumerable<SensorValueType> SupportedMethods { get; set; }
        public string Protocol { get; set; }
        public string Model { get; set; }
    }

    public abstract class Device
    {
        public int Id { get; set; }
    }

    public class ReceiverDevice : Device
    {
        public ReceiverDevice()
        {
            SupportedMethods = new List<Method>();
        }
        public string Name { get; set; }
        public int Index { get; set; }
        public IEnumerable<Method> SupportedMethods { get; set; }

        public bool IsMethodSupported(Method method)
        {
            return SupportedMethods.Contains(method);
        }
    }
}


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

<title>Uses of Package org.drip.spline.pchip</title>
<meta name="date" content="2014-01-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.drip.spline.pchip

Packages that use org.drip.spline.pchip

Package
Description

org.drip.spline.pchip

Classes in org.drip.spline.pchip used by org.drip.spline.pchip

Class and Description

AkimaLocalC1Generator

AkimaLocalC1Generator generates the local control C1 Slope using the Akima Cubic Algorithm:

        Akima (1970): A New Method of Interpolation and Smooth Curve Fitting based on Local Procedures,
                Journal of the Association for the Computing Machinery 17 (4), 589-602.

LocalMonotoneCkGenerator

LocalMonotoneCkGenerator generates customized Local Stretch by trading off Ck for local control.

MinimalQuadraticHaganWest

This class implements the regime using the Hagan and West (2006) Minimal Quadratic Estimator.

MonotoneConvexHaganWest

This class implements the regime using the Hagan and West (2006) Estimator.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package battle;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by Nathan on 11/14/2015.
 */
public class BattlePanel extends JPanel {
    static int panelHeight = 100;
    static private String backgroundFile = "Assets/Misc/BattlePanelBackground.png";
    static BufferedImage img;
    static BufferedImage subImg;

    public BattlePanel() {
        try {
            img = ImageIO.read(new File(backgroundFile));
        } catch (IOException e) {
            System.err.println("BattlePanel: Error reading file: " + backgroundFile);
        }
    }

    public void paintComponent(Graphics g) {
        if(subImg == null) {
            subImg = img.getSubimage(0, 0, this.getWidth(), this.getHeight());
        }
        g.drawImage(subImg, 0, 0, this.getWidth(), this.getHeight(), null);
    }

    public void updateBattlePanel(List<JButton> buttons, JButton backButton) {
        this.removeAll();
        this.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        // Normal buttons
        if(buttons != null) {
            for(int i = 0; i < buttons.size(); i++) {
                c.fill = GridBagConstraints.HORIZONTAL;
                c.weightx = 1;
                c.gridwidth = 1;
                c.gridheight = 1;
                c.gridx = i/2;
                c.gridy = i%2;
                this.add(buttons.get(i), c);
            }
        }

        // Back button
        if(backButton != null) {
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 1;
            c.gridwidth = 1;
            c.gridheight = 1;
            c.gridx = 1;
            c.gridy = 1;
            this.add(backButton, c);
        }

        revalidate();
        repaint();
    }
}


text:
package com.redmintie.steelplate.net.event;

import com.redmintie.steelplate.net.Client;

public interface ServerListener extends ClientListener {
	public void clientAccepted(Client client);
}


text:
class PostProcessScene :public CameraScene
{
public:
   PostProcessScene(Context * ctx);
   virtual ~PostProcessScene();
   virtual void initPrograms();

   virtual void initialBind();

   virtual void render();

   virtual void update();

   virtual void cleanup();
private:

   void renderGeometry();

   void renderFrameBuffer();

   Program * texProg;
   Program * postprocessProg;
   Texture2D metal, marble;
   Plane plane, renderPlane;
   Cube cube1, cube2;

   Framebuffer fbo;

};
#endif


text:
import AkiroBuilder from "../../../../lib/akiro/builders/nodejs/akiroBuilder.js";
import sinon from "sinon";
import temp from "temp";
import packageJson from "../../../../../package.json";
import fileSystem from "fs-extra";
import createMockExec from "../../../helpers/mockExec.js";
import createMockTemp from "../../../helpers/mockTemp.js";
import glob from "glob";
import unzip from "unzip2";
import path from "path";

temp.track();

describe("AkiroBuilder(event, context)", () => {
	let event,
			context,
			akiroBuilder,

			nodeModulesDirectoryPath,
			temporaryDirectoryPath,

			mockExec,
			mockNpmPath,
			mockTemp,
			mockAWS,
			mockS3;

	beforeEach((done) => {
		temp.mkdir("akiroBuilder", (error, newTemporaryDirectoryPath) => {
			temporaryDirectoryPath = newTemporaryDirectoryPath;
			done();
		});
	});

	afterEach(done => {
		temp.cleanup(done);
	});

	beforeEach(function (done) {

		event = {
			region: "us-east-1",
			package: {
				name: "async",
				version: packageJson.dependencies.async
			}
		};

		nodeModulesDirectoryPath = path.normalize(`${__dirname}/../../../../../node_modules`);

		mockNpmPath = `${nodeModulesDirectoryPath}/npm/bin/npm-cli.js`;
		mockExec = createMockExec({
			[`cd ${temporaryDirectoryPath};node ${mockNpmPath} install`]: execDone => execDone(),
			[`cd ${temporaryDirectoryPath};node ${mockNpmPath} init -y`]: execDone => {
				fileSystem.copySync(`${__dirname}/../../../fixtures/newPackage.json`, `${temporaryDirectoryPath}/package.json`);
				execDone();
			}
		});
		mockTemp = createMockTemp(temporaryDirectoryPath);

		mockS3 = {
			putObject: sinon.spy((parameters, callback) => {
				callback();
			})
		};

		class MockS3 {
			constructor() {
				return mockS3;
			}
		}

		mockAWS = {
			S3: MockS3
		};

		context = {
			AWS: mockAWS,
			exec: mockExec,
			npmPath: mockNpmPath,
			temp: mockTemp,
			succeed: (data) => { done(null, data); },
			fail: done
		};

		akiroBuilder = new AkiroBuilder(event, context);
		akiroBuilder.invoke(event, context);
	});

	it("should add all designated package code to a .zip file", function (done) {
		/* eslint-disable new-cap */

		const zipFilePath = `${temporaryDirectoryPath}/package.zip`;

		let asyncFilePaths = glob.sync(`${temporaryDirectoryPath}/node_modules/async/**/*`, { dot: true });
		let npmFilePaths = glob.sync(`${temporaryDirectoryPath}/node_modules/npm/**/*`, { dot: true });

		asyncFilePaths = asyncFilePaths.filter(filterDirectories);
		npmFilePaths = npmFilePaths.filter(filterDirectories);

		function filterDirectories(filePath) {
			return !fileSystem.statSync(filePath).isDirectory();
		}

		let expectedFilePaths = asyncFilePaths.concat(npmFilePaths);
		expectedFilePaths = expectedFilePaths.map((filePath) => {
			const relativePath = filePath.replace(`${temporaryDirectoryPath}/node_modules/`, "");
			return relativePath;
		});

		let filePaths = [];
		fileSystem.createReadStream(zipFilePath)
			.pipe(unzip.Parse())
			.on("entry", (entry) => {
				filePaths.push(entry.path);
			})
			.on("close", () => {
				filePaths.should.have.members(expectedFilePaths);
				done();
			});
	});
});


text:
package org.apache.batik.dom.svg;

import org.apache.batik.css.engine.CSSNavigableNode;
import org.apache.batik.dom.AbstractAttr;
import org.apache.batik.dom.AbstractDocument;
import org.apache.batik.dom.events.NodeEventTarget;
import org.apache.batik.util.SoftDoublyIndexedTable;

import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.events.MutationEvent;

/**
 * This class provides a superclass to implement an SVG element, or
 * an element interoperable with the SVG elements.
 *
 * @author Stephane Hillion
 * @version $Id$
 */
public abstract class AbstractElement
        extends org.apache.batik.dom.AbstractElement
        implements NodeEventTarget, CSSNavigableNode {

    /**
     * The live attribute values.
     */
    protected transient SoftDoublyIndexedTable liveAttributeValues;

    /**
     * Creates a new Element object.
     */
    protected AbstractElement() {
    }

    /**
     * Creates a new Element object.
     * @param prefix The namespace prefix.
     * @param owner  The owner document.
     */
    protected AbstractElement(String prefix, AbstractDocument owner) {
        ownerDocument = owner;
        setPrefix(prefix);
      	initializeAttributes();
    }

    // CSSNavigableNode ///////////////////////////////////////////////////

    /**
     * Returns the CSS parent node of this node.
     */
    public Node getCSSParentNode() {
        return getXblParentNode();
    }

    /**
     * Returns the CSS previous sibling node of this node.
     */
    public Node getCSSPreviousSibling() {
        return getXblPreviousSibling();
    }

    /**
     * Returns the CSS next sibling node of this node.
     */
    public Node getCSSNextSibling() {
        return getXblNextSibling();
    }

    /**
     * Returns the CSS first child node of this node.
     */
    public Node getCSSFirstChild() {
        return getXblFirstChild();
    }

    /**
     * Returns the CSS last child of this node.
     */
    public Node getCSSLastChild() {
        return getXblLastChild();
    }

    /**
     * Returns whether this node is the root of a (conceptual) hidden tree
     * that selectors will not work across.
     */
    public boolean isHiddenFromSelectors() {
        return false;
    }

    // Attributes /////////////////////////////////////////////////////////

    /**
     * Returns the live attribute value associated with given
     * attribute, if any.
     * @param ns The attribute's namespace.
     * @param ln The attribute's local name.
     */
    public LiveAttributeValue getLiveAttributeValue(String ns, String ln) {
        if (liveAttributeValues == null) {
            return null;
        }
        return (LiveAttributeValue)liveAttributeValues.get(ns, ln);
    }

    /**
     * Associates a live attribute value to this element.
     * @param ns The attribute's namespace.
     * @param ln The attribute's local name.
     * @param val The live value.
     */
    public void putLiveAttributeValue(String ns, String ln,
                                      LiveAttributeValue val) {
        if (liveAttributeValues == null) {
            liveAttributeValues = new SoftDoublyIndexedTable();
        }
        liveAttributeValues.put(ns, ln, val);
    }

    /**
     * Returns the AttributeInitializer for this element type.
     * @return null if this element has no attribute with a default value.
     */
    protected AttributeInitializer getAttributeInitializer() {
        return null;
    }

    /**
     * Initializes the attributes of this element to their default value.
     */
    protected void initializeAttributes() {
        AttributeInitializer ai = getAttributeInitializer();
        if (ai != null) {
            ai.initializeAttributes(this);
        }
    }

    /**
     * Resets an attribute to the default value.
     * @return true if a default value is known for the given attribute.
     */
    protected boolean resetAttribute(String ns, String prefix, String ln) {
        AttributeInitializer ai = getAttributeInitializer();
        if (ai == null) {
            return false;
        }
        return ai.resetAttribute(this, ns, prefix, ln);
    }

    /**
     * Creates the attribute list.
     */
    protected NamedNodeMap createAttributes() {
      	return new ExtendedNamedNodeHashMap();
    }

    /**
     * Sets an unspecified attribute.
     * @param nsURI The attribute namespace URI.
     * @param name The attribute's qualified name.
     * @param value The attribute's default value.
    */
    public void setUnspecifiedAttribute(String nsURI, String name,
                                        String value) {
        if (attributes == null) {
            attributes = createAttributes();
        }
        ((ExtendedNamedNodeHashMap)attributes).
            setUnspecifiedAttribute(nsURI, name, value);
    }

    /**
     * Called when an attribute has been added.
     */
    protected void attrAdded(Attr node, String newv) {
        LiveAttributeValue lav = getLiveAttributeValue(node);
        if (lav != null) {
            lav.attrAdded(node, newv);
        }
    }

    /**
     * Called when an attribute has been modified.
     */
    protected void attrModified(Attr node, String oldv, String newv) {
        LiveAttributeValue lav = getLiveAttributeValue(node);
        if (lav != null) {
            lav.attrModified(node, oldv, newv);
        }
    }

    /**
     * Called when an attribute has been removed.
     */
    protected void attrRemoved(Attr node, String oldv) {
        LiveAttributeValue lav = getLiveAttributeValue(node);
        if (lav != null) {
            lav.attrRemoved(node, oldv);
        }
    }

    /**
     * Gets Returns the live attribute value associated with given
     * attribute, if any.
     */
    private LiveAttributeValue getLiveAttributeValue(Attr node) {
        String ns = node.getNamespaceURI();
        return getLiveAttributeValue(ns, (ns == null)
                                     ? node.getNodeName()
                                     : node.getLocalName());
    }

    // Importation ////////////////////////////////////////////////////

    /**
     * Exports this node to the given document.
     */
    protected Node export(Node n, AbstractDocument d) {
        super.export(n, d);
              ((AbstractElement)n).initializeAttributes();

        super.export(n, d);
        return n;
    }

    /**
     * Deeply exports this node to the given document.
     */
    protected Node deepExport(Node n, AbstractDocument d) {
        super.export(n, d);
              ((AbstractElement)n).initializeAttributes();

        super.deepExport(n, d);
        return n;
    }

    /**
     * An implementation of the {@link NamedNodeMap}.
     */
    protected class ExtendedNamedNodeHashMap extends NamedNodeHashMap {

        /**
         * Creates a new ExtendedNamedNodeHashMap object.
         */
        public ExtendedNamedNodeHashMap() {
        }

        /**
         * Adds an unspecified attribute to the map.
         *
         * @param nsURI The attribute namespace URI.
         * @param name The attribute's qualified name.
         * @param value The attribute's default value.
         */
        public void setUnspecifiedAttribute( String nsURI, String name,
                                             String value ) {
            Attr attr = getOwnerDocument().createAttributeNS( nsURI, name );
            attr.setValue( value );
            ( (AbstractAttr)attr ).setSpecified( false );
            setNamedItemNS( attr );
        }

        /**
         * DOM: Implements {@link NamedNodeMap#removeNamedItemNS(String,String)}.
         */
        public Node removeNamedItemNS( String namespaceURI, String localName )
                throws DOMException {
            if ( isReadonly() ) {
                throw createDOMException
                        ( DOMException.NO_MODIFICATION_ALLOWED_ERR,
                                "readonly.node.map",
                                new Object[]{} );
            }
            if ( localName == null ) {
                throw createDOMException( DOMException.NOT_FOUND_ERR,
                        "attribute.missing",
                        new Object[]{""} );
            }
            AbstractAttr n = (AbstractAttr)remove( namespaceURI, localName );
            if ( n == null ) {
                throw createDOMException( DOMException.NOT_FOUND_ERR,
                        "attribute.missing",
                        new Object[]{localName} );
            }
            n.setOwnerElement( null );
            String prefix = n.getPrefix();

            // Reset the attribute to its default value
            if ( !resetAttribute( namespaceURI, prefix, localName ) ) {
                // Mutation event
                fireDOMAttrModifiedEvent( n.getNodeName(), n,
                        n.getNodeValue(), "",
                        MutationEvent.REMOVAL );
            }
            return n;
        }
    }

}


text:
import { getOwner } from '@ember/application';
import RSVP from 'rsvp';
import { set } from '@ember/object';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import { getFlashMessageCount } from 'code-corps-ember/tests/helpers/flash-message';
import PageObject from 'ember-cli-page-object';
import component from 'code-corps-ember/tests/pages/components/project-settings-form';

let page = PageObject.create(component);

moduleForComponent('project-settings-form', 'Integration | Component | project settings form', {
  integration: true,
  beforeEach() {
    getOwner(this).lookup('service:flash-messages').registerTypes(['success']);
    page.setContext(this);
  },
  afterEach() {
    page.removeContext();
  }
});

let project = {
  title: 'Test Project',
  description: 'A test project',
  website: 'https://www.testproject.org'
};

test('it renders form elements properly', function(assert) {
  assert.expect(4);

  set(this, 'project', project);

  this.render(hbs`{{project-settings-form project=project}}`);

  assert.equal(page.title.value, 'Test Project');
  assert.equal(page.description.value, 'A test project');
  assert.equal(page.website.value, 'https://www.testproject.org');
  assert.ok(page.save.isVisible);
});

test('it calls save on project when save button is clicked', function(assert) {
  assert.expect(2);

  project.save = function() {
    assert.ok(true, 'Save method was called on project');
    return RSVP.resolve();
  };

  set(this, 'project', project);

  this.render(hbs`{{project-settings-form project=project}}`);

  page.save.click();

  assert.equal(getFlashMessageCount(this), 1, 'A flash message was shown');
});


text:
<?php

/**
 * This object represents a voice note.
 *
 * Required params: $file_id, $duration;
 * Optional params: $mime_type, $file_size.
 * User: valizada
 * Date: 26/08/15
 * Time: 14:21
 */
class Voice
{
    private $file_id;
    private $duration;
    private $mime_type;
    private $file_size;

    /**
     * @return String
     * Unique identifier for this file
     */
    public function getFileId()
    {
        return $this->file_id;
    }

    /**
     * @param mixed $file_id
     */
    public function setFileId($file_id)
    {
        $this->file_id = $file_id;
    }

    /**
     * @return Integer
     * Duration of the audio in seconds as defined by sender
     */
    public function getDuration()
    {
        return $this->duration;
    }

    /**
     * @param mixed $duration
     */
    public function setDuration($duration)
    {
        $this->duration = $duration;
    }

    /**
     * @return String
     * Optional. MIME type of the file as defined by sender
     */
    public function getMimeType()
    {
        return $this->mime_type;
    }

    /**
     * @param mixed $mime_type
     */
    public function setMimeType($mime_type)
    {
        $this->mime_type = $mime_type;
    }

    /**
     * @return Integer
     * Optional. File size
     */
    public function getFileSize()
    {
        return $this->file_size;
    }

    /**
     * @param mixed $file_size
     */
    public function setFileSize($file_size)
    {
        $this->file_size = $file_size;
    }
}


text:
use camino::{Utf8Path, Utf8PathBuf};
use hex::FromHexError;
use serde::{de, ser};
use std::{borrow::Cow, error, fmt, io, process::ExitStatus, result, str::Utf8Error};

/// Type alias for the return type for `run` methods.
pub type Result<T, E = SystemError> = result::Result<T, E>;

/// A system error that happened while running a lint.
#[derive(Debug)]
#[non_exhaustive]
pub enum SystemError {
    CwdNotInProjectRoot {
        current_dir: Utf8PathBuf,
        project_root: &'static Utf8Path,
    },
    Exec {
        cmd: &'static str,
        status: ExitStatus,
    },
    GitRoot(Cow<'static, str>),
    FromHex {
        context: Cow<'static, str>,
        err: FromHexError,
    },
    Guppy {
        context: Cow<'static, str>,
        err: guppy::Error,
    },
    HakariCargoToml {
        context: Cow<'static, str>,
        err: hakari::CargoTomlError,
    },
    HakariTomlOut {
        context: Cow<'static, str>,
        err: hakari::TomlOutError,
    },
    Io {
        context: Cow<'static, str>,
        err: io::Error,
    },
    NonUtf8Path {
        path: Vec<u8>,
        err: Utf8Error,
    },
    Serde {
        context: Cow<'static, str>,
        err: Box<dyn error::Error + Send + Sync>,
    },
}

impl SystemError {
    pub fn io(context: impl Into<Cow<'static, str>>, err: io::Error) -> Self {
        SystemError::Io {
            context: context.into(),
            err,
        }
    }

    pub fn guppy(context: impl Into<Cow<'static, str>>, err: guppy::Error) -> Self {
        SystemError::Guppy {
            context: context.into(),
            err,
        }
    }

    pub fn git_root(msg: impl Into<Cow<'static, str>>) -> Self {
        SystemError::GitRoot(msg.into())
    }

    pub fn from_hex(context: impl Into<Cow<'static, str>>, err: FromHexError) -> Self {
        SystemError::FromHex {
            context: context.into(),
            err,
        }
    }

    pub fn hakari_cargo_toml(
        context: impl Into<Cow<'static, str>>,
        err: hakari::CargoTomlError,
    ) -> Self {
        SystemError::HakariCargoToml {
            context: context.into(),
            err,
        }
    }

    pub fn hakari_toml_out(
        context: impl Into<Cow<'static, str>>,
        err: hakari::TomlOutError,
    ) -> Self {
        SystemError::HakariTomlOut {
            context: context.into(),
            err,
        }
    }

    pub fn de(
        context: impl Into<Cow<'static, str>>,
        err: impl de::Error + Send + Sync + 'static,
    ) -> Self {
        SystemError::Serde {
            context: context.into(),
            err: Box::new(err),
        }
    }

    pub fn ser(
        context: impl Into<Cow<'static, str>>,
        err: impl ser::Error + Send + Sync + 'static,
    ) -> Self {
        SystemError::Serde {
            context: context.into(),
            err: Box::new(err),
        }
    }
}

impl fmt::Display for SystemError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SystemError::CwdNotInProjectRoot {
                current_dir,
                project_root,
            } => write!(
                f,
                "current dir {} not in project root {}",
                current_dir, project_root,
            ),
            SystemError::Exec { cmd, status } => match status.code() {
                Some(code) => write!(f, "'{}' failed with exit code {}", cmd, code),
                None => write!(f, "'{}' terminated by signal", cmd),
            },
            SystemError::GitRoot(s) => write!(f, "git root error: {}", s),
            SystemError::NonUtf8Path { path, .. } => {
                write!(f, "non-UTF-8 path \"{}\"", String::from_utf8_lossy(path))
            }
            SystemError::FromHex { context, .. }
            | SystemError::Io { context, .. }
            | SystemError::Serde { context, .. }
            | SystemError::Guppy { context, .. }
            | SystemError::HakariCargoToml { context, .. }
            | SystemError::HakariTomlOut { context, .. } => write!(f, "while {}", context),
        }
    }
}

impl error::Error for SystemError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            SystemError::CwdNotInProjectRoot { .. }
            | SystemError::Exec { .. }
            | SystemError::GitRoot(_) => None,
            SystemError::FromHex { err, .. } => Some(err),
            SystemError::Io { err, .. } => Some(err),
            SystemError::Guppy { err, .. } => Some(err),
            SystemError::HakariCargoToml { err, .. } => Some(err),
            SystemError::HakariTomlOut { err, .. } => Some(err),
            SystemError::NonUtf8Path { err, .. } => Some(err),
            SystemError::Serde { err, .. } => Some(err.as_ref()),
        }
    }
}


text:
package net.jini.jeri.ssl;

import java.net.Socket;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
import javax.security.auth.x500.X500PrivateCredential;
import net.jini.io.UnsupportedConstraintException;
import net.jini.security.AuthenticationPermission;

/**
 * An AuthManager for clients.  Uses the fact that client connections only
 * share SSLContexts after a single client and server principal have been
 * chosen.
 *
 * @author Sun Microsystems, Inc.
 */
class ClientAuthManager extends AuthManager {

    /* -- Fields -- */

    /** Client logger */
    private static final Logger logger = clientLogger;

    /** The server certificate chosen by the first handshake. */
    private X509Certificate serverCredential;

    /** The server principal chosen by the first handshake. */
    private X500Principal serverPrincipal;

    /**
     * The private credential supplied by chooseClientAlias in the last
     * handshake or null if none was supplied.
     */
    private X500PrivateCredential clientCredential;

    /** The client principal chosen by the first handshake. */
    private X500Principal clientPrincipal;

    /**
     * The exception that occurred within the last call to chooseClientAlias if
     * no credential could be supplied.
     */
    private Exception clientCredentialException;

    /**
     * The latest time for which all client and server credentials remain
     * valid.
     */
    private long credentialsValidUntil = 0;

    /** The permission to check for the last cached credential */
    private AuthenticationPermission authenticationPermission;

    /* -- Constructors -- */

    /**
     * Creates an AuthManager that retrieves principals and credentials for
     * authentication from the specified subject.  If permittedLocalPrincipals
     * is non-null, then the principals used for authentication are restricted
     * to the elements of that set.  If permittedRemotePrincipals is non-null,
     * then the server principals accepted are restricted to the elements of
     * that set.
     *
     * @param subject the subject for retrieving principals and credentials
     * @param permittedLocalPrincipals if non-null, then only principals in
     *	      this set may be used for authentication
     * @param permittedRemotePrincipals if non-null, then only principals in
     *	      this set will be trusted when authenticating the peer
     * @throws NoSuchAlgorithmException if the trust manager factory algorithm
     *	       is not found
     */
    ClientAuthManager(Subject subject,
		      Set permittedLocalPrincipals,
		      Set permittedRemotePrincipals)
	throws NoSuchAlgorithmException
    {
	super(subject, permittedLocalPrincipals, permittedRemotePrincipals);
    }

    /* -- Methods -- */

    /**
     * Returns true if the last handshake authenticated the client, else
     * false.
     */
    synchronized boolean getClientAuthenticated() {
	return clientCredential != null;
    }

    /**
     * Returns the last SecurityException or GeneralSecurityException that
     * occurred when attempting to choose client credentials, or null if no
     * exception occurred.
     */
    synchronized Exception getClientCredentialException() {
	return clientCredentialException;
    }

    /**
     * Checks if the subject still contains the proper credentials, and the
     * current access control context has the proper AuthenticationPermission,
     * to use the current session.  Callers should only call this method if
     * client authentication is being used.
     *
     * @throws SecurityException if the access control context does not have
     *	       the proper AuthenticationPermission
     * @throws UnsupportedConstraintException if the subject does not contain
     *	       the proper credentials
     */
    synchronized void checkAuthentication()
	throws UnsupportedConstraintException
    {
	if (clientCredential == null) {
	    throw new UnsupportedConstraintException(
		"Client is not authenticated");
	} else if (clientCredential.isDestroyed()) {
	    throw new UnsupportedConstraintException(
		"Private credentials are destroyed");
	} else if (System.currentTimeMillis() > credentialsValidUntil) {
	    throw new UnsupportedConstraintException(
		"Certificates are no longer valid");
	}
	if (subjectIsReadOnly) {
	    SecurityManager sm = System.getSecurityManager();
	    if (sm != null) {
		sm.checkPermission(authenticationPermission);
	    }
	} else {
	    Subject subject = getSubject();
	    X509Certificate cert = clientCredential.getCertificate();
	    if (SubjectCredentials.getPrincipal(subject, cert) == null) {
		throw new UnsupportedConstraintException("Missing principal");
	    }
	    CertPath chain =
		SubjectCredentials.getCertificateChain(subject, cert);
	    if (chain == null) {
		throw new UnsupportedConstraintException(
		    "Missing public credentials");
	    }
	    X500PrivateCredential pc = getPrivateCredential(
		cert, authenticationPermission);
	    if (pc == null) {
		throw new UnsupportedConstraintException(
		    "Missing private credentials");
	    } else if (!equalPrivateCredentials(clientCredential, pc)) {
		throw new UnsupportedConstraintException(
		    "Wrong private credentials");
	    }
	}
    }

    /**
     * Gets the private credential for the specified X.509 certificate,
     * checking for AuthenticationPermission to connect with the last server
     * principal.
     *
     * @param cert the certificate for the local principal
     * @return the associated private credential or null if not found
     * @throws SecurityException if the access control context does not have
     *	       the proper AuthenticationPermission
     */
    synchronized X500PrivateCredential getPrivateCredential(
	X509Certificate cert)
    {
	return getPrivateCredential(cert, getAuthenticationPermission(cert));
    }

    /**
     * Gets the private credential for the specified X.509 certificate,
     * checking for the specified AuthenticationPermission.
     *
     * @param cert the certificate for the local principal
     * @param ap the permission needed to connect to the peer
     * @return the associated private credential or null if not found
     * @throws SecurityException if the access control context does not have
     *	       the proper AuthenticationPermission
     */
    private X500PrivateCredential getPrivateCredential(
	X509Certificate cert, AuthenticationPermission ap)
    {
	Subject subject = getSubject();
	if (subject == null) {
	    return null;
	}
	SecurityManager sm = System.getSecurityManager();
	if (sm != null) {
	    sm.checkPermission(ap);
	}
	return (X500PrivateCredential) AccessController.doPrivileged(
	    new SubjectCredentials.GetPrivateCredentialAction(
		subject, cert));
    }

    /** Returns the client logger */
    Logger getLogger() {
	return logger;
    }

    /**
     * Returns the permission needed to connect to the last server principal
     * with the specified client certificate.
     */
    private AuthenticationPermission getAuthenticationPermission(
	X509Certificate cert)
    {
	Set client = Collections.singleton(cert.getSubjectX500Principal());
	Set server = (serverPrincipal == null)
	    ? null : Collections.singleton(serverPrincipal);
	return new AuthenticationPermission(client, server, "connect");
    }

    /** Returns the server principal chosen. */
    synchronized X500Principal getServerPrincipal() {
	return serverPrincipal;
    }

    /** Returns the client principal chosen. */
    synchronized X500Principal getClientPrincipal() {
	return clientPrincipal;
    }

    /* -- X500TrustManager -- */

    /**
     * Override this X509TrustManager method in order to cache the server
     * principal and to continue to choose the same one.
     */
    public synchronized void checkServerTrusted(X509Certificate[] chain,
						String authType)
	throws CertificateException
    {
	super.checkServerTrusted(chain, authType);
	if (serverPrincipal == null) {
	    serverCredential = chain[0];
	    serverPrincipal = serverCredential.getSubjectX500Principal();
	    setPermittedRemotePrincipals(
		Collections.singleton(serverPrincipal));
	    credentialsValidUntil = certificatesValidUntil(chain);
	} else if (!serverCredential.equals(chain[0])) {
	    throw new CertificateException("Server credentials changed");
	}
    }

    /* -- Implement X509KeyManager -- */

    public String[] getClientAliases(String keyType, Principal[] issuers) {
	String[] result = getAliases(keyType, issuers);
	if (logger.isLoggable(Level.FINE)) {
	    logger.log(Level.FINE,
		       "get client aliases for key type {0}\n" +
		       "and issuers {1}\nreturns {2}",
		       new Object[] {
			   keyType, toString(issuers), toString(result)
		       });
	}
	return result;
    }

    public String[] getServerAliases(String keyType, Principal[] issuers) {
	return null;
    }

    public synchronized String chooseClientAlias(
	String[] keyTypes, Principal[] issuers, Socket socket)
    {
	/*
	 * Only choose new client credentials for the first handshake.
	 * Otherwise, just use the previous client credentials.
	 */
	if (clientCredentialException != null) {
	    return null;
	} else if (clientCredential == null) {
	    List exceptions = null;
	    for (int i = 0; i < keyTypes.length; i++) {
		Exception exception;
		try {
		    clientCredential = chooseCredential(keyTypes[i], issuers);
		    if (clientCredential != null) {
			break;
		    }
		    continue;
		} catch (GeneralSecurityException e) {
		    exception = e;
		} catch (SecurityException e) {
		    exception = e;
		}
		if (exceptions == null) {
		    exceptions = new ArrayList();
		}
		exceptions.add(exception);
	    }
	    if (clientCredential == null) {
		if (exceptions == null) {
		    clientCredentialException =
			new GeneralSecurityException("Credentials not found");
		} else if (exceptions.size() == 1) {
		    clientCredentialException = (Exception) exceptions.get(0);
		} else {
		    for (int i = exceptions.size(); --i >= 0; ) {
			Exception e = (Exception) exceptions.get(i);
			if (!(e instanceof SecurityException)) {
			    clientCredentialException =
				new GeneralSecurityException(
				    exceptions.toString());
			    break;
			}
		    }
		    if (clientCredentialException == null) {
			clientCredentialException =
			    new SecurityException(exceptions.toString());
		    }
		}
		return null;
	    }
	}
	X509Certificate cert = clientCredential.getCertificate();
	clientPrincipal = cert.getSubjectX500Principal();
	credentialsValidUntil =
	    Math.min(credentialsValidUntil,
		     certificatesValidUntil(
			 SubjectCredentials.getCertificateChain(
			     getSubject(), cert)));
	authenticationPermission = getAuthenticationPermission(cert);
	String result = SubjectCredentials.getCertificateName(
	    clientCredential.getCertificate());
	if (logger.isLoggable(Level.FINE)) {
	    logger.log(
		Level.FINE,
		"choose client alias for key types {0}\nand issuers {1}\n" +
		"returns {2}",
		new Object[] { toString(keyTypes), toString(issuers), result });
	}
	return result;
    }

    public String chooseServerAlias(
	String keyType, Principal[] issuers, Socket socket)
    {
	return null;
    }
}


text:
The API reference of the @material-ui/styles package.

## `createGenerateClassName([options]) => class name generator`

A function which returns [a class name generator function](http://cssinjs.org/jss-api/#generate-your-class-names).

#### Arguments

1. `options` (*Object* [optional]):
    - `options.disableGlobal` (*Boolan* [optional]): Defaults to `false`. Disable the generation of deterministic class names.
    - `options.productionPrefix` (*String* [optional]): Defaults to `'jss'`. The string used to prefix the class names in production.
    - `options.seed` (*String* [optional]): Defaults to `''`. The string used to uniquely identify the generator. It can be used to avoid class name collisions when using multiple generators in the same document.

#### Returns

`class name generator`: The generator should be provided to JSS.

#### Ejemplos

```jsx
import React from 'react';
import { StylesProvider, createGenerateClassName } from '@material-ui/styles';

const generateClassName = createGenerateClassName({
  productionPrefix: 'c',
});

export default function App() {
  return (
    <StylesProvider generateClassName={generateClassName}>...</StylesProvider>
  );
}
```

## `createStyles(styles) => styles`

This function doesn't really "do anything" at runtime, it's just the identity function. Its only purpose is to defeat **TypeScript**'s type widening when providing style rules to `makeStyles`/`withStyles` which are a function of the `Theme`.

#### Arguments

1. `styles` (*Function | Object*): A function generating the styles or a styles object.

#### Returns

`styles`: A function generating the styles or a styles object.

#### Ejemplos

```jsx
import { makeStyles, createStyles } from '@material-ui/styles';

const styles = makeStyles((theme: Theme) => createStyles({
  root: {
    backgroundColor: theme.color.red,
  },
}));

function MyComponent {
  const classes = useStyles();
  return <div className={classes.root} />;
}

export default MyComponent;
```

## `makeStyles(styles, [options]) => hook`

Link a style sheet with a function component using the **hook** pattern.

#### Arguments

1. `styles` (*Function | Object*): A function generating the styles or a styles object. It will be linked to the component. Use the function signature if you need to have access to the theme. It's provided as the first argument.
2. `options` (*Object* [optional]):
    - `options.defaultTheme` (*Object* [optional]): The default theme to use if a theme isn't supplied through a Theme Provider.
    - `options.withTheme` (*Boolean* [optional]): Defaults to `false`. Provide the `theme` object to the component as a property.
    - `options.name` (*String* [optional]): The name of the style sheet. Useful for debugging. If the value isn't provided, it will try to fallback to the name of the component.
    - `options.flip` (*Boolean* [optional]): When set to `false`, this sheet will opt-out the `rtl` transformation. When set to `true`, the styles are inversed. When set to `null`, it follows `theme.direction`.
    - The other keys are forwarded to the options argument of [jss.createStyleSheet([styles], [options])](http://cssinjs.org/jss-api/#create-style-sheet).

#### Returns

`hook`: A hook. This hook can be used in a function component. It accepts one argument: the properties that will be used for "interpolation" in the style sheet.

#### Ejemplos

```jsx
import React from 'react';
import { makeStyles } from '@material-ui/styles';

const useStyles = makeStyles({
  root: {
    backgroundColor: 'red',
  },
});

export default function MyComponent() {
  const classes = useStyles();
  return <div className={classes.root} />;
}
```

## `ServerStyleSheets`

This is a class helper to handle server-side rendering. [You can follow our guide for a practical approach](/guides/server-rendering/).

```jsx
import ReactDOMServer from 'react-dom/server';
import { ServerStyleSheets } from '@material-ui/styles';

const sheets = new ServerStyleSheets();
const html = ReactDOMServer.renderToString(sheets.collect(<App />));
const cssString = sheets.toString();

const response = `
<!DOCTYPE html>
<html>
  <head>
    <style id="jss-server-side">${cssString}</style>
  </head>
  <body>${html}</body>
</html>
`;
```

### `new ServerStyleSheets([options])`

The instantiation accepts an options object as a first argument.

1. `options` (*Object* [optional]): The options are spread as props to the [`StylesProvider`](#stylesprovider) component.

### `sheets.collect(node) => React element`

The method wraps your React node in a provider element. It collects the style sheets during the rendering so they can be later sent to the client.

### `sheets.toString() => CSS string`

The method returns the collected styles.

⚠ You must call `.collect()` before using this method.

### `sheets.getStyleElement() => CSS React element`

The method is an alternative to `.toString()` when you are rendering the whole page with React.

⚠ You must call `.collect()` before using this method.

## `styled(Component)(styles, [options]) => Component`

Link a style sheet with a function component using the **styled components** pattern.

#### Arguments

1. `Component`: The component that will be wrapped.
2. `styles` (*Function | Object*): A function generating the styles or a styles object. It will be linked to the component. Use the function signature if you need to have access to the theme. It's provided as property of the first argument.
3. `options` (*Object* [optional]):
    - `options.defaultTheme` (*Object* [optional]): The default theme to use if a theme isn't supplied through a Theme Provider.
    - `options.withTheme` (*Boolean* [optional]): Defaults to `false`. Provide the `theme` object to the component as a property.
    - `options.name` (*String* [optional]): The name of the style sheet. Useful for debugging. If the value isn't provided, it will try to fallback to the name of the component.
    - `options.flip` (*Boolean* [optional]): When set to `false`, this sheet will opt-out the `rtl` transformation. When set to `true`, the styles are inversed. When set to `null`, it follows `theme.direction`.
    - The other keys are forwarded to the options argument of [jss.createStyleSheet([styles], [options])](http://cssinjs.org/jss-api/#create-style-sheet).

#### Returns

`Component`: The new component created.

#### Ejemplos

```jsx
import React from 'react';
import { styled } from '@material-ui/styles';

const MyComponent = styled('div')({
  backgroundColor: 'red',
});

const MyThemeComponent = styled('div')(({
  theme
}) => ({
  padding: theme.spacing(1),
}));

export default function StyledComponents() {
  return (
    <MyThemeComponent>
      <MyComponent />
    </MyThemeComponent>
  );
}
```

## `StylesProvider`

This component allows you to change the behavior of the styling solution. It makes the options available down the React tree thanks to the context.

It should preferably be used at **the root of your component tree**.

#### PropsBy default, the styles are injected last in the

  element of the page. As a result, they gain more specificity than any other style sheet. If you want to override Material-UI's styles, set this prop.

      jss

      object

      JSS's instance.

    Ejemplos

import React from 'react';
import ReactDOM from 'react-dom';
import { StylesProvider } from '@material-ui/styles';

function App() {
  return (
    <StylesProvider jss={jss}>...</StylesProvider>
  );
}

ReactDOM.render(<App />, document.querySelector('#app'));

    ThemeProvider

    This component takes a theme property, and makes it available down the React tree thanks to the context. It should preferably be used at the root of your component tree.

    Props

        Name

        Type

        Default

        Description

        children *

        node

        Your component tree.

        theme *

        union: object | func

        A theme object. You can provide a function to extend the outer theme.

    Ejemplos

import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from '@material-ui/styles';

const theme = {};

function App() {
  return (
    <ThemeProvider theme={theme}>...</ThemeProvider>
  );
}

ReactDOM.render(<App />, document.querySelector('#app'));

    useTheme() => theme

    This hook returns the theme object so it can be used inside a function component.

    Returns

    theme: The theme object previously injected in the context.

    Ejemplos

import React from 'react';
import { useTheme } from '@material-ui/styles';

export default function MyComponent() {
  const theme = useTheme();

  return <div>{`spacing ${theme.spacing}`}</div>;
}

    withStyles(styles, [options]) => higher-order component

    Link a style sheet with a component using the higher-order component pattern. It does not modify the component passed to it; instead, it returns a new component with a classes property. This classes object contains the name of the class names injected in the DOM.

    Some implementation details that might be interesting to being aware of:

      It adds a classes property so you can override the injected class names from the outside.

      It forwards refs to the inner component.

      The innerRef prop is deprecated. Use ref instead.

      It does not copy over statics. For instance, it can be used to defined a getInitialProps() static method (next.js).

    Arguments

      styles (Function | Object): A function generating the styles or a styles object. It will be linked to the component. Use the function signature if you need to have access to the theme. It's provided as the first argument.

      options (Object [optional]):

          options.defaultTheme (Object [optional]): The default theme to use if a theme isn't supplied through a Theme Provider.

          options.withTheme (Boolean [optional]): Defaults to false. Provide the theme object to the component as a property.

          options.name (String [optional]): The name of the style sheet. Useful for debugging. If the value isn't provided, it will try to fallback to the name of the component.

          options.flip (Boolean [optional]): When set to false, this sheet will opt-out the rtl transformation. When set to true, the styles are inversed. When set to null, it follows theme.direction.

          The other keys are forwarded to the options argument of jss.createStyleSheet([styles], [options]).

    Returns

    higher-order component: Should be used to wrap a component.

    Ejemplos

import React from 'react';
import { withStyles } from '@material-ui/styles';

const styles = {
  root: {
    backgroundColor: 'red',
  },
};

class MyComponent extends React.Component {
  render () {
    return <div className={this.props.classes.root} />;
  }
}

export default withStyles(styles)(MyComponent);

    Also, you can use as decorators like so:

import React from 'react';
import { withStyles } from '@material-ui/styles';

const styles = {
  root: {
    backgroundColor: 'red',
  },
};

@withStyles(styles)
class MyComponent extends React.Component {
  render () {
    return <div className={this.props.classes.root} />;
  }
}

export default MyComponent

    withTheme(Component) => Component

    Provide the theme object as a property of the input component so it can be used in the render method.

    Arguments

      Component: The component that will be wrapped.

    Returns

    Component: The new component created. Does forward refs to the inner component.

    Ejemplos

import React from 'react';
import { withTheme } from '@material-ui/styles';

function MyComponent(props) {
  return <div>{props.theme.direction}</div>;
}

export default withTheme(MyComponent);


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Gallio.Common.Policies;
using Gallio.Runtime.Hosting;
using MbUnit.Framework;

namespace Gallio.Tests.Runtime.Hosting
{
    [TestsOn(typeof(HostConfiguration))]
    public class HostConfigurationTest
    {
        [Test]
        public void WriteToReencodesAccordingToTextWriter()
        {
            StringWriter writer = new StringWriter();
            Assert.AreEqual(Encoding.Unicode.EncodingName, writer.Encoding.EncodingName);

            HostConfiguration config = new HostConfiguration();
            config.WriteTo(writer);

            Assert.Contains(writer.ToString(), writer.Encoding.WebName);
        }

        [Test]
        public void WriteToReencodesAccordingToTextWriter_WhenConfigurationXmlContainsDifferentEncoding()
        {
            StringWriter writer = new StringWriter();
            Assert.AreEqual(Encoding.Unicode.EncodingName, writer.Encoding.EncodingName);

            HostConfiguration config = new HostConfiguration();
            config.ConfigurationXml = "<?xml version=\"1.0\" encoding=\"utf-32\"?><configuration />";
            config.WriteTo(writer);

            Assert.Contains(writer.ToString(), writer.Encoding.WebName);
        }

        [Test]
        public void WriteToThrowsIfTextWriterIsNull()
        {
            HostConfiguration config = new HostConfiguration();
            Assert.Throws<ArgumentNullException>(() => config.WriteTo(null));
        }

        [Test]
        public void WriteToFileThrowsIfPathIsNull()
        {
            HostConfiguration config = new HostConfiguration();
            Assert.Throws<ArgumentNullException>(() => config.WriteToFile(null));
        }

        [Test]
        public void WriteToFile()
        {
            HostConfiguration config = new HostConfiguration();
            string path = SpecialPathPolicy.For<HostConfigurationTest>().CreateTempFileWithUniqueName().FullName;
            try
            {
                config.WriteToFile(path);

                Assert.Contains(File.ReadAllText(path), "<configuration>");
            }
            finally
            {
                File.Delete(path);
            }
        }
    }
}


text:
//========= Copyright 2016-2017, HTC Corporation. All rights reserved. ===========

using System;
using Valve.VR;

namespace HTC.UnityPlugin.Vive
{
    /// <summary>
    /// Defines roles for those devices that have tracking data
    /// </summary>
    [ViveRoleEnum((int)DeviceRole.Invalid)]
    public enum DeviceRole
    {
        Invalid = -2,
        Hmd,
        Device1,
        Device2,
        Device3,
        Device4,
        Device5,
        Device6,
        Device7,
        Device8,
        Device9,
        Device10,
        Device11,
        Device12,
        Device13,
        Device14,
        Device15,
        [HideMamber]
        [Obsolete("Use HandRole.RightHand instead")]
        RightHand = Device1,
        [HideMamber]
        [Obsolete("Use HandRole.LeftHand instead")]
        LeftHand,
        [HideMamber]
        [Obsolete("Use HandRole.Controller3 instead")]
        Controller3,
        [HideMamber]
        [Obsolete("Use HandRole.Controller4 instead")]
        Controller4,
        [HideMamber]
        [Obsolete("Use HandRole.Controller5 instead")]
        Controller5,
        [HideMamber]
        [Obsolete("Use HandRole.Controller6 instead")]
        Controller6,
        [HideMamber]
        [Obsolete("Use HandRole.Controller7 instead")]
        Controller7,
        [HideMamber]
        [Obsolete("Use HandRole.Controller8 instead")]
        Controller8,
        [HideMamber]
        [Obsolete("Use HandRole.Controller9 instead")]
        Controller9,
        [HideMamber]
        [Obsolete("Use HandRole.Controller10 instead")]
        Controller10,
        [HideMamber]
        [Obsolete("Use HandRole.Controller11 instead")]
        Controller11,
        [HideMamber]
        [Obsolete("Use HandRole.Controller12 instead")]
        Controller12,
        [HideMamber]
        [Obsolete("Use HandRole.Controller13 instead")]
        Controller13,
        [HideMamber]
        [Obsolete("Use HandRole.Controller14 instead")]
        Controller14,
        [HideMamber]
        [Obsolete("Use HandRole.Controller15 instead")]
        Controller15,
    }

    public class DeviceRoleHandler : ViveRole.MapHandler<DeviceRole>
    {
        public override void OnInitialize() { Refresh(); }

        public override void OnConnectedDeviceChanged(uint deviceIndex, ETrackedDeviceClass deviceClass, string deviceSN, bool connected) { Refresh(); }

        public override void OnBindingChanged(DeviceRole role, string deviceSN, bool bound) { Refresh(); }

        public override void OnTrackedDeviceRoleChanged() { Refresh(); }

        public void Refresh()
        {
            UnmappingAll();

            var role = DeviceRole.Hmd;
            var deviceIndex = 0u;
            for (; role <= DeviceRole.Device15 && deviceIndex < ViveRole.MAX_DEVICE_COUNT; ++role, ++deviceIndex)
            {
                if (ViveRole.GetDeviceClass(deviceIndex) == ETrackedDeviceClass.Invalid) { continue; }
                MappingRoleIfUnbound(role, deviceIndex);
            }
        }
    }
}


text:
import sys, os
import pickle, subprocess
from mesonbuild.mesonlib import meson_command

# This could also be used for XCode.

def need_regen(regeninfo, regen_timestamp):
    for i in regeninfo.depfiles:
        curfile = os.path.join(regeninfo.build_dir, i)
        curtime = os.stat(curfile).st_mtime
        if curtime > regen_timestamp:
            return True
    # The timestamp file gets automatically deleted by MSBuild during a 'Clean' build.
    # We must make sure to recreate it, even if we do not regenerate the solution.
    # Otherwise, Visual Studio will always consider the REGEN project out of date.
    print("Everything is up-to-date, regeneration of build files is not needed.")
    from ..backend.vs2010backend import Vs2010Backend
    Vs2010Backend.touch_regen_timestamp(regeninfo.build_dir)
    return False

def regen(regeninfo, mesonscript, backend):
    cmd = meson_command + ['--internal',
                           'regenerate',
                           regeninfo.build_dir,
                           regeninfo.source_dir,
                           '--backend=' + backend]
    subprocess.check_call(cmd)

def run(args):
    private_dir = args[0]
    dumpfile = os.path.join(private_dir, 'regeninfo.dump')
    coredata = os.path.join(private_dir, 'coredata.dat')
    with open(dumpfile, 'rb') as f:
        regeninfo = pickle.load(f)
    with open(coredata, 'rb') as f:
        coredata = pickle.load(f)
    mesonscript = coredata.meson_script_launcher
    backend = coredata.get_builtin_option('backend')
    regen_timestamp = os.stat(dumpfile).st_mtime
    if need_regen(regeninfo, regen_timestamp):
        regen(regeninfo, mesonscript, backend)
    sys.exit(0)

if __name__ == '__main__':
    run(sys.argv[1:])


text:
#include "sign.h"

int tpm_sign(struct ecdaa_tpm_context *tpm_ctx,
             TPM2B_DIGEST *digest,
             TPMT_SIGNATURE *signature)
{
    TPMT_SIG_SCHEME inScheme;
    inScheme.scheme = TPM2_ALG_ECDAA;
	inScheme.details.ecdaa.hashAlg = TPM2_ALG_SHA256;
	inScheme.details.ecdaa.count = tpm_ctx->commit_counter;

    // Key _shouldn't_ be restricted, so no need for this
    TPMT_TK_HASHCHECK validation;
	validation.tag = TPM2_ST_HASHCHECK;
	validation.hierarchy = TPM2_RH_NULL;
	validation.digest.size = 0;

    tpm_ctx->last_return_code = Tss2_Sys_Sign(tpm_ctx->sapi_context,
                                              tpm_ctx->key_handle,
                                              &tpm_ctx->key_authentication_cmd,
                                              digest,
                                              &inScheme,
                                              &validation,
                                              signature,
                                              &tpm_ctx->last_auth_response_cmd);

    if (TSS2_RC_SUCCESS != tpm_ctx->last_return_code) {
        return -1;
    } else {
        return 0;
    }
}


text:
using System;
using NServiceBus;
using NServiceBus.Faults;
using NServiceBus.Transports;
using NServiceBus.Unicast.Queuing;
using Anotar.NLog;

namespace Xero.Bus.EventPublisher
{
	/// <summary>
	/// Custom FaultManager which doesn't freak out when serialization exceptions happen.
	/// </summary>
	public class EventPublisherFaultManager : IManageMessageFailures
	{
		Address localAddress;

		public Address ErrorQueue { get; set; }

		public void Init(Address address) {
			localAddress = address;
		}

		public void ProcessingAlwaysFailsForMessage(TransportMessage message, Exception e) {
			SendFailureMessage(message, e);
		}

		/// <summary>
		///     if the EventPublisher does not have the Xero assembly for the event it is trying to publish, serialization will
		///     fail and this will be the method called
		/// </summary>
		public void SerializationFailedForMessage(TransportMessage message, Exception e) {
			SendFailureMessage(message, e, true);
		}

		void SendFailureMessage(TransportMessage message, Exception e, bool serializationException = false) {
			SetExceptionHeaders(message, e);

			try {
				var destinationQ = ErrorQueue;

				// Intentionally service-locate ISendMessages to avoid circular resolution problem in the container
				var sender = Configure.Instance.Builder.Build<ISendMessages>();

				if (serializationException) {
        			LogTo.Error("Serialization failed for message - you probably haven't copied the relevant Xero.*.Events assembly into the bin dir for the EventPublisher");
					sender.Send(message, ErrorQueue);
					return;
				}

				sender.Send(message, destinationQ);

				LogTo.Error("Message has failed FLR and will be moved to the configured error queue, ID={0}.", message.Id);
			}
			catch (Exception exception) {
				var qnfEx = exception as QueueNotFoundException;
				string errorMessage;

				if (qnfEx != null) {
					errorMessage = string.Format("Could not forward failed message to error queue '{0}' as it could not be found.", qnfEx.Queue);
					LogTo.Fatal(errorMessage);
				}
				else {
					errorMessage = "Could not forward failed message to error queue.";
					LogTo.Fatal(errorMessage, exception);
				}

				throw new InvalidOperationException(errorMessage, exception);
			}
		}

		void SetExceptionHeaders(TransportMessage message, Exception e) {
			message.Headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName;

			if (e.InnerException != null) {
				message.Headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName;
			}

			message.Headers["NServiceBus.ExceptionInfo.Message"] = e.Message;
			message.Headers["NServiceBus.ExceptionInfo.Source"] = e.Source;
			message.Headers["NServiceBus.ExceptionInfo.StackTrace"] = e.ToString();

			var failedQ = localAddress ?? Address.Local;

			message.Headers[FaultsHeaderKeys.FailedQ] = failedQ.ToString();
			message.Headers["NServiceBus.TimeOfFailure"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
		}
	}
}


text:
var mongo_uri = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/test';
module.exports = {
  db: mongo_uri,

  sessionSecret: "Your Session Secret goes here",

  localAuth: true,

  mailgun: {
    login: 'Your Mailgun SMTP Username',
    password: 'Your Mailgun SMTP Password'
  },

  sendgrid: {
    user: 'Your SendGrid Username',
    password: 'Your SendGrid Password'
  },

  gmail: {
    user: 'Your Gmail Username',
    password: 'Your Gmail Password'
  },

  nyt: {
    key: 'Your New York Times API Key'
  },

  lastfm: {
    api_key: 'Your API Key',
    secret: 'Your API Secret'
  },

  facebookAuth: true,
  facebook: {
    clientID: '596026050480545',
    clientSecret: '7b8d834e9a8a6bd19d4158c59a1aaa3f',
    callbackURL: '/auth/facebook/callback',
    passReqToCallback: true
  },

  githubAuth: true,
  github: {
    clientID: 'Your Client ID',
    clientSecret: 'Your Client Secret',
    callbackURL: '/auth/github/callback',
    passReqToCallback: true
  },

  twitterAuth: true,
  twitter: {
    consumerKey: 'MBq17Fuoa7J00RgtJQ0hPA',
    consumerSecret: 'G5lkVNyFLUAuKDslCS2AlWNEXUd1GovKnm9k0QofZk',
    callbackURL: '/auth/twitter/callback',
    passReqToCallback: true
  },

  googleAuth: true,
  google: {
    clientID: '875444853115-3p0i3a9tpv8osr6hstqumsucftdb0bjn.apps.googleusercontent.com',
    clientSecret: 'Hvg4t7TR9HvUt6to-Vb3e7il',
    callbackURL: '/auth/google/callback',
    passReqToCallback: true
  },

  steam: {
    apiKey: 'Your Steam API Key'
  },

  twilio: {
    sid: 'Your Account SID',
    token: 'Your Auth Token'
  },

  tumblr: {
    consumerKey: 'Your Consumer Key',
    consumerSecret: 'Your Consumer Secret',
    callbackURL: '/auth/tumblr/callback'
  },

  foursquare: {
    clientId: 'Your Client ID',
    clientSecret: 'Your Client Secret',
    redirectUrl: 'http://localhost:3000/auth/foursquare/callback'
  },

  venmo: {
    clientId: 'Your Venmo Client ID',
    clientSecret: 'Your Venmo Client Secret',
    redirectUrl: 'http://localhost:3000/auth/venmo/callback'
  },

  paypal: {
    host: 'api.sandbox.paypal.com', // or api.paypal.com
    client_id: 'Your Client ID',
    client_secret: 'Your Client Secret',
    returnUrl: 'http://localhost:3000/api/paypal/success',
    cancelUrl: 'http://localhost:3000/api/paypal/cancel'
  }
};


text:
#!/usr/local/bin/php
<?php

error_reporting(E_ALL);
ini_set('display_errors', true);

include 'util.php';
include 'solver.php';
include 'reader.php';

function usage($path)
{
	echo "Usage: $path knowledge.xml [goal]";
	exit;
}

function main($argc, $argv)
{
	if ($argc < 2 || $argc > 3)
		usage($argv[0]);

	// Als '-v' is meegegeven tijdens het starten, ga in verbose mode
	if ($argv[1] == '-v')
	{
		verbose(true);
		$argc--;
		array_shift($argv);
	}
	else
		verbose(false);

	// Reader voor de XML-bestanden
	$reader = new KnowledgeBaseReader;

	// Parse een xml-bestand (het eerste argument) tot knowledge base
	$state = $reader->parse($argv[1]);

	// Start de solver, dat ding dat kan infereren
	$solver = new Solver;

	// leid alle goals in de knowledge base af.
	$goals = $state->goals;

	// Begin met de doelen die we hebben op de goal stack te zetten
	foreach($goals as $goal)
		$state->goalStack->push($goal->name);

	// Zo lang we nog vragen kunnen stellen, stel ze
	while (($question = $solver->solveAll($state)) instanceof AskedQuestion)
	{
		$answer = cli_ask($question);

		if ($answer instanceof Option)
			$state->apply($answer->consequences,
				Yes::because("User answered '{$answer->description}' to '{$question->description}'"));
	}

	// Geen vragen meer, print de gevonden oplossingen.
	foreach ($goals as $goal)
	{
		printf("%s: %s\n",
			$goal->description,
			$goal->answer($state)->description);
	}
}

/**
 * Stelt een vraag op de terminal, en blijf net zo lang wachten totdat
 * we een zinnig antwoord krijgen.
 *
 * @return Option
 */
function cli_ask(Question $question)
{
	echo $question->description . "\n";

	for ($i = 0; $i < count($question->options); ++$i)
		printf("%2d) %s\n", $i + 1, $question->options[$i]->description);

	if ($question->skippable)
		printf("%2d) weet ik niet\n", ++$i);

	do {
		$response = fgetc(STDIN);

		$choice = @intval(trim($response));

		if ($choice > 0 && $choice <= count($question->options))
			return $question->options[$choice - 1];

		if ($question->skippable && $choice == $i)
			return null;

	} while (true);
}

main($argc, $argv);


text:
package datomisca

final class Datom(val underlying: datomic.Datom) extends AnyVal {

  def id:     Long    = underlying.e.asInstanceOf[Long]
  def attrId: Int     = underlying.a.asInstanceOf[Integer]
  def value:  Any     = Convert.toScala(underlying.v)
  def tx:     Long    = underlying.tx.asInstanceOf[Long]
  def added:  Boolean = underlying.added

}

object Datom {
   def unapply(da: Datom): Option[(Long, Int, Any, Long, Boolean)] =
    Some((da.id,da.attrId,da.value,da.tx,da.added))
}


text:
<?php

use Doctrine\ORM\Mapping as ORM;

/**
 * Chamados
 *
 * @ORM\Table(name="chamados", indexes={@ORM\Index(name="fk_chamados_ticket1", columns={"ticket_idticket"}), @ORM\Index(name="fk_chamados_clientes1", columns={"clientes_idclientes"}), @ORM\Index(name="fk_chamados_login1", columns={"login_idlogin"})})
 * @ORM\Entity
 */
class Chamados
{
    /**
     * @var integer
     *
     * @ORM\Column(name="idchamados", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idchamados;

    /**
     * @var string
     *
     * @ORM\Column(name="titulo", type="string", length=50, nullable=true)
     */
    private $titulo;

    /**
     * @var string
     *
     * @ORM\Column(name="mensagem", type="text", length=65535, nullable=true)
     */
    private $mensagem;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dataRegsitro", type="datetime", nullable=true)
     */
    private $dataregsitro;

    /**
     * @var string
     *
     * @ORM\Column(name="laudo", type="text", length=65535, nullable=true)
     */
    private $laudo;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dataLaudo", type="datetime", nullable=true)
     */
    private $datalaudo;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="string", length=20, nullable=true)
     */
    private $status;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dataPrevisao", type="date", nullable=true)
     */
    private $dataprevisao;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dataCadastro", type="datetime", nullable=false)
     */
    private $datacadastro;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dataUpdate", type="datetime", nullable=true)
     */
    private $dataupdate;

    /**
     * @var \Clientes
     *
     * @ORM\ManyToOne(targetEntity="Clientes")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="clientes_idclientes", referencedColumnName="idclientes")
     * })
     */
    private $clientesclientes;

    /**
     * @var \Login
     *
     * @ORM\ManyToOne(targetEntity="Login")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="login_idlogin", referencedColumnName="idlogin")
     * })
     */
    private $loginlogin;

    /**
     * @var \Ticket
     *
     * @ORM\ManyToOne(targetEntity="Ticket")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="ticket_idticket", referencedColumnName="idticket")
     * })
     */
    private $ticketticket;

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.danielfireman.gci.jooby</groupId>
  <artifactId>gci-jooby</artifactId>
  <packaging>jar</packaging>
  <version>0.1</version>
  <name>gci-jooby</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jooby</groupId>
      <artifactId>jooby</artifactId>
      <version>1.0.1</version>
    </dependency>
    <dependency>
      <groupId>com.danielfireman</groupId>
      <artifactId>gci</artifactId>
      <version>0.1</version>
    </dependency>
  </dependencies>
</project>


text:
<?php

namespace Oito\Micro\Plugin;

use \Symfony\Component\Translation\Translator;
use \Symfony\Component\Translation\MessageSelector;
use \Symfony\Component\Translation\Loader\ArrayLoader;

class Translation extends \Oito\Micro\AbstractPlugin {

    public function getPluginName() {
        return 'translation';
    }

    public function initPlugin() {
        $this->app[$this->getPluginName()] = function ($app) {
            $locale     = $app['app.locale'] ? : $app->config('app.locale.default')? : 'en_US';
            $translator = new Translator($locale, new MessageSelector());
            $translator->addLoader('array', new ArrayLoader());

            $app->event()->emit('plugin.translation.after', [$app, $translator]);

            return $translator;
        };
    }

}


text:
import React from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom'
import { matchRoutes } from 'react-router-config'
import { Provider } from 'react-redux'
import routes from '../../client/routes'
import Html from '../markup/Html'
import { store } from '../../client/misc'

export default function(req, res) {
  // We need require app in each request for hot server updates
  const App = require('../../client/layouts/App').default

  webpackIsomorphicTools.refresh()

  const renderHtml = (store, appString) => {
    const html = renderToStaticMarkup(
      <Html
        store={store}
        appString={appString}
      />
    )

    return `<!doctype html>${html}`
  }

  // If __DISABLE_SSR__ = true, disable server side rendering
  if (__DISABLE_SSR__) {
    res.send(renderHtml(store))

    return
  }

  // Load data on server-side
  const loadBranchData = () => {
    const branch = matchRoutes(routes, req.url)

    const promises = branch.map(({ route, match }) => {
      // Dispatch the action(s) through the loadData method of "./routes.js"
      if (route.loadData) {
        return route.loadData(store.dispatch, match.params)
      }

      return Promise.resolve(null)
    })

    return Promise.all(promises)
  }

  // Send response after all the action(s) are dispathed
  loadBranchData()
    .then(() => {
      // Setup React-Router server-side rendering
      const routerContext = {}

      const app = (
        <Provider store={store}>
          <StaticRouter location={req.url} context={routerContext}>
            <App />
          </StaticRouter>
        </Provider>
      )

      // Check if the render result contains a redirect, if so we need to set
      // the specific status and redirect header and end the response
      if (routerContext.url) {
        res.status(301).setHeader('Location', routerContext.url)
        res.end()

        return
      }

      // Checking is page is 404
      const status = routerContext.status === '404' ? 404 : 200

      // We can now render our app
      const appString = renderToString(app)

      // Pass the route and initial state into html template
      res.status(status).send(renderHtml(store, appString))
    })
    .catch(err => {
      res.status(404).send('Not Found :(')
      console.error(`==> 😭  Rendering routes error: ${err}`)
    })
}


text:
<?php

namespace ZendTest\Form;

use Interop\Container\ContainerInterface;
use PHPUnit\Framework\TestCase;
use Zend\Form\ElementInterface;
use Zend\Form\Element\Number;
use Zend\Form\FormElementManager;
use Zend\Form\FormElementManagerFactory;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementManagerFactoryTest extends TestCase
{
    public function testFactoryReturnsPluginManager()
    {
        $container = $this->prophesize(ContainerInterface::class)->reveal();
        $factory = new FormElementManagerFactory();

        $elements = $factory($container, FormElementManager::class);
        $this->assertInstanceOf(FormElementManager::class, $elements);

        if (method_exists($elements, 'configure')) {
            // zend-servicemanager v3
            $this->assertAttributeSame($container, 'creationContext', $elements);
        } else {
            // zend-servicemanager v2
            $this->assertSame($container, $elements->getServiceLocator());
        }
    }

    /**
     * @depends testFactoryReturnsPluginManager
     */
    public function testFactoryConfiguresPluginManagerUnderContainerInterop()
    {
        $container = $this->prophesize(ContainerInterface::class)->reveal();
        $element = $this->prophesize(ElementInterface::class)->reveal();

        $factory = new FormElementManagerFactory();
        $elements = $factory($container, FormElementManager::class, [
            'services' => [
                'test' => $element,
            ],
        ]);
        $this->assertSame($element, $elements->get('test'));
    }

    /**
     * @depends testFactoryReturnsPluginManager
     */
    public function testFactoryConfiguresPluginManagerUnderServiceManagerV2()
    {
        $container = $this->prophesize(ServiceLocatorInterface::class);
        $container->willImplement(ContainerInterface::class);

        $element = $this->prophesize(ElementInterface::class)->reveal();

        $factory = new FormElementManagerFactory();
        $factory->setCreationOptions([
            'services' => [
                'test' => $element,
            ],
        ]);

        $elements = $factory->createService($container->reveal());
        $this->assertSame($element, $elements->get('test'));
    }

    public function testConfiguresFormElementsServicesWhenFound()
    {
        $element = $this->prophesize(ElementInterface::class)->reveal();
        $config = [
            'form_elements' => [
                'aliases' => [
                    'test' => Number::class,
                ],
                'factories' => [
                    'test-too' => function ($container) use ($element) {
                        return $element;
                    },
                ],
            ],
        ];

        $container = $this->prophesize(ServiceLocatorInterface::class);
        $container->willImplement(ContainerInterface::class);

        $container->has('ServiceListener')->willReturn(false);
        $container->has('config')->willReturn(true);
        $container->get('config')->willReturn($config);

        $factory = new FormElementManagerFactory();
        $elements = $factory($container->reveal(), 'FormElementManager');

        $this->assertInstanceOf(FormElementManager::class, $elements);
        $this->assertTrue($elements->has('test'));
        $this->assertInstanceOf(Number::class, $elements->get('test'));
        $this->assertTrue($elements->has('test-too'));
        $this->assertSame($element, $elements->get('test-too'));
    }

    public function testDoesNotConfigureFormElementsServicesWhenServiceListenerPresent()
    {
        $element = $this->prophesize(ElementInterface::class)->reveal();
        $config = [
            'form_elements' => [
                'aliases' => [
                    'test' => Number::class,
                ],
                'factories' => [
                    'test-too' => function ($container) use ($element) {
                        return $element;
                    },
                ],
            ],
        ];

        $container = $this->prophesize(ServiceLocatorInterface::class);
        $container->willImplement(ContainerInterface::class);

        $container->has('ServiceListener')->willReturn(true);
        $container->has('config')->shouldNotBeCalled();
        $container->get('config')->shouldNotBeCalled();

        $factory = new FormElementManagerFactory();
        $elements = $factory($container->reveal(), 'FormElementManager');

        $this->assertInstanceOf(FormElementManager::class, $elements);
        $this->assertFalse($elements->has('test'));
        $this->assertFalse($elements->has('test-too'));
    }

    public function testDoesNotConfigureFormElementsServicesWhenConfigServiceNotPresent()
    {
        $container = $this->prophesize(ServiceLocatorInterface::class);
        $container->willImplement(ContainerInterface::class);

        $container->has('ServiceListener')->willReturn(false);
        $container->has('config')->willReturn(false);
        $container->get('config')->shouldNotBeCalled();

        $factory = new FormElementManagerFactory();
        $elements = $factory($container->reveal(), 'FormElementManager');

        $this->assertInstanceOf(FormElementManager::class, $elements);
    }

    public function testDoesNotConfigureFormElementServicesWhenConfigServiceDoesNotContainFormElementsConfig()
    {
        $container = $this->prophesize(ServiceLocatorInterface::class);
        $container->willImplement(ContainerInterface::class);

        $container->has('ServiceListener')->willReturn(false);
        $container->has('config')->willReturn(true);
        $container->get('config')->willReturn(['foo' => 'bar']);
        $container->has('MvcTranslator')->willReturn(false); // necessary due to default initializers

        $factory = new FormElementManagerFactory();
        $elements = $factory($container->reveal(), 'FormElementManager');

        $this->assertInstanceOf(FormElementManager::class, $elements);
        $this->assertFalse($elements->has('foo'));
    }
}


text:
static long sys_mprotect(void* addr, size_t len, int prot)
{
    if ((uintptr_t) addr & 0xFFF) {
        return -EINVAL;
    }
    if (len & 0xFFF) {
        return -EINVAL;
    }
    // TODO: mprotect(0x900000, 86016, 3) = -38 Function not implemented
    if (prot == 0x3) // read & write
    {
        // all the heap is already read/write
        return 0;
    }
    return -EINVAL;
}

extern "C"
long syscall_SYS_mprotect(void *addr, size_t len, int prot)
{
  return stubtrace(sys_mprotect, "mprotect", addr, len, prot);
}


text:
API_ERROR = {
    100: 'Unknown error',
    101: 'Invalid parameter',
    102: 'The requested API does not exist',
    103: 'The requested method does not exist',
    104: 'The requested version does not support the functionality',
    105: 'The logged in session does not have permission',
    106: 'Session timeout',
    107: 'Session interrupted by duplicate login'
}

class CGIException(Exception):
    pass

class ConsumerFactoryException(Exception):
    pass

class SynologyException(Exception):
    pass


text:
10-adic numbers
===============

The [TenAdic.hs](TenAdic.hs) file contains an experimental implementation of 10-adic numbers
including basic arithmetic (addition, multiplication, negation). Haskell provides subtraction
and exponentiation by a natural number for free.

It is best to try it out by firing up Haskell interpreter:

```
$ ghci TenAdic.hs
```

The infinite sequence of nines is represented by the `Nines` constructor,
similarly with `Zeros`. A digit can be appended using the `:~` operator.
Decimal digits are represented by constructors `D0` to `D9`.

A few examples:

```Haskell
λ> Zeros :~ D3         --  (3)
...00003

λ> Nines               -- (-1)
...9999

λ> Nines :~ D5         -- (-5)
...99995

λ> Zeros :~ D1 :~ D4   -- (14)
...000014
```

Adding a nine to an infinite stream of nines is the same thing:

```Haskell
λ> (Nines :~ D9) == Nines
True
```

Let's try some arithmetic (`:~` has a low operator precedence, parenthesise carefully):

```Haskell
λ> (Zeros :~ D3) - (Zeros :~ D7)
...99996

λ> Nines + (Zeros :~ D1)
...0000

λ> Nines * Nines
...00001
```

We can convert 10-adic number to a regular integer:

```Haskell
λ> (Nines :~ D7)
...99997

λ> asInteger (Nines :~ D7)
-3
```

Numeric literals work provided we give the interpreter type hint we want a `TenAdic` number:

```Haskell
λ> -762241 :: TenAdic
...9999237759

λ> [ x^3 | x <- [-6..2] ] :: [TenAdic]
[...9999784,...9999875,...9999936,...9999973,...9999992,...9999,...0000,...00001,...00008]
```

That's it for now, have fun.


text:
import { Template } from 'meteor/templating';

Template.Scoreboard_Page.onCreated(function scoreboardPageOnCreated() {
  // add your statement here
});

Template.Scoreboard_Page.helpers({
  // add your helpers here
});

Template.Scoreboard_Page.events({
  // add your events here
});

Template.Scoreboard_Page.onRendered(function scoreboardPageOnRendered() {
  // add your statement here
});

Template.Scoreboard_Page.onDestroyed(function scoreboardPageOnDestroyed() {
  // add your statement here
});


text:
from django.conf import settings
from django.template import Library

register = Library()

def filer_actions(context):
    """
    Track the number of times the action field has been rendered on the page,
    so we know which value to use.
    """
    context['action_index'] = context.get('action_index', -1) + 1
    return context
filer_actions = register.inclusion_tag("admin/filer/actions.html", takes_context=True)(filer_actions)

ADMIN_ICON_BASE = "%sadmin/img/" % settings.STATIC_URL
ADMIN_CSS_BASE = "%sadmin/css/" % settings.STATIC_URL
ADMIN_JS_BASE = "%sadmin/js/" % settings.STATIC_URL

@register.simple_tag
def admin_icon_base():
    return ADMIN_ICON_BASE

@register.simple_tag
def admin_css_base():
    return ADMIN_CSS_BASE

@register.simple_tag
def admin_js_base():
    return ADMIN_JS_BASE