text:
namespace Microsoft.Azure.Management.Storage.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    public partial class SshPublicKey
    {
        /// <summary>
        /// Initializes a new instance of the SshPublicKey class.
        /// </summary>
        public SshPublicKey()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SshPublicKey class.
        /// </summary>
        /// <param name="description">Optional. It is used to store the
        /// function/usage of the key</param>
        /// <param name="key">Ssh public key base64 encoded. The format should
        /// be: '<keyType> <keyData>', e.g. ssh-rsa
        /// AAAABBBB</param>
        public SshPublicKey(string description = default(string), string key = default(string))
        {
            Description = description;
            Key = key;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets optional. It is used to store the function/usage of
        /// the key
        /// </summary>
        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets ssh public key base64 encoded. The format should be:
        /// '&lt;keyType&gt; &lt;keyData&gt;', e.g. ssh-rsa
        /// AAAABBBB
        /// </summary>
        [JsonProperty(PropertyName = "key")]
        public string Key { get; set; }

    }
}


text:
module.exports = function () {
    return function (req, res, next) {
        next(Object.assign(new Error('Not Found'), {status: 404}));
    };
};

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Training
permalink: /training/
---

I've put together a few trainings over the years.

* [Git basics](https://docs.google.com/presentation/d/1XW3vkiFaHgD0q5CElGI1Tm_4OsrR3Fz08d327ZJGC6s/edit?usp=sharing)
* [JavaScript](https://docs.google.com/presentation/d/1UJI86XO1mhirNzfferJmszWG32b0nE1OgQw3g5dA7gs/edit?usp=sharing)
* [The Future of the Web](https://docs.google.com/presentation/d/1nICnEH5NN4Q59tMO1DHl5_JI0kN9KjRtO99ct5GIr8k/edit?usp=sharing) (note: I'm not quite as gung-ho about web components as the future of web development as I was at the time I wrote this)


text:
<?php
//
namespace App\Http\Controllers\v2;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\v2\UserAddress;
use App\Models\v2\Features;
use App\Helper\Token;

class ConsigneeController extends Controller {

    /**
    * POST ecapi.consignee.list
    */
    public function index(Request $request)
    {
        $data = UserAddress::getList($this->validated);
        return $this->json($data);
    }

    /**
    * POST ecapi.consignee.add
    */
    public function add(Request $request)
    {
        $rules = [
            'name'      => 'required|string|min:2|max:15',
            'mobile'    => 'numeric|required_without:tel',
            'tel'       => 'string|required_without:mobile',
            'zip_code'  => 'numeric',
            'region'    => 'required|integer|min:1',
            'address'   => 'required|string',
            'identity'  => 'string|min:2|max:19',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }
        $data = UserAddress::add($this->validated);

        return $this->json($data);
    }

    /**
    * POST ecapi.consignee.delete
    */
    public function remove(Request $request)
    {
        $rules = [
            'consignee' => 'required|integer|min:1',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = UserAddress::remove($this->validated);
        return $this->json($data);
    }

    /**
    * POST ecapi.consignee.update
    */
    public function modify(Request $request)
    {
        $rules = [
            'consignee' => 'required|integer|min:1',
            'name'      => 'required|string|min:2|max:15',
            'mobile'    => 'numeric|required_without:tel',
            'tel'       => 'string|required_without:mobile',
            'zip_code'  => 'numeric',
            'region'    => 'required|integer|min:1',
            'address'   => 'required|string',
            'identity'  => 'string|min:2|max:19',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = UserAddress::modify($this->validated);

        return $this->json($data);
    }

    /**
    * POST ecapi.consignee.setDefault
    */
    public function setDefault(Request $request)
    {

        $rules = [
            'consignee' => 'required|integer|min:1',
        ];

        if($res = Features::check('address.default'))
        {
            return $this->json($res);
        }

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = UserAddress::setDefault($this->validated);

        return $this->json($data);
    }
}


text:
<?php
/**
 * Created by Suley.
 * @author: suley<dearsuley@gmail.com>
 * @date: 1/21/14
 * @time: 11:24 AM
 */

class VisaOrderCustomer extends CActiveRecord{
    public $ids;
    const STATUS_DEFAULT = 0;
    const STATUS_SENTOUT = 1;
    const STATUS_ISSUED = 2;
    const STATUS_REJECT = 3;
    const STATUS_DELETED = 4;

    public static function model($className = __CLASS__){
        return parent::model($className);
    }
    public function tableName(){
        return 'visa_order_customer';
    }
    public function relations(){
        return array(
            'order'=>array(self::BELONGS_TO, 'VisaOrder', 'visa_order_id'),
            'agencyType'=>array(self::BELONGS_TO, 'VisaTypeAgency', 'agency_id'),
            'financeRecord'=>array(self::HAS_ONE, 'FinanceItems', 'vid', 'on'=>'financeRecord.type = "'.FinanceItems::TYPE_VISA_CUSTOMER.'"')
        );
    }
    public function rules(){
        return array(
            array('name, passport, create_time, is_pay, price, cost_price, agency_id, status, visa_order_id', 'safe')
        );
    }
    public function attributeLabels(){
        return array(
          'name'=>'姓名', 'cost_price'=>'成本价', 'price'=>'售价', 'is_pay'=>'支付状态','passport'=>'护照', 'agencyType'=>'送签渠道', 'agency_id'=>'送签渠道', 'status'=>'状态'
        );
    }

    public function getUnpayoutAmount(){
        $criteria = new CDbCriteria();
        $criteria->addCondition('is_payout != 1');
        $criteria->select = "SUM()";
        return $this->commandBuilder->createFindCommand($this->getTableSchema(),$criteria)->queryScalar();
    }
    public function beforeSave(){
        if($this->isNewRecord){
            $this->status = self::STATUS_DEFAULT;
            $this->create_time = strtotime('now');
        }else{
            $oldRecord = self::model()->findByPk($this->id);
            $orderModel = VisaOrder::model()->findByPk($this->visa_order_id);
            if($oldRecord->status != $this->status && $this->status == self::STATUS_SENTOUT){
                $agencyModel = VisaTypeAgency::model()->findByPk($this->agency_id);

                $orderModel->memo = $orderModel->memo."\n".date('Y-m-d H:i')." 客户".$this->name."[".$this->passport."]送签到渠道【".$agencyModel->agency->name."】,操作:".User::getUserRealname(Yii::app()->user->id);

                if(self::checkAllCustomerSent($this->visa_order_id, $this->id)){
                    $orderModel->memo = $orderModel->memo."\n".date('Y-m-d H:i')." 订单所有客户送签完毕,订单状态修改为【全部送签】,操作:".User::getUserRealname(Yii::app()->user->id);
                    $orderModel->status = VisaOrder::STATUS_SENTOUT;
                }elseif($orderModel->status != VisaOrder::STATUS_PARTIAL_SENT){
                    $orderModel->memo = $orderModel->memo."\n".date('Y-m-d H:i')." 订单部分客户已经送签,订单状态修改为【部分送签】,操作:".User::getUserRealname(Yii::app()->user->id);
                    $orderModel->status = VisaOrder::STATUS_PARTIAL_SENT;
                }
                $orderModel->save();
            }
            if($oldRecord->status != $this->status && $this->status == self::STATUS_REJECT){
                $orderModel->memo = $orderModel->memo."\n".date('Y-m-d H:i')." 客户".$this->name."[".$this->passport."]被拒签,操作:".User::getUserRealname(Yii::app()->user->id);
                $orderModel->save();
            }
            if($oldRecord->status != $this->status && $this->status == self::STATUS_DELETED){
                $orderModel->memo = $orderModel->memo."\n".date('Y-m-d H:i')." 客户".$this->name."[".$this->passport."]被删除,操作:".User::getUserRealname(Yii::app()->user->id);
                $orderModel->save();
            }
        }
        return parent::beforeSave();
    }

    public static function checkAllCustomerSent($id, $excludeId){
        //$count = self::model()->count("status IN (:default, :sent, :issued, :reject)", array(':default'=>self::STATUS_DEFAULT, ':sent'=>self::STATUS_SENTOUT, ':issued'=>self::STATUS_ISSUED, ':reject'=>self::STATUS_REJECT));
        $count = self::model()->count("visa_order_id = :order_id AND status IN (:default) AND id NOT IN (:exclude_id)", array(':default'=>self::STATUS_DEFAULT, ':order_id'=>$id, ':exclude_id'=>$excludeId));
        error_log("Count:".$count);
        if($count >= 1){
            return false;
        }else{
            return true;
        }
    }

    public function search(){
        $criteria = new CDbCriteria;

        if(is_array($this->id)){
            $criteria->addInCondition('id', $this->id);
        }else{
            $criteria->compare('id', $this->id);
        }

        return new CActiveDataProvider('VisaOrderCustomer', array(
           'criteria'=>$criteria
        ));
    }
}


text:
package edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.policies;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
import org.eclipse.gmf.runtime.diagram.ui.commands.DeferredLayoutCommand;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.commands.SetViewMutabilityCommand;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CanonicalEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewRequest;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.Edge;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.update.UpdaterLinkDescriptor;

import edu.thu.ggxx.hellobrazil.wc2014.Wc2014Package;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.EliminationMatchEditPart;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.GroupEditPart;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.GroupMatchEditPart;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.TeamEditPart;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.WorldCupEditPart;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.part.Wc2014DiagramUpdater;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.part.Wc2014LinkDescriptor;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.part.Wc2014NodeDescriptor;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.part.Wc2014VisualIDRegistry;

/**
 * @generated
 */
public class WorldCupCanonicalEditPolicy extends CanonicalEditPolicy {

	/**
	 * @generated
	 */
	private Set<EStructuralFeature> myFeaturesToSynchronize;

	/**
	 * @generated
	 */
	protected void refreshOnActivate() {
		// Need to activate editpart children before invoking the canonical refresh for EditParts to add event listeners
		List<?> c = getHost().getChildren();
		for (int i = 0; i < c.size(); i++) {
			((EditPart) c.get(i)).activate();
		}
		super.refreshOnActivate();
	}

	/**
	 * @generated
	 */
	protected Set getFeaturesToSynchronize() {
		if (myFeaturesToSynchronize == null) {
			myFeaturesToSynchronize = new HashSet<EStructuralFeature>();
			myFeaturesToSynchronize.add(Wc2014Package.eINSTANCE
					.getWorldCup_Matches());
			myFeaturesToSynchronize.add(Wc2014Package.eINSTANCE
					.getWorldCup_Teams());
			myFeaturesToSynchronize.add(Wc2014Package.eINSTANCE
					.getWorldCup_Groups());
		}
		return myFeaturesToSynchronize;
	}

	/**
	 * @generated
	 */
	@SuppressWarnings("rawtypes")
	protected List getSemanticChildrenList() {
		View viewObject = (View) getHost().getModel();
		LinkedList<EObject> result = new LinkedList<EObject>();
		List<Wc2014NodeDescriptor> childDescriptors = Wc2014DiagramUpdater
				.getWorldCup_1000SemanticChildren(viewObject);
		for (Wc2014NodeDescriptor d : childDescriptors) {
			result.add(d.getModelElement());
		}
		return result;
	}

	/**
	 * @generated
	 */
	protected boolean isOrphaned(Collection<EObject> semanticChildren,
			final View view) {
		return isMyDiagramElement(view)
				&& !semanticChildren.contains(view.getElement());
	}

	/**
	 * @generated
	 */
	private boolean isMyDiagramElement(View view) {
		int visualID = Wc2014VisualIDRegistry.getVisualID(view);
		switch (visualID) {
		case EliminationMatchEditPart.VISUAL_ID:
		case TeamEditPart.VISUAL_ID:
		case GroupEditPart.VISUAL_ID:
		case GroupMatchEditPart.VISUAL_ID:
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected void refreshSemantic() {
		if (resolveSemanticElement() == null) {
			return;
		}
		LinkedList<IAdaptable> createdViews = new LinkedList<IAdaptable>();
		List<Wc2014NodeDescriptor> childDescriptors = Wc2014DiagramUpdater
				.getWorldCup_1000SemanticChildren((View) getHost().getModel());
		LinkedList<View> orphaned = new LinkedList<View>();
		// we care to check only views we recognize as ours
		LinkedList<View> knownViewChildren = new LinkedList<View>();
		for (View v : getViewChildren()) {
			if (isMyDiagramElement(v)) {
				knownViewChildren.add(v);
			}
		}
		// alternative to #cleanCanonicalSemanticChildren(getViewChildren(), semanticChildren)
		//
		// iteration happens over list of desired semantic elements, trying to find best matching View, while original CEP
		// iterates views, potentially losing view (size/bounds) information - i.e. if there are few views to reference same EObject, only last one
		// to answer isOrphaned == true will be used for the domain element representation, see #cleanCanonicalSemanticChildren()
		for (Iterator<Wc2014NodeDescriptor> descriptorsIterator = childDescriptors
				.iterator(); descriptorsIterator.hasNext();) {
			Wc2014NodeDescriptor next = descriptorsIterator.next();
			String hint = Wc2014VisualIDRegistry.getType(next.getVisualID());
			LinkedList<View> perfectMatch = new LinkedList<View>(); // both semanticElement and hint match that of NodeDescriptor
			for (View childView : getViewChildren()) {
				EObject semanticElement = childView.getElement();
				if (next.getModelElement().equals(semanticElement)) {
					if (hint.equals(childView.getType())) {
						perfectMatch.add(childView);
						// actually, can stop iteration over view children here, but
						// may want to use not the first view but last one as a 'real' match (the way original CEP does
						// with its trick with viewToSemanticMap inside #cleanCanonicalSemanticChildren
					}
				}
			}
			if (perfectMatch.size() > 0) {
				descriptorsIterator.remove(); // precise match found no need to create anything for the NodeDescriptor
				// use only one view (first or last?), keep rest as orphaned for further consideration
				knownViewChildren.remove(perfectMatch.getFirst());
			}
		}
		// those left in knownViewChildren are subject to removal - they are our diagram elements we didn't find match to,
		// or those we have potential matches to, and thus need to be recreated, preserving size/location information.
		orphaned.addAll(knownViewChildren);
		//
		ArrayList<CreateViewRequest.ViewDescriptor> viewDescriptors = new ArrayList<CreateViewRequest.ViewDescriptor>(
				childDescriptors.size());
		for (Wc2014NodeDescriptor next : childDescriptors) {
			String hint = Wc2014VisualIDRegistry.getType(next.getVisualID());
			IAdaptable elementAdapter = new CanonicalElementAdapter(
					next.getModelElement(), hint);
			CreateViewRequest.ViewDescriptor descriptor = new CreateViewRequest.ViewDescriptor(
					elementAdapter, Node.class, hint, ViewUtil.APPEND, false,
					host().getDiagramPreferencesHint());
			viewDescriptors.add(descriptor);
		}

		boolean changed = deleteViews(orphaned.iterator());
		//
		CreateViewRequest request = getCreateViewRequest(viewDescriptors);
		Command cmd = getCreateViewCommand(request);
		if (cmd != null && cmd.canExecute()) {
			SetViewMutabilityCommand.makeMutable(
					new EObjectAdapter(host().getNotationView())).execute();
			executeCommand(cmd);
			@SuppressWarnings("unchecked")
			List<IAdaptable> nl = (List<IAdaptable>) request.getNewObject();
			createdViews.addAll(nl);
		}
		if (changed || createdViews.size() > 0) {
			postProcessRefreshSemantic(createdViews);
		}

		Collection<IAdaptable> createdConnectionViews = refreshConnections();

		if (createdViews.size() > 1) {
			// perform a layout of the container
			DeferredLayoutCommand layoutCmd = new DeferredLayoutCommand(host()
					.getEditingDomain(), createdViews, host());
			executeCommand(new ICommandProxy(layoutCmd));
		}

		createdViews.addAll(createdConnectionViews);

		makeViewsImmutable(createdViews);
	}

	/**
	 * @generated
	 */
	private Collection<IAdaptable> refreshConnections() {
		Domain2Notation domain2NotationMap = new Domain2Notation();
		Collection<Wc2014LinkDescriptor> linkDescriptors = collectAllLinks(
				getDiagram(), domain2NotationMap);
		Collection existingLinks = new LinkedList(getDiagram().getEdges());
		for (Iterator linksIterator = existingLinks.iterator(); linksIterator
				.hasNext();) {
			Edge nextDiagramLink = (Edge) linksIterator.next();
			int diagramLinkVisualID = Wc2014VisualIDRegistry
					.getVisualID(nextDiagramLink);
			if (diagramLinkVisualID == -1) {
				if (nextDiagramLink.getSource() != null
						&& nextDiagramLink.getTarget() != null) {
					linksIterator.remove();
				}
				continue;
			}
			EObject diagramLinkObject = nextDiagramLink.getElement();
			EObject diagramLinkSrc = nextDiagramLink.getSource().getElement();
			EObject diagramLinkDst = nextDiagramLink.getTarget().getElement();
			for (Iterator<Wc2014LinkDescriptor> linkDescriptorsIterator = linkDescriptors
					.iterator(); linkDescriptorsIterator.hasNext();) {
				Wc2014LinkDescriptor nextLinkDescriptor = linkDescriptorsIterator
						.next();
				if (diagramLinkObject == nextLinkDescriptor.getModelElement()
						&& diagramLinkSrc == nextLinkDescriptor.getSource()
						&& diagramLinkDst == nextLinkDescriptor
								.getDestination()
						&& diagramLinkVisualID == nextLinkDescriptor
								.getVisualID()) {
					linksIterator.remove();
					linkDescriptorsIterator.remove();
					break;
				}
			}
		}
		deleteViews(existingLinks.iterator());
		return createConnections(linkDescriptors, domain2NotationMap);
	}

	/**
	 * @generated
	 */
	private Collection<Wc2014LinkDescriptor> collectAllLinks(View view,
			Domain2Notation domain2NotationMap) {
		if (!WorldCupEditPart.MODEL_ID.equals(Wc2014VisualIDRegistry
				.getModelID(view))) {
			return Collections.emptyList();
		}
		LinkedList<Wc2014LinkDescriptor> result = new LinkedList<Wc2014LinkDescriptor>();
		switch (Wc2014VisualIDRegistry.getVisualID(view)) {
		case WorldCupEditPart.VISUAL_ID: {
			if (!domain2NotationMap.containsKey(view.getElement())) {
				result.addAll(Wc2014DiagramUpdater
						.getWorldCup_1000ContainedLinks(view));
			}
			domain2NotationMap.putView(view.getElement(), view);
			break;
		}
		case EliminationMatchEditPart.VISUAL_ID: {
			if (!domain2NotationMap.containsKey(view.getElement())) {
				result.addAll(Wc2014DiagramUpdater
						.getEliminationMatch_2001ContainedLinks(view));
			}
			domain2NotationMap.putView(view.getElement(), view);
			break;
		}
		case TeamEditPart.VISUAL_ID: {
			if (!domain2NotationMap.containsKey(view.getElement())) {
				result.addAll(Wc2014DiagramUpdater
						.getTeam_2002ContainedLinks(view));
			}
			domain2NotationMap.putView(view.getElement(), view);
			break;
		}
		case GroupEditPart.VISUAL_ID: {
			if (!domain2NotationMap.containsKey(view.getElement())) {
				result.addAll(Wc2014DiagramUpdater
						.getGroup_2003ContainedLinks(view));
			}
			domain2NotationMap.putView(view.getElement(), view);
			break;
		}
		case GroupMatchEditPart.VISUAL_ID: {
			if (!domain2NotationMap.containsKey(view.getElement())) {
				result.addAll(Wc2014DiagramUpdater
						.getGroupMatch_2004ContainedLinks(view));
			}
			domain2NotationMap.putView(view.getElement(), view);
			break;
		}
		}
		for (Iterator children = view.getChildren().iterator(); children
				.hasNext();) {
			result.addAll(collectAllLinks((View) children.next(),
					domain2NotationMap));
		}
		for (Iterator edges = view.getSourceEdges().iterator(); edges.hasNext();) {
			result.addAll(collectAllLinks((View) edges.next(),
					domain2NotationMap));
		}
		return result;
	}

	/**
	 * @generated
	 */
	private Collection<IAdaptable> createConnections(
			Collection<Wc2014LinkDescriptor> linkDescriptors,
			Domain2Notation domain2NotationMap) {
		LinkedList<IAdaptable> adapters = new LinkedList<IAdaptable>();
		for (Wc2014LinkDescriptor nextLinkDescriptor : linkDescriptors) {
			EditPart sourceEditPart = getSourceEditPart(nextLinkDescriptor,
					domain2NotationMap);
			EditPart targetEditPart = getTargetEditPart(nextLinkDescriptor,
					domain2NotationMap);
			if (sourceEditPart == null || targetEditPart == null) {
				continue;
			}
			CreateConnectionViewRequest.ConnectionViewDescriptor descriptor = new CreateConnectionViewRequest.ConnectionViewDescriptor(
					nextLinkDescriptor.getSemanticAdapter(),
					Wc2014VisualIDRegistry.getType(nextLinkDescriptor
							.getVisualID()), ViewUtil.APPEND, false,
					((IGraphicalEditPart) getHost())
							.getDiagramPreferencesHint());
			CreateConnectionViewRequest ccr = new CreateConnectionViewRequest(
					descriptor);
			ccr.setType(RequestConstants.REQ_CONNECTION_START);
			ccr.setSourceEditPart(sourceEditPart);
			sourceEditPart.getCommand(ccr);
			ccr.setTargetEditPart(targetEditPart);
			ccr.setType(RequestConstants.REQ_CONNECTION_END);
			Command cmd = targetEditPart.getCommand(ccr);
			if (cmd != null && cmd.canExecute()) {
				executeCommand(cmd);
				IAdaptable viewAdapter = (IAdaptable) ccr.getNewObject();
				if (viewAdapter != null) {
					adapters.add(viewAdapter);
				}
			}
		}
		return adapters;
	}

	/**
	 * @generated
	 */
	private EditPart getEditPart(EObject domainModelElement,
			Domain2Notation domain2NotationMap) {
		View view = (View) domain2NotationMap.get(domainModelElement);
		if (view != null) {
			return (EditPart) getHost().getViewer().getEditPartRegistry()
					.get(view);
		}
		return null;
	}

	/**
	 * @generated
	 */
	private Diagram getDiagram() {
		return ((View) getHost().getModel()).getDiagram();
	}

	/**
	 * @generated
	 */
	private EditPart getSourceEditPart(UpdaterLinkDescriptor descriptor,
			Domain2Notation domain2NotationMap) {
		return getEditPart(descriptor.getSource(), domain2NotationMap);
	}

	/**
	 * @generated
	 */
	private EditPart getTargetEditPart(UpdaterLinkDescriptor descriptor,
			Domain2Notation domain2NotationMap) {
		return getEditPart(descriptor.getDestination(), domain2NotationMap);
	}

	/**
	 * @generated
	 */
	protected final EditPart getHintedEditPart(EObject domainModelElement,
			Domain2Notation domain2NotationMap, int hintVisualId) {
		View view = (View) domain2NotationMap.getHinted(domainModelElement,
				Wc2014VisualIDRegistry.getType(hintVisualId));
		if (view != null) {
			return (EditPart) getHost().getViewer().getEditPartRegistry()
					.get(view);
		}
		return null;
	}

	/**
	 * @generated
	 */
	@SuppressWarnings("serial")
	protected static class Domain2Notation extends HashMap<EObject, View> {
		/**
		 * @generated
		 */
		public boolean containsDomainElement(EObject domainElement) {
			return this.containsKey(domainElement);
		}

		/**
		 * @generated
		 */
		public View getHinted(EObject domainEObject, String hint) {
			return this.get(domainEObject);
		}

		/**
		 * @generated
		 */
		public void putView(EObject domainElement, View view) {
			if (!containsKey(view.getElement())) {
				this.put(domainElement, view);
			}
		}

	}
}


text:
function [y,dx,k, r] = wrapPcg(L,Lden,At,dense,d, DAt,K, rb,rv,cgpars, y0)
% [y,r,k, DAy] = normeqPcg(L,Lden,At,dense,d, DAt,K, b, cgpars, y0,rhs)
%
% WRAPPCG  Solve y from AP(d)A' * y = b
% using PCG-method and Cholesky L as conditioner.
% If L is sufficiently accurate, then only 1 CG-step is needed.
% In general, proceeds until ||DAy - DA'(AD^2A')^{-1}b||
% has converged (to zero). k = #(CG-iterations).
%
% **********  INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi, loopPcg

% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA

% --------------------------------------------------
% INITIALIZE:
% --------------------------------------------------
restol = y0 * cgpars.restol;
dx = [sqrt(d.l).*rv(1:K.l); asmDxq(d,rv,K); psdscale(d,rv,K,1)];
r = Amul(At,dense,dx);
if ~isempty(rb)
    r = r+rb;
end
% --------------------------------------------------
% Pre - Conditioning/ Direct Solving:
% Solve L*THETA*L'*p = r, set ssqrNew = r'*inv(L*THETA*L')*r.
% --------------------------------------------------
p = fwdpr1(Lden,sparfwslv(L, r));
y = p ./ L.d;
ssqrNew = p'*y;
p = sparbwslv(L, bwdpr1(Lden,y));
% --------------------------------------------------
% SCALING OPERATION AND MATRIX*VECTOR.
% Let dx = D*A'*p
% Set alpha = ssqrNew / ||dx||^2
% --------------------------------------------------
x = vecsym(Amul(At,dense,p,1), K);
dx = [sqrt(d.l).*x(1:K.l); asmDxq(d,x,K); psdscale(d,x,K)];
ssqrdx = norm(dx)^2;
if ssqrdx <= 0.0
    y = zeros(length(r),1);
    k = 0;
    dx = rv;
    return
end
% --------------------------------------------------
% Take 1st step:  y *= alpha, alpha:=ssqrNew / ssqrdx,
% dx = rv - alpha * dx.
% --------------------------------------------------
k = 1;
alpha = ssqrNew / ssqrdx;
y = alpha * p;
dx = rv - alpha * dx;
% --------------------------------------------------
% Compute 1st residual r := b + A*D*dx.   (MATRIX*VECTOR).
% --------------------------------------------------
x = [sqrt(d.l).*dx(1:K.l); asmDxq(d,dx,K); psdscale(d,dx,K,1)];
r = Amul(At,dense,x);
if ~isempty(rb)
    r = r + rb;
end
normr = norm(r,inf);
if normr < restol
    return                % No CG nor refinement needed.
end
STOP = 0;
trial = 0;
k = 1;
% --------------------------------------------------
% Conjugate Gradient until convergence
% --------------------------------------------------
while ~STOP
    [dy,dk, x] = loopPcg(L,Lden,At,dense,d, DAt,K, r,p,ssqrNew,...
        cgpars, restol);
    if isempty(dy)
        return
    else
        % ------------------------------------------------------------
        % Add step from PCG-method. If P(d) is highly ill-conditioned, then
        % "x=DA*dy" as returned from PCG is inaccurate, and the residual
        % based on x can differ from the internal PCG residual. Therefore,
        % we recompute r based on x, and refine if needed & allowed.
        % ------------------------------------------------------------
        k = k + dk;
        y = y + dy;
        dx = dx - x;
        x = [sqrt(d.l).*dx(1:K.l); asmDxq(d,dx,K); psdscale(d,dx,K,1)];
        r = Amul(At,dense,x);
        if ~isempty(rb)
            r = r+rb;
        end
        normr = norm(r,inf);
        if normr < restol
            return
        elseif trial >= cgpars.refine
            return
        else
            p = [];
            trial = trial + 1;              % Refine
        end
    end
end


text:
// Copyright 2004-2005 Omni Development, Inc.  All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// http://www.omnigroup.com/DeveloperResources/OmniSourceLicense.html.
//
// $Id$

#import <OmniFoundation/OFXMLMaker.h>

/* XMLCFXMLTreeSink is a concrete subclass of XMLSink which writes its nodes into a CFXMLTree. */
@interface OFXMLCFXMLTreeSink : OFXMLSink
{
    CFXMLTreeRef topNode, currentEltTree;
#ifdef DEBUG
    OFXMLMaker *currentElt;
#endif
}

- initWithCFXMLTree:(CFXMLTreeRef)toplevel;

- (void)learnAncestralNamespaces;

- (CFXMLTreeRef)topNode;
- (void)addCFXMLNode:(CFXMLNodeRef)newNode;

- (NSData *)xmlData;

@end


text: import 'antd/lib/tree-select/style/css';


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

<meta http-equiv="content-type" content="text/html; charset=US-ASCII">
<title>Mines</title>
<link rel="previous" href="solo.html">
<link rel="ToC" href="index.html">
<link rel="up" href="index.html">
<link rel="index" href="docindex.html">
<link rel="next" href="samegame.html">

Previous | Contents | Index | Next

Chapter 12: Mines

You have a grid of covered squares, some of which contain mines, but you don't know which. Your job is to uncover every square which does not contain a mine. If you uncover a square containing a mine, you lose. If you uncover a square which does not contain a mine, you are told how many mines are contained within the eight surrounding squares.

This game needs no introduction; popularised by Windows, it is perhaps the single best known desktop puzzle game in existence.

This version of it has an unusual property. By default, it will generate its mine positions in such a way as to ensure that you never need to guess where a mine is: you will always be able to deduce it somehow. So you will never, as can happen in other versions, get to the last four squares and discover that there are two mines left but you have no way of knowing for sure where they are.

12.1 Mines controls

This game is played with the mouse.

If you left-click in a covered square, it will be uncovered.

If you right-click in a covered square, it will place a flag which indicates that the square is believed to be a mine. Left-clicking in a marked square will not uncover it, for safety. You can right-click again to remove a mark placed in error.

If you left-click in an uncovered square, it will ‘clear around’ the square. This means: if the square has exactly as many flags surrounding it as it should have mines, then all the covered squares next to it which are not flagged will be uncovered. So once you think you know the location of all the mines around a square, you can use this function as a shortcut to avoid having to click on each of the remaining squares one by one.

If you uncover a square which has no mines in the surrounding eight squares, then it is obviously safe to uncover those squares in turn, and so on if any of them also has no surrounding mines. This will be done for you automatically; so sometimes when you uncover a square, a whole new area will open up to be explored.

You can also use the cursor keys to move around the minefield. Pressing the return key in a covered square uncovers it, and in an uncovered square will clear around it (so it acts as the left button), pressing the space bar in a covered square will place a flag (similarly, it acts as the right button).

All the actions described in section 2.2 are also available.

Even Undo is available, although you might consider it cheating to use it. If you step on a mine, the program will only reveal the mine in question (unlike most other implementations, which reveal all of them). You can then Undo your fatal move and continue playing if you like. The program will track the number of times you died (and Undo will not reduce that counter), so when you get to the end of the game you know whether or not you did it without making any errors.

(If you really want to know the full layout of the grid, which other implementations will show you after you die, you can always use the Solve menu option.)

12.2 Mines parameters

The options available from the ‘Custom...’ option on the ‘Type’ menu are:

Width, Height

Size of grid in squares.

Mines

Number of mines in the grid. You can enter this as an absolute mine count, or alternatively you can put a % sign on the end in which case the game will arrange for that proportion of the squares in the grid to be mines.

Beware of setting the mine count too high. At very high densities, the program may spend forever searching for a solvable grid.

Ensure solubility

When this option is enabled (as it is by default), Mines will ensure that the entire grid can be fully deduced starting from the initial open space. If you prefer the riskier grids generated by other implementations, you can switch off this option.

<address>
[Puzzles S60 version 1.5.r9411]</address>


text:
from __future__ import division

import os
import time
import struct
import shutil
import tempfile

from io import BytesIO

from mapproxy.cache.compact import CompactCacheV1, CompactCacheV2
from mapproxy.cache.tile import Tile
from mapproxy.image import ImageSource
from mapproxy.image.opts import ImageOptions
from mapproxy.script.defrag import defrag_compact_cache
from mapproxy.test.unit.test_cache_tile import TileCacheTestBase

from nose.tools import eq_

class TestCompactCacheV1(TileCacheTestBase):

    always_loads_metadata = True

    def setup(self):
        TileCacheTestBase.setup(self)
        self.cache = CompactCacheV1(
            cache_dir=self.cache_dir,
        )

    def test_bundle_files(self):
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundlx'))
        self.cache.store_tile(self.create_tile(coord=(0, 0, 0)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundlx'))

        assert not os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundlx'))
        self.cache.store_tile(self.create_tile(coord=(127, 127, 12)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundlx'))

        assert not os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0100C0080.bundle'))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0100C0080.bundlx'))
        self.cache.store_tile(self.create_tile(coord=(128, 256, 12)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0100C0080.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0100C0080.bundlx'))

    def test_bundle_files_not_created_on_is_cached(self):
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundlx'))
        self.cache.is_cached(Tile(coord=(0, 0, 0)))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundlx'))

    def test_missing_tiles(self):
        self.cache.store_tile(self.create_tile(coord=(130, 200, 8)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L08', 'R0080C0080.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L08', 'R0080C0080.bundlx'))

        # test that all other tiles in this bundle are missing
        assert self.cache.is_cached(Tile((130, 200, 8)))
        for x in range(128, 255):
            for y in range(128, 255):
                if x == 130 and y == 200:
                    continue
                assert not self.cache.is_cached(Tile((x, y, 8))), (x, y)
                assert not self.cache.load_tile(Tile((x, y, 8))), (x, y)

    def test_remove_level_tiles_before(self):
        self.cache.store_tile(self.create_tile(coord=(0, 0, 12)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundlx'))

        # not removed with timestamp
        self.cache.remove_level_tiles_before(12, time.time())
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundlx'))

        # removed with timestamp=0 (remove_all:true in seed.yaml)
        self.cache.remove_level_tiles_before(12, 0)
        assert not os.path.exists(os.path.join(self.cache_dir, 'L12'))

    def test_bundle_header(self):
        t = Tile((5000, 1000, 12), ImageSource(BytesIO(b'a' * 4000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundle'))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundlx'))

        def assert_header(tile_bytes_written, max_tile_bytes):
            with open(os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundle'), 'r+b') as f:
                header = struct.unpack('<lllllllllllllll', f.read(60))
                eq_(header[11], 896)
                eq_(header[12], 1023)
                eq_(header[13], 4992)
                eq_(header[14], 5119)
                eq_(header[6], 60 + 128*128*4 + sum(tile_bytes_written))
                eq_(header[2], max_tile_bytes)
                eq_(header[4], len(tile_bytes_written)*4)

        assert_header([4000 + 4], 4000)

        t = Tile((5000, 1001, 12), ImageSource(BytesIO(b'a' * 6000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert_header([4000 + 4, 6000 + 4], 6000)

        t = Tile((4992, 999, 12), ImageSource(BytesIO(b'a' * 1000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert_header([4000 + 4, 6000 + 4, 1000 + 4], 6000)

        t = Tile((5000, 1001, 12), ImageSource(BytesIO(b'a' * 3000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert_header([4000 + 4, 6000 + 4 + 3000 + 4, 1000 + 4], 6000) # still contains bytes from overwritten tile

class TestCompactCacheV2(TileCacheTestBase):

    always_loads_metadata = True

    def setup(self):
        TileCacheTestBase.setup(self)
        self.cache = CompactCacheV2(
            cache_dir=self.cache_dir,
        )

    def test_bundle_files(self):
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))
        self.cache.store_tile(self.create_tile(coord=(0, 0, 0)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))

        assert not os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))
        self.cache.store_tile(self.create_tile(coord=(127, 127, 12)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))

        assert not os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0100C0080.bundle'))
        self.cache.store_tile(self.create_tile(coord=(128, 256, 12)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0100C0080.bundle'))

    def test_bundle_files_not_created_on_is_cached(self):
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))
        self.cache.is_cached(Tile(coord=(0, 0, 0)))
        assert not os.path.exists(os.path.join(self.cache_dir, 'L00', 'R0000C0000.bundle'))

    def test_missing_tiles(self):
        self.cache.store_tile(self.create_tile(coord=(130, 200, 8)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L08', 'R0080C0080.bundle'))

        # test that all other tiles in this bundle are missing
        assert self.cache.is_cached(Tile((130, 200, 8)))
        for x in range(128, 255):
            for y in range(128, 255):
                if x == 130 and y == 200:
                    continue
                assert not self.cache.is_cached(Tile((x, y, 8))), (x, y)
                assert not self.cache.load_tile(Tile((x, y, 8))), (x, y)

    def test_remove_level_tiles_before(self):
        self.cache.store_tile(self.create_tile(coord=(0, 0, 12)))
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))

        # not removed with timestamp
        self.cache.remove_level_tiles_before(12, time.time())
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0000C0000.bundle'))

        # removed with timestamp=0 (remove_all:true in seed.yaml)
        self.cache.remove_level_tiles_before(12, 0)
        assert not os.path.exists(os.path.join(self.cache_dir, 'L12'))

    def test_bundle_header(self):
        t = Tile((5000, 1000, 12), ImageSource(BytesIO(b'a' * 4000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert os.path.exists(os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundle'))

        def assert_header(tile_bytes_written, max_tile_bytes):
            with open(os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundle'), 'r+b') as f:
                header = struct.unpack('<4I3Q6I', f.read(64))
                eq_(header[0], 3) # version
                eq_(header[1], 128*128)
                eq_(header[2], max_tile_bytes)
                eq_(header[5], 64 + 128*128*8 + sum(tile_bytes_written))

        assert_header([4000 + 4], 4000)

        t = Tile((5000, 1001, 12), ImageSource(BytesIO(b'a' * 6000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert_header([4000 + 4, 6000 + 4], 6000)

        t = Tile((4992, 999, 12), ImageSource(BytesIO(b'a' * 1000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert_header([4000 + 4, 6000 + 4, 1000 + 4], 6000)

        t = Tile((5000, 1001, 12), ImageSource(BytesIO(b'a' * 3000), image_opts=ImageOptions(format='image/png')))
        self.cache.store_tile(t)
        assert_header([4000 + 4, 6000 + 4 + 3000 + 4, 1000 + 4], 6000) # still contains bytes from overwritten tile

class mockProgressLog(object):
    def __init__(self):
        self.logs = []

    def log(self, fname, fragmentation, fragmentation_bytes, num, total, defrag):
        self.logs.append({
            'fname': fname,
            'fragmentation': fragmentation,
            'fragmentation_bytes': fragmentation_bytes,
            'num': num,
            'total': total,
            'defrag': defrag,
        })
        self.logs.sort(key=lambda x: (x['fname'], 'num'))

class DefragmentationTestBase(object):
    def setup(self):
        self.cache_dir = tempfile.mkdtemp()

    def teardown(self):
        if os.path.exists(self.cache_dir):
            shutil.rmtree(self.cache_dir)

    def test_defragmentation_min_bytes(self):
        cache = self.cache_class(self.cache_dir)

        for _ in range(2):
            t = Tile((5000, 1000, 12),
                ImageSource(BytesIO(b'a' * 60*1024), image_opts=ImageOptions(format='image/png')))
            cache.store_tile(t)

        logger = mockProgressLog()
        fname = os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundle')
        before = os.path.getsize(fname)
        defrag_compact_cache(cache, log_progress=logger)
        assert len(logger.logs) == 1
        eq_(logger.logs[0]['defrag'], False)
        after = os.path.getsize(fname)
        assert before == after

        logger = mockProgressLog()
        before = os.path.getsize(fname)
        defrag_compact_cache(cache, min_bytes=50000, log_progress=logger)
        assert len(logger.logs) == 1
        eq_(logger.logs[0]['defrag'], True)
        after = os.path.getsize(fname)
        assert after < before

    def test_defragmentation_min_percent(self):
        cache = self.cache_class(self.cache_dir)

        t = Tile((10000, 2000, 13),
                        ImageSource(
                            BytesIO(b'a' * 120 * 1024),
                            image_opts=ImageOptions(format='image/png')))
        cache.store_tile(t)

        for x in range(100):
            for _ in range(2 if x < 10 else 1):
                t = Tile((5000+x, 1000, 12),
                        ImageSource(
                            BytesIO(b'a' * 120 * 1024),
                            image_opts=ImageOptions(format='image/png')))
                cache.store_tile(t)

        logger = mockProgressLog()
        fname = os.path.join(self.cache_dir, 'L12', 'R0380C1380.bundle')
        before = os.path.getsize(fname)
        defrag_compact_cache(cache, log_progress=logger)
        assert len(logger.logs) == 2
        eq_(logger.logs[0]['defrag'], False)
        eq_(logger.logs[1]['defrag'], False)
        after = os.path.getsize(fname)
        assert before == after

        logger = mockProgressLog()
        before = os.path.getsize(fname)
        defrag_compact_cache(cache, min_percent=0.08, log_progress=logger)
        assert len(logger.logs) == 2
        eq_(logger.logs[0]['defrag'], True)
        eq_(logger.logs[1]['defrag'], False)
        after = os.path.getsize(fname)
        assert after < before

class TestDefragmentationV1(DefragmentationTestBase):
    cache_class = CompactCacheV1

class TestDefragmentationV2(DefragmentationTestBase):
    cache_class = CompactCacheV2


text:
require "rexml/document"
include REXML

if ARGV.length < 1 then
	$stderr.puts "Needs a filename."
	exit 1
end

filename = ARGV.shift
doc = Document.new(File.open(filename))

$touched = false

# Fixing varnames having a sibling element without spacing.
# This is to fix an initial `xmlformat` issue where `term`
# would mangle as spaces.
#
#   <varlistentry>
#    <term><varname>types.separatedString</varname><replaceable>sep</replaceable> <----
#    </term>
#    ...
#
# Generates: types.separatedStringsep
#                               ^^^^
#
# <varlistentry xml:id='fun-makeWrapper'>
#  <term>
#   <function>makeWrapper</function><replaceable>executable</replaceable><replaceable>wrapperfile</replaceable><replaceable>args</replaceable>  <----
#  </term>
#
# Generates: makeWrapperexecutablewrapperfileargs
#                     ^^^^      ^^^^    ^^  ^^
#
#    <term>
#     <option>--option</option><replaceable>name</replaceable><replaceable>value</replaceable> <-----
#    </term>
#
# Generates: --optionnamevalue
#                   ^^  ^^
doc.elements.each("//varlistentry/term") do |term|
	["varname", "function", "option", "replaceable"].each do |prev_name|
		term.elements.each(prev_name) do |el|
			if el.next_element and
					el.next_element.name == "replaceable" and
					el.next_sibling_node.class == Element
				then
				$touched = true
				term.insert_after(el, Text.new(" "))
			end
		end
	end
end

#  <cmdsynopsis>
#   <command>nixos-option</command>
#   <arg>
#    <option>-I</option><replaceable>path</replaceable>        <------
#   </arg>
#
# Generates: -Ipath
#             ^^
doc.elements.each("//cmdsynopsis/arg") do |term|
	["option", "replaceable"].each do |prev_name|
		term.elements.each(prev_name) do |el|
			if el.next_element and
				el.next_element.name == "replaceable" and
				el.next_sibling_node.class == Element
			then
				$touched = true
				term.insert_after(el, Text.new(" "))
			end
		end
	end
end

#  <cmdsynopsis>
#   <arg>
#    <group choice='req'>
#    <arg choice='plain'>
#     <option>--profile-name</option>
#    </arg>
#
#    <arg choice='plain'>
#     <option>-p</option>
#    </arg>
#     </group><replaceable>name</replaceable>   <----
#   </arg>
#
# Generates: [{--profile-name | -p }name]
#                                   ^^^^
doc.elements.each("//cmdsynopsis/arg") do |term|
	["group"].each do |prev_name|
		term.elements.each(prev_name) do |el|
			if el.next_element and
				el.next_element.name == "replaceable" and
				el.next_sibling_node.class == Element
			then
				$touched = true
				term.insert_after(el, Text.new(" "))
			end
		end
	end
end

if $touched then
	doc.context[:attribute_quote] = :quote
	doc.write(output: File.open(filename, "w"))
end


text:
require 'spec_helper'

require 'flapjack/gateways/pagerduty'

describe Flapjack::Gateways::Pagerduty, :logger => true do

  let(:config) { {'queue'    => 'pagerduty_notifications'} }

  let(:time)   { Time.new }

  let(:redis) {  double('redis') }

  it "prompts the blocking redis connection to quit" do
    shutdown_redis = double('shutdown_redis')
    expect(shutdown_redis).to receive(:rpush).with(config['queue'], %q{{"notification_type":"shutdown"}})
    expect(EM::Hiredis).to receive(:connect).and_return(shutdown_redis)

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)
    fp.stop
  end

  it "doesn't look for acknowledgements if this search is already running" do
    expect(redis).to receive(:get).with('sem_pagerduty_acks_running').and_return('true')
    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    expect(fp).not_to receive(:find_pagerduty_acknowledgements)
    fp.find_pagerduty_acknowledgements_if_safe
  end

  it "looks for acknowledgements if the search is not already running" do
    expect(redis).to receive(:get).with('sem_pagerduty_acks_running').and_return(nil)
    expect(redis).to receive(:set).with('sem_pagerduty_acks_running', 'true')
    expect(redis).to receive(:expire).with('sem_pagerduty_acks_running', 300)

    expect(redis).to receive(:del).with('sem_pagerduty_acks_running')

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    expect(fp).to receive(:find_pagerduty_acknowledgements)
    fp.find_pagerduty_acknowledgements_if_safe
  end

  # Testing the private PagerDuty methods separately, it's simpler. May be
  # an argument for splitting some of them to another module, accessed by this
  # class, in which case it makes more sense for the methods to be public.

  # NB: needs to run in synchrony block to catch the evented HTTP requests
  it "looks for acknowledgements via the PagerDuty API" do
    check = 'PING'
    expect(Time).to receive(:now).and_return(time)
    since = (time.utc - (60*60*24*7)).iso8601 # the last week
    unt   = (time.utc + (60*60*24)).iso8601   # 1 day in the future

    response = {"incidents" =>
      [{"incident_number" => 12,
        "status" => "acknowledged",
        "last_status_change_by" => {"id"=>"ABCDEFG", "name"=>"John Smith",
                                    "email"=>"johns@example.com",
                                    "html_url"=>"http://flpjck.pagerduty.com/users/ABCDEFG"}
       }
      ],
      "limit"=>100,
      "offset"=>0,
      "total"=>1}

    stub_request(:get, "https://flpjck.pagerduty.com/api/v1/incidents?" +
      "fields=incident_number,status,last_status_change_by&incident_key=#{check}&" +
      "since=#{since}&status=acknowledged&until=#{unt}").
       with(:headers => {'Authorization'=>['flapjack', 'password123']}).
       to_return(:status => 200, :body => response.to_json, :headers => {})

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    EM.synchrony do
      result = fp.send(:pagerduty_acknowledged?, 'subdomain' => 'flpjck', 'username' => 'flapjack',
        'password' => 'password123', 'check' => check)

      expect(result).to be_a(Hash)
      expect(result).to have_key(:pg_acknowledged_by)
      expect(result[:pg_acknowledged_by]).to be_a(Hash)
      expect(result[:pg_acknowledged_by]).to have_key('id')
      expect(result[:pg_acknowledged_by]['id']).to eq('ABCDEFG')
      EM.stop
    end

  end

  it "creates acknowledgements when pagerduty acknowledgements are found" do
    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    contact = double('contact')
    expect(contact).to receive(:pagerduty_credentials).and_return({
      'service_key' => '12345678',
      'subdomain"'  => 'flpjck',
      'username'    => 'flapjack',
      'password'    => 'password123'
    })

    entity_check = double('entity_check')
    expect(entity_check).to receive(:check).exactly(2).times.and_return('PING')
    expect(entity_check).to receive(:contacts).and_return([contact])
    expect(entity_check).to receive(:entity_name).exactly(2).times.and_return('foo-app-01.bar.net')
    expect(Flapjack::Data::Event).to receive(:create_acknowledgement).with('foo-app-01.bar.net', 'PING',
      :summary => 'Acknowledged on PagerDuty', :duration => 14400, :redis => redis)

    expect(Flapjack::Data::EntityCheck).to receive(:unacknowledged_failing).exactly(2).times.and_return([entity_check])

    expect(fp).to receive(:pagerduty_acknowledged?).and_return({})

    fp.send(:find_pagerduty_acknowledgements)
  end

  it "runs a blocking loop listening for notifications" do
    timer = double('timer')
    expect(timer).to receive(:cancel)
    expect(EM::Synchrony).to receive(:add_periodic_timer).with(10).and_return(timer)

    expect(redis).to receive(:del).with('sem_pagerduty_acks_running')

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    blpop_count = 0

    expect(redis).to receive(:blpop).twice {
      blpop_count += 1
      if blpop_count == 1
        ["pagerduty_notifications", '{"notification_type":"problem","event_id":"main-example.com:ping",' +
          '"state":"critical","summary":"!!!","state_duration":120,"duration":30}']
      else
        fp.instance_variable_set('@should_quit', true)
        ["pagerduty_notifications", %q{{"notification_type":"shutdown"}}]
      end
    }

    expect(fp).to receive(:test_pagerduty_connection).and_return(true)
    expect(fp).to receive(:send_pagerduty_event)

    fp.start

    expect(@logger.errors).to be_empty
  end

  it "tests the pagerduty connection" do
    evt = { "service_key"  => "11111111111111111111111111111111",
            "incident_key" => "Flapjack is running a NOOP",
            "event_type"   => "nop",
            "description"  => "I love APIs with noops."}
    body = evt.to_json

    stub_request(:post, "https://events.pagerduty.com/generic/2010-04-15/create_event.json").
      with(:body => body).to_return(:status => 200, :body => '{"status":"success"}', :headers => {})

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    EM.synchrony do
      ret = fp.send(:test_pagerduty_connection)
      expect(ret).to be true
      EM.stop
    end
  end

  it "sends an event to pagerduty" do
    evt = {"service_key"  => "abcdefg",
           "incident_key" => "www.example.com:ssh",
           "event_type"   => "nop",
           "description"  => "Not really sent anyway",
           "details"      => { 'HOSTNAME' => 'www.example.com', 'SERVICE' => 'ssh' }
          }
    body = evt.to_json

    stub_request(:post, "https://events.pagerduty.com/generic/2010-04-15/create_event.json").
      with(:body => body).to_return(:status => 200, :body => "", :headers => {})

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)

    EM.synchrony do
      ret = fp.send(:send_pagerduty_event, evt)
      expect(ret).not_to be_nil
      expect(ret).to eq([200, nil])
      EM.stop
    end
  end

  it "does not look for acknowledgements if all required credentials are not present" do
    creds = {'subdomain' => 'example',
             'username'  => 'sausage',
             'check'     => 'PING'}

    expect(Flapjack::RedisPool).to receive(:new).and_return(redis)
    fp = Flapjack::Gateways::Pagerduty.new(:config => config, :logger => @logger)
    EM.synchrony do
      result = fp.send(:pagerduty_acknowledged?, creds)

      expect(result).to be(nil)
      EM.stop
    end

  end

end


text:
"""Recipe supervisor"""

import os
import pwd
from mako.template import Template

import logging

import zc.recipe.egg
from zc.buildout.buildout import bool_option
import zc.recipe.deployment
from zc.recipe.deployment import Configuration
from zc.recipe.deployment import make_dir
import birdhousebuilder.recipe.conda

templ_config = Template(filename=os.path.join(os.path.dirname(__file__), "supervisord.conf"))
templ_program = Template(filename=os.path.join(os.path.dirname(__file__), "program.conf"))
templ_start_stop = Template(filename=os.path.join(os.path.dirname(__file__), "supervisord"))

class Recipe(object):
    """This recipe is used by zc.buildout.
    It installs supervisor as conda package and setups configuration."""

    def __init__(self, buildout, name, options):
        self.buildout, self.name, self.options = buildout, name, options
        b_options = buildout['buildout']

        self.name = options.get('name', name)
        self.options['name'] = self.name

        self.logger = logging.getLogger(self.name)

        # deployment layout
        def add_section(section_name, options):
            if section_name in buildout._raw:
                raise KeyError("already in buildout", section_name)
            buildout._raw[section_name] = options
            buildout[section_name]  # cause it to be added to the working parts

        self.deployment_name = self.name + "-supervisor-deployment"
        self.deployment = zc.recipe.deployment.Install(buildout, self.deployment_name, {
            'name': "supervisor",
            'prefix': self.options.get('prefix'),
            'user': self.options.get('user'),
            'etc-user': self.options.get('etc-user')})
        add_section(self.deployment_name, self.deployment.options)

        self.options['user'] = self.deployment.options['user']
        self.options['home'] = os.path.expanduser('~' + self.options['user'])
        self.options['etc-user'] = self.deployment.options['etc-user']
        self.options['etc-prefix'] = self.options['etc_prefix'] = self.deployment.options['etc-prefix']
        self.options['var-prefix'] = self.options['var_prefix'] = self.deployment.options['var-prefix']
        self.options['etc-directory'] = self.options['etc_directory'] = self.deployment.options['etc-directory']
        self.options['log-directory'] = self.options['log_directory'] = self.deployment.options['log-directory']
        self.options['run-directory'] = self.options['run_directory'] = self.deployment.options['run-directory']
        self.options['cache-directory'] = self.options['cache_directory'] = self.deployment.options['cache-directory']
        self.options['bin-directory'] = b_options['bin-directory']
        self.prefix = self.options['prefix']

        # conda environment path
        self.options['env'] = self.options.get('env', '')
        self.options['pkgs'] = self.options.get('pkgs', 'supervisor')
        self.options['channels'] = self.options.get('channels', 'defaults')

        self.conda = birdhousebuilder.recipe.conda.Recipe(self.buildout, self.name, {
            #'prefix': self.options.get('conda-prefix', ''),
            'env': self.options['env'],
            'pkgs': self.options['pkgs'],
            'channels': self.options['channels']})
        self.options['conda-prefix'] = self.options['conda_prefix'] = self.conda.options['prefix']

        bin_path = os.path.join(self.options['conda-prefix'], 'bin')
        lib_path = os.path.join(self.options['conda-prefix'], 'lib')

        # buildout options used for supervisord.conf

        self.options['host'] = b_options.get('supervisor-host', '127.0.0.1')
        self.options['port'] = b_options.get('supervisor-port', '9001')
        self.options['username'] = b_options.get('supervisor-username', '')
        self.options['password'] = b_options.get('supervisor-password', '')
        use_monitor = bool_option(b_options, 'supervisor-use-monitor', True)
        self.options['use-monitor'] = self.options['use_monitor'] = 'true' if use_monitor else 'false'
        self.options['loglevel'] = b_options.get('supervisor-loglevel', 'info')

        # options used for program config

        self.program = self.options.get('program', name)
        logfile = os.path.join(self.options['log-directory'], self.program + ".log")
        # set default options
        skip_user = bool_option(self.options, 'skip-user', False)
        self.options['skip-user'] = self.options['skip_user'] = 'true' if skip_user else 'false'
        # TODO: fix usage of directory ... currently searches for wpsapp.py
        self.options['directory'] = self.options.get('directory', bin_path)
        self.options['priority'] = self.options.get('priority', '999')
        self.options['autostart'] = self.options.get('autostart', 'true')
        self.options['autorestart'] = self.options.get('autorestart', 'false')
        self.options['stdout-logfile'] = self.options['stdout_logfile'] = self.options.get('stdout-logfile', logfile)
        self.options['stderr-logfile'] = self.options['stderr_logfile'] = self.options.get('stderr-logfile', logfile)
        self.options['startsecs'] = self.options.get('startsecs', '1')
        self.options['numprocs'] = self.options.get('numprocs', '1')
        self.options['stopwaitsecs'] = self.options.get('stopwaitsecs', '10')
        self.options['stopasgroup'] = self.options.get('stopasgroup', 'false')
        self.options['killasgroup'] = self.options.get('killasgroup', 'true')
        self.options['stopsignal'] = self.options.get('stopsignal', 'TERM')
        env_templ = \
            'USER={0},LOGNAME={0},HOME={1},PATH="/bin:/usr/bin:{2}",PYTHON_EGG_CACHE="{3}"'
        self.options['environment'] = self.options.get(
            'environment',
            env_templ.format(self.options['user'], self.options['home'],
                             bin_path, self.options['cache-directory']))

    def install(self, update=False):
        installed = []
        if not update:
            installed += list(self.deployment.install())
        installed += list(self.conda.install(update))
        installed += list(self.install_config())
        installed += list(self.install_program())
        installed += list(self.install_start_stop())
        installed += list(self.install_supervisord())
        installed += list(self.install_supervisorctl())
        return installed

    def install_config(self):
        """
        install supervisor main config file
        """
        text = templ_config.render(**self.options)
        config = Configuration(self.buildout, 'supervisord.conf', {
            'deployment': self.deployment_name,
            'text': text})
        return [config.install()]

    def install_program(self):
        """
        install supervisor program config file
        """
        text = templ_program.render(**self.options)
        config = Configuration(self.buildout, self.program + '.conf', {
            'deployment': self.deployment_name,
            'directory': os.path.join(self.options['etc-directory'], 'conf.d'),
            'text': text})
        return [config.install()]

    def install_start_stop(self):
        text = templ_start_stop.render(**self.options)
        config = Configuration(self.buildout, 'supervisord', {
            'deployment': self.deployment_name,
            'directory': os.path.join(self.options['etc-prefix'], 'init.d'),
            'text': text})
        configfile = config.install()
        os.chmod(configfile, 0o755)
        return [configfile]

    def install_supervisord(self):
        script = 'supervisord'
        source = os.path.join(self.options['etc-prefix'], 'init.d', script)
        target = os.path.join(self.options['bin-directory'], script)
        if not os.path.exists(target):
            os.symlink(source, target)
        return [target]

    def install_supervisorctl(self):
        conf_file = os.path.join(self.options['etc-directory'], 'supervisord.conf')
        init_stmt = 'import sys; sys.argv[1:1] = ["-c", "{0}"]'.format(conf_file)
        ctlscript = zc.recipe.egg.Egg(
            self.buildout,
            self.name, {
                'eggs': 'supervisor',
                'scripts': 'supervisorctl=supervisorctl',
                'initialization': init_stmt,
                'arguments': 'sys.argv[1:]',
            })
        return ctlscript.install()

    def update(self):
        return self.install(update=True)

def uninstall(name, options):
    pass


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Examining the mentoring of undergraduates engaged in science research: An empirical study of undergraduate-postgraduate-faculty triads</AwardTitle>
    <AwardEffectiveDate>06/14/2014</AwardEffectiveDate>
    <AwardExpirationDate>05/31/2017</AwardExpirationDate>
    <AwardAmount>365000</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      11090000
      <Directorate>
        <LongName>Direct For Education and Human Resources</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Research On Learning</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Gregg E. Solomon</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>PROJECT SUMMARY<br/>The PI proposes to conduct a 2-year empirical study that will: (1) identify the mentoring structures that are empirically observable in undergraduate research experiences at research universities, in terms of the strength and function of relationships within the undergraduate-postgraduate-faculty triad; (2) examine how different mentoring structures relate to the cognitive, behavioral, and affective outcomes undergraduates realize from participating in research; and (3) determine the extent to which women and underrepresented minority undergraduates experience different mentoring structures or realize outcomes differentially in comparison to majority students.</AbstractNarration>
    <MinAmdLetterDate>09/16/2014</MinAmdLetterDate>
    <MaxAmdLetterDate>09/16/2014</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1451999</AwardID>
    <Investigator>
      <FirstName>Erin</FirstName>
      <LastName>Dolan</LastName>
      <EmailAddress>eldolan@uga.edu</EmailAddress>
      <StartDate>09/16/2014</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>University of Texas at Austin</Name>
      <CityName>Austin</CityName>
      <ZipCode>787121532</ZipCode>
      <PhoneNumber>5124716424</PhoneNumber>
      <StreetAddress>101 E. 27th Street, Suite 5.300</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Texas</StateName>
      <StateCode>TX</StateCode>
    </Institution>
    <ProgramElement>
      7625
      <Text>REAL</Text>
    </ProgramElement>
  </Award>
</rootTag>


text:
import { NgModule, enableProdMode } from '@angular/core';

import { RouterModule } from '@angular/router';
import { rootRouterConfig } from './app.routes';
import { AppComponent } from './app.component';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';

import { CodePrev } from './fusioncharts/codepreview';
import { CodemirrorModule } from 'ng2-codemirror';

import { Ex1 } from './fusioncharts/ex1/ex1';
import { Ex2 } from './fusioncharts/ex2/ex2';
import { Ex3 } from './fusioncharts/ex3/ex3';
import { Ex4 } from './fusioncharts/ex4/ex4';
import { Ex5 } from './fusioncharts/ex5/ex5';
import { Ex5a } from './fusioncharts/ex5a/ex5a';
import { Ex6 } from './fusioncharts/ex6/ex6';
import { Ex7 } from './fusioncharts/ex7/ex7';
import { Ex8 } from './fusioncharts/ex8/ex8';
import { Ex9 } from './fusioncharts/ex9/ex9';
import { Ex10 } from './fusioncharts/ex10/ex10';
import { Ex11 } from './fusioncharts/ex11/ex11';
import { Ex12 } from './fusioncharts/ex12/ex12';
import { Ex13 } from './fusioncharts/ex13/ex13';
import { Ex14 } from './fusioncharts/ex14/ex14';
import { Ex15 } from './fusioncharts/ex15/ex15';
import { Ex16 } from './fusioncharts/ex16/ex16';
import { Ex17 } from './fusioncharts/ex17/ex17';
import { Ex18 } from './fusioncharts/ex18/ex18';
import { Ex19 } from './fusioncharts/ex19/ex19';
import { Ex20 } from './fusioncharts/ex20/ex20';
import { Ex21 } from './fusioncharts/ex21/ex21';
import { Ex22 } from './fusioncharts/ex22/ex22';
import { Ex23 } from './fusioncharts/ex23/ex23';
import { Ex24 } from './fusioncharts/ex24/ex24';
import { Ex25 } from './fusioncharts/ex25/ex25';
import { Ex26 } from './fusioncharts/ex26/ex26';
import { Ex27 } from './fusioncharts/ex27/ex27';
import { Ex28 } from './fusioncharts/ex28/ex28';
import { Ex29 } from './fusioncharts/ex29/ex29';
import { Ex30 } from './fusioncharts/ex30/ex30';
import { Ex31 } from './fusioncharts/ex31/ex31';
import { Ex32 } from './fusioncharts/ex32/ex32';
import { Ex33 } from './fusioncharts/ex33/ex33';
import { Ex34 } from './fusioncharts/ex34/ex34';
import { Ex35 } from './fusioncharts/ex35/ex35';
import { Ex36 } from './fusioncharts/ex36/ex36';

import { FusionTime } from './fusiontime/fusiontime';

import { SafeHtmlPipe } from './pipes/trustAsHtml';
import { TabbedCode } from './fusioncharts/tabbedComponent/tabbed.code.component';

import {
  Navigation,
  NavService,
  ObservingComponent,
  MyAppComponent
} from './observable/observable.component';

import { FusionChartsSample } from './fusioncharts/fusioncharts.component';
import {
  FusionChartsModule,
  FusionChartsStatic
} from '../angular-fusioncharts';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';

// Load FusionCharts
import * as FusionCharts from 'fusioncharts';

// Load fusion-time module
import * as TimeSeries from 'fusioncharts/fusioncharts.timeseries';

// Load charts module
import * as Charts from 'fusioncharts/fusioncharts.charts';
// import * as Charts from 'fusioncharts/fusioncharts.charts';
// Load PowerCharts module
import * as PowerCharts from 'fusioncharts/fusioncharts.powercharts';
// import * as PowerCharts from 'fusioncharts/fusioncharts.powercharts';
// Load Widgets module
import * as Widgets from 'fusioncharts/fusioncharts.widgets';
// import * as Widgets from 'fusioncharts/fusioncharts.widgets';
// Load Maps module
import * as Maps from 'fusioncharts/fusioncharts.maps';
// import * as Maps from 'fusioncharts/fusioncharts.maps';
// Load WorldMap module
import * as WorldMap from 'fusioncharts/maps/fusioncharts.world';
// import * as WorldMap from 'fusioncharts/maps/fusioncharts.world';
// Load Ocean theme
import * as Ocean from 'fusioncharts/themes/fusioncharts.theme.ocean';
import * as Fint from 'fusioncharts/themes/fusioncharts.theme.fint';
import * as Candy from 'fusioncharts/themes/fusioncharts.theme.candy';
import * as Gammel from 'fusioncharts/themes/fusioncharts.theme.gammel';
import * as Zune from 'fusioncharts/themes/fusioncharts.theme.zune';
import * as Fusion from 'fusioncharts/themes/fusioncharts.theme.fusion';
import * as Carbon from 'fusioncharts/themes/fusioncharts.theme.carbon';
// import * as Ocean from 'fusioncharts/themes/fusioncharts.theme.ocean';

// require('./themes/fusioncharts.theme.fusion.js');
// require('./themes/fusioncharts.theme.gammel.js');

FusionChartsModule.fcRoot(
  FusionCharts,
  Charts,
  TimeSeries,
  PowerCharts,
  Widgets,
  Maps,
  WorldMap,
  Ocean,
  Fint,
  Gammel,
  Zune,
  Fusion,
  Candy,
  Carbon
);

@NgModule({
  declarations: [
    Ex1,
    Ex2,
    Ex3,
    Ex4,
    Ex5,
    Ex5a,
    Ex6,
    Ex7,
    Ex8,
    Ex9,
    Ex10,
    Ex11,
    Ex12,
    Ex13,
    Ex14,
    Ex15,
    Ex16,
    Ex17,
    Ex18,
    Ex19,
    Ex20,
    Ex21,
    Ex22,
    Ex23,
    Ex24,
    Ex25,
    Ex26,
    Ex27,
    Ex28,
    Ex29,
    Ex30,
    Ex31,
    Ex32,
    Ex33,
    Ex34,
    Ex35,
    Ex36,
    SafeHtmlPipe,
    Navigation,
    ObservingComponent,
    MyAppComponent,
    CodePrev,
    AppComponent,
    FusionChartsSample,
    TabbedCode,
    FusionTime
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    FusionChartsModule,
    RouterModule.forRoot(rootRouterConfig, { useHash: true }),
    CodemirrorModule
  ],
  providers: [NavService],
  bootstrap: [AppComponent]
})
export class AppModule {}


text:
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Controllers;
using JsonApiDotNetCore.Services;
using Microsoft.Extensions.Logging;

namespace JsonApiDotNetCoreTests.IntegrationTests.NamingConventions;

public sealed class DivingBoardsController : JsonApiController<DivingBoard, int>
{
    public DivingBoardsController(IJsonApiOptions options, IResourceGraph resourceGraph, ILoggerFactory loggerFactory,
        IResourceService<DivingBoard, int> resourceService)
        : base(options, resourceGraph, loggerFactory, resourceService)
    {
    }
}


text:
Sequel.migration do
  up do
    alter_table :export_refund_nomenclature_description_periods do
      set_column_type :additional_code_type, String
    end

    alter_table :export_refund_nomenclature_descriptions do
      set_column_type :additional_code_type, String
    end

    alter_table :export_refund_nomenclature_indents do
      set_column_type :additional_code_type, String
    end

    alter_table :export_refund_nomenclatures do
      set_column_type :additional_code_type, String
    end

    alter_table :footnote_association_additional_codes do
      set_column_type :additional_code_type_id, String
    end

    alter_table :footnote_association_erns do
      set_column_type :additional_code_type, String
    end

    alter_table :measures do
      set_column_type :additional_code_type_id, String
    end
  end

  down do
    alter_table :export_refund_nomenclature_description_periods do
      set_column_type :additional_code_type, Integer
    end

    alter_table :export_refund_nomenclature_descriptions do
      set_column_type :additional_code_type, Integer
    end

    alter_table :export_refund_nomenclature_indents do
      set_column_type :additional_code_type, Integer
    end

    alter_table :export_refund_nomenclatures do
      set_column_type :additional_code_type, Integer
    end

    alter_table :footnote_association_additional_codes do
      set_column_type :additional_code_type_id, Integer
    end

    alter_table :footnote_association_erns do
      set_column_type :additional_code_type, Integer
    end

    alter_table :measures do
      set_column_type :additional_code_type, Integer
    end
  end
end


text:
module.exports = function(robot) {
  robot.brain.data.dialogue = {};
  return robot.hear(/.*/, function(res) {
    var ctx, p, payload, ref, room_id;
    p = parseFloat((ref = process.env.HUBOT_DOCOMO_DIALOGUE_P) != null ? ref : '0.3');
    if (!(Math.random() < p)) {
      return;
    }
    payload = {
      utt: res.match[0],
      nickname: res.message.user.name
    };
    room_id = res.message.user.reply_to || res.message.user.room;
    if (ctx = robot.brain.data.dialogue[room_id]) {
      payload.context = ctx.context;
      payload.mode = ctx.mode;
    }
    return res.http('https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue').header('Content-Type', 'application/json').query({
      APIKEY: process.env.HUBOT_DOCOMO_DIALOGUE_API_KEY
    }).post(JSON.stringify(payload))(function(err, _, body) {
      var data;
      if (err != null) {
        robot.logger.error(e);
        return res.send('docomo-dialogue: error');
      } else {
        data = JSON.parse(body);
        res.send(data.utt);
        return robot.brain.data.dialogue[room_id] = {
          context: data.context,
          mode: data.mode
        };
      }
    });
  });
};


text:
import json
import os
import subprocess

import lib.aur as aur
import lib.download as download
import packager.path
from manager.models import Package
from packager.path import DEST_DIR_NAME
from packager.settings_local import PACKAGER

class BuilderError(Exception):
    pass

class Builder:
    def __init__(self, package_id):
        self.package = Package.objects.get(id=package_id)
        self.version = ''

    @property
    def package_name(self):
        return self.package.name

    def build(self, date):
        # get package info from AUR
        info = aur.info(self.package_name, self.package.server)

        # create required path
        self.version = info.Version
        path = packager.path.Path(self.package_name, self.version, date.isoformat())
        build_dir = path.build_dir
        dest_dir = path.dest_dir

        # create working directories
        os.makedirs(build_dir, 0o700)
        os.makedirs(dest_dir, 0o700)

        # get tarball
        download.save_to_file(info.tar_url, path.tar_file, opener=aur.create_opener(self.package.server))

        # generate build script
        build_script = '''
#!/bin/bash

cd {build_dir}
tar xvf {package_name}
cd $(ls -d */ | grep -v "{dest_dir_name}")
export PKGDEST='{dest}'
export PACKAGER='{packager_name}'
makepkg -s --noconfirm
workdir=$(pwd)
cd ..
rm -rf ${{workdir}}
if [[ -e {package_name} ]]; then
    rm -f {package_name}
fi
'''
        with open(path.script_file, 'w') as f:
            f.write(build_script.format(build_dir=build_dir, package_name=self.package_name, dest=dest_dir,
                                        dest_dir_name=DEST_DIR_NAME, packager_name=PACKAGER))

        # execute build script
        completed = subprocess.run('cd {} && bash _build_script.sh'.format(build_dir), shell=True,
                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)

        # write log
        with open(path.log_file, 'w') as f:
            f.write(json.dumps(info, indent=4))
            f.write('\n')
            f.write(completed.stdout)


text: Basis for Pamphlet 4-based frontend websites


text:
package fr.adrienbrault.idea.symfony2plugin.ui;

import com.intellij.openapi.project.Project;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.table.TableView;
import fr.adrienbrault.idea.symfony2plugin.assistant.signature.MethodSignatureSetting;
import fr.adrienbrault.idea.symfony2plugin.assistant.signature.PhpTypeSignatureInterface;
import fr.adrienbrault.idea.symfony2plugin.assistant.signature.PhpTypeSignatureTypes;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class MethodSignatureTypeDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JComboBox comboProvider;
    private JTextField textCallTo;
    private JTextField textMethodName;
    private JTextField textIndex;
    private MethodSignatureSetting methodParameterSetting;
    private TableView<MethodSignatureSetting> tableView;

    private Project project;

    class ComboBoxRenderer extends ColoredListCellRenderer {
        @Override
        protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
            append((String) value);
        }
    }

    public MethodSignatureTypeDialog(Project project, TableView<MethodSignatureSetting> tableView) {
        this.tableView = tableView;
        this.project = project;

        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        this.textCallTo.getDocument().addDocumentListener(new ChangeDocumentListener());
        this.textMethodName.getDocument().addDocumentListener(new ChangeDocumentListener());
        this.textIndex.getDocument().addDocumentListener(new ChangeDocumentListener());

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        // allow only number values to indexes
        // simple?
        this.textIndex.addKeyListener(new KeyAdapter() {
            private String allowedRegex = "[^0-9]";

            @Override
            public void keyReleased(KeyEvent e) {
                String curText = ((JTextComponent) e.getSource()).getText();
                curText = curText.replaceAll(allowedRegex, "");

                ((JTextComponent) e.getSource()).setText(curText);
            }
        });

        this.attachComboBoxValues(project);
    }

    private void attachComboBoxValues(Project project) {
        for(PhpTypeSignatureInterface provider: PhpTypeSignatureTypes.DEFAULT_PROVIDER) {
            comboProvider.addItem(provider.getName());
        }
    }

    public MethodSignatureTypeDialog(Project project, TableView<MethodSignatureSetting> tableView, MethodSignatureSetting methodParameterSetting) {
        this(project, tableView);

        this.textCallTo.setText(methodParameterSetting.getCallTo());
        this.textMethodName.setText(methodParameterSetting.getMethodName());
        this.textIndex.setText(String.valueOf(methodParameterSetting.getIndexParameter()));
        this.methodParameterSetting = methodParameterSetting;

        if(methodParameterSetting.getReferenceProviderName() != null) {
            this.comboProvider.setSelectedItem(methodParameterSetting.getReferenceProviderName());
        }

    }

    private void onOK() {

        int index;
        try {
            index = Integer.parseInt(this.textIndex.getText());
        } catch (NumberFormatException e) {
            index = 0;
        }

        MethodSignatureSetting twigPath = new MethodSignatureSetting(this.textCallTo.getText(), this.textMethodName.getText(), index, (String) this.comboProvider.getSelectedItem());

        // re-add old item to not use public setter wor twigpaths
        // update ?
        if(this.methodParameterSetting != null) {
            int row = this.tableView.getSelectedRows()[0];
            this.tableView.getListTableModel().removeRow(row);
            this.tableView.getListTableModel().insertRow(row, twigPath);
            this.tableView.setRowSelectionInterval(row, row);
        } else {
            int row = this.tableView.getRowCount();
            this.tableView.getListTableModel().addRow(twigPath);
            this.tableView.setRowSelectionInterval(row, row);
        }

        dispose();
    }

    private void setOkState() {
        this.buttonOK.setEnabled(
            this.textCallTo.getText().length() > 0 &&
            this.textMethodName.getText().length() > 0 &&
            this.textIndex.getText().length() > 0
        );
    }

    private class ChangeDocumentListener implements DocumentListener {
        @Override
        public void insertUpdate(DocumentEvent e) {
            setOkState();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            setOkState();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            setOkState();
        }
    }

    private void onCancel() {
        dispose();
    }

}


text:
angular.module('allcount').controller('IntegrationsController', ['$scope', '$http', function ($scope, $http) {
    $scope.loadAvailableIntegrations = function () {
        return $http.get('/api/integrations').then(function (resp) {
            $scope.integrations = resp.data;
            $scope.appIdToIntegration = _.chain(resp.data).map(function (i) { return [i.appId, i] }).object().value();
        });
    };

    $scope.loadAvailableIntegrations();
}]);


text:
List building application for Android and iOS that utilizes the Ionic Framework.
This is mainly for learning purposes as I work through Ionic's setup.

This will be a simple list-tracking application, that will allow users to create lists for multiple uses, such as:
* Grocery Shopping
* Packing
* Hit Lists
* Reasons They Love Spanish
* Etc.


text:
<!DOCTYPE html>

  <title>Andres Carrion Quiz</title>
  <meta charset="utf-8">
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
  <meta content="" name="Andres' Website">
  <meta content="width=device-width, initial-scale=1" name="viewport">
  <link href="css/materialize.css" rel="stylesheet" type="text/css">

        About

        Projects

        Contact

QUIZ

Question??

            <input name="groupz" type="radio" id="test1" value="0"/>
            Answer1

            <input name="groupz" type="radio" id="test2" value="1"/>
            Answer 2

            <input name="groupz" type="radio" id="test3" value="2"/>
            Answer 3

            <input name="groupz" type="radio" id="test4" value="3"/>
            Answer 4

<button class="btn waves-effect waves-light" type="button" name="action">Next
    </button>

Footer Content

You can use rows and columns here
          to organize your footer content.

        © 2017 Andres Carrion


text:
#ifndef UNDO_H
#define UNDO_H

typedef struct _UndoStack UndoStack;
typedef struct _Change Change;

#include "diagram.h"
#include "objchange.h"

typedef void (*UndoApplyFunc)(Change *change, Diagram *dia);
typedef void (*UndoRevertFunc)(Change *change, Diagram *dia);
typedef void (*UndoFreeFunc)(Change *change);

struct _Change {
  /* If apply == transaction_point_pointer then this is a transaction
     point */
  UndoApplyFunc  apply;
  UndoRevertFunc revert;
  UndoFreeFunc   free; /* Remove extra data. Then this object is freed */
  Change *prev, *next;
};

struct _UndoStack {
  Diagram *dia;
  Change *last_change; /* Points to the object on the top of stack. */
  Change *current_change; /* Points to the last object currently applied */
  int depth;
};

extern UndoStack *new_undo_stack(Diagram *dia);
extern void undo_destroy(UndoStack *stack);
extern void undo_push_change(UndoStack *stack, Change *change);
extern void undo_set_transactionpoint(UndoStack *stack);
extern void undo_revert_to_last_tp(UndoStack *stack);
extern void undo_apply_to_next_tp(UndoStack *stack);
extern void undo_clear(UndoStack *stack);

/* Specific undo functions: */

extern Change *undo_move_objects(Diagram *dia, Point *orig_pos,
				 Point *dest_pos, GList *obj_list);
extern Change *undo_move_handle(Diagram *dia,
				Handle *handle, Object *obj,
				Point orig_pos, Point dest_pos);
extern Change *undo_connect(Diagram *dia, Object *obj, Handle *handle,
			    ConnectionPoint *connectionpoint);
extern Change *undo_unconnect(Diagram *dia, Object *obj, Handle *handle);
extern Change *undo_delete_objects(Diagram *dia, GList *obj_list); /* Reads current obj list */
extern Change *undo_insert_objects(Diagram *dia, GList *obj_list,
				   int applied);
extern Change *undo_reorder_objects(Diagram *dia, GList *changed_list,
				    GList *orig_list); /* Reads current obj list */
extern Change *undo_object_change(Diagram *dia, Object *obj,
				  ObjectChange *obj_change);
extern Change *undo_group_objects(Diagram *dia, GList *obj_list,
				  Object *group, GList *orig_list);
extern Change *undo_ungroup_objects(Diagram *dia, GList *obj_list,
				    Object *group, int group_index);

#endif /* UNDO_H */


text:
/**
 * Menu
 */
(function()
{
  var global = this,
      nspace = global.Menu,
      Util = global.Util,
      Exception = global.Exception;

  /**
   *
   * @type Menu
   */
  var Menu = nspace.Menu = function(selector)
  {
    this.resource = $(selector);
    this.items = new Array();
  };

  Menu.prototype =
  {
    resource: null,
    items: null,

    /**
     *
     * @param {Object} menuItem
     * @returns {undefined}
     */
    addItem: function(menuItem)
    {
      this.resource.append(menuItem.build());
      this.items.push(menuItem);
    },

    /**
     *
     * @returns {jQuery|String}
     */
    build: function()
    {
      throw new Exception.Unsupported('Method not implemented');
    }
  };

})();


text:
__attribute__((objc_root_class))
@interface NSValue
+ (NSValue *)valueWithBytes:(const void *)bytes objCType:(const char *)type;
@end

void doStuff(struct boxable b) {
  id v = @(b);
}


text:
package com.groupon.mapreduce.mongo;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import static org.junit.Assert.assertEquals;

public class WritableBSONObjectTest {
    @Test
    public void testSerialization() throws Exception {
        WritableBSONObject x = new WritableBSONObject();
        x.put("key1", 4);
        x.put("key2", 9);

        WritableBSONObject x2 = new WritableBSONObject();

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        DataOutputStream stream = new DataOutputStream(byteStream);

        x.write(stream);
        byte[] output = byteStream.toByteArray();

        x2.readFields(new DataInputStream(new ByteArrayInputStream(output)));

        assertEquals(x, x2);
    }
}


text:
/* $Id: template.h 2 2009-10-12 09:51:22Z mamonski $ */
/*
 *  FedStage DRMAA utilities library
 *  Copyright (C) 2006-2008  FedStage Systems
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __DRMAA_UTILS__TEMPLATE_H
#define __DRMAA_UTILS__TEMPLATE_H

#ifdef HAVE_CONFIG_H
#	include <config.h>
#endif

#include <drmaa_utils/common.h>

typedef const fsd_attribute_t *
fsd_template_by_name_method( const fsd_template_t *self, const char *name );

typedef const fsd_attribute_t *
fsd_template_by_code_method( const fsd_template_t *self, int code );

fsd_template_t *
fsd_template_new(
		fsd_template_by_name_method *by_name_method,
		fsd_template_by_code_method *by_code_method,
		unsigned n_attributes
		);

struct fsd_template_s {
	const char* (*
	get_attr)( const fsd_template_t *self, const char *name );

	void (*
	set_attr)( fsd_template_t *self, const char *name, const char *value );

	const char* const* (*
	get_v_attr)( const fsd_template_t *self, const char *name );

	void (*
	set_v_attr)( fsd_template_t *self, const char *name, const char **value );

	const fsd_attribute_t* (*
	by_name)( const fsd_template_t *self, const char *name );

	const fsd_attribute_t* (*
	by_code)( const fsd_template_t *self, int code );

	void (*
	destroy)( fsd_template_t *self );

	void **attributes;
	unsigned n_attributes;
};

struct fsd_attribute_s {
	const char *name;
	int code;
	bool is_vector;
};

#endif /* __DRMAA_UTILS__TEMPLATE_H */


text:
OneTouchDriver
==============

Driver for Ingenious Technology Co Ltd "OneTouch" transparent touchscreen overlay

Copyright 2011, Joe Koberg <joe@osoft.us>

Data format is a 3 or 5 byte report sent at 19200 8N1, either

    0xFF 0xFE 0xFE    - Sent upon touch release and sometimes alone on taps/short touches.
    0xFF X0 X1 Y0 Y1  - Where X and Y are little-endian 2-byte integers. Position is the high bits so divide by 64.

There is significant position noise at the start and end of each raw touch event.
We wait for DISCARD_START reports to come in after a touch, then start putting them into a buffer.
When AVG_COUNT + DISCARD_END have accumulated, we output the average of the earliest AVG_COUNT samples.
When the touch is released the fifo is cleared. Thus the final DISCARD_END samples are ignored.
The panel reports at 200Hz.

There is also an attempt at auto-calibration/scaling. The edges of the panel are intermittent
and it's best to use a smaller active screen area.


text:
import { Component } from '@angular/core';
import { Constance } from '../../../utils/constance';

@Component({
  selector: 'reports',
  template: `<page-header [pageTitle]='pageTitle'  [pageIcon]='pageIcon' [description]="description"></page-header>`,
})
export class ReportsComponent {
    public pageTitle = 'Reports';
    public pageIcon = Constance.REPORTS_ICON;
    public description = 'A report is a survey of the Courses of Actions that your organization implements, ' +
            'and to what level (High, Medium, or Low).  Unfetter|Discover will use the survey to help you ' +
            'understand your gaps, how important they are and which should be addressed.  You may create ' +
            'multiple reports to see how new or different Courses of Actions implemented may change your security posture.';
}


text:
'use strict';

var executable = require('executable');
var spawn = require('child_process').spawn;

/**
 * Check if a executable is working correctly by checking it's exit code
 *
 * @param {String} name
 * @param {String|Array} cmd
 * @param {Function} cb
 * @api public
 */

module.exports = function (name, cmd, cb) {
    var bin;

    if (typeof cmd === 'function') {
        cb = cmd;
        cmd = ['--help'];
    }

    cmd = cmd || ['--help'];
    cmd = Array.isArray(cmd) ? cmd : [cmd];

    executable(name, function (err, works) {
        if (err) {
            return cb(err);
        }

        if (works) {
            bin = spawn(name, cmd);

            bin.on('error', function (err) {
                return cb(err);
            });

            bin.on('exit', function (code) {
                return cb(null, code === 0 ? true : false);
            });
        } else {
            return cb(null, false);
        }
    });
};


text:
<?php $this->load->view('header_admin'); ?>

			    Create User

			    <form class="form-horizontal" role="form" method="post" action="<?php echo base_url();?>survey/save_user">

						Data Collector's Name:

							<input type="text" class="form-control" name="name" placeholder="Name" required>

						User Type:

							<input type="radio" name="admin" value=1>Admin
							<input type="radio" name="admin" value=0>Data Clerk

						Username:

							<input type="text" class="form-control" name="username" placeholder="Username" required>

						Password:

							<input type="text" class="form-control" name="password" placeholder="Password" required>

							<input id="submit" name="submit" type="submit" value="Submit" class="btn btn-primary" style="color:white; background-color:#1BA39C;">

				</form>


text:
angular.module('medekApp.services').service('BookService', [
'$http',
'$rootScope',
function($http, $rootScope) {
    this.booklist = function(from, limit, orderBy, orderDir) {
        return $http.get('services/books?from='+from+'&limit='+limit+'&orderBy='+orderBy+'&orderDir='+orderDir);
    };

    this.userBooklist = function(from, limit, orderBy, orderDir, userId) {
        return $http.get('services/books/user?from='+from+'&limit='+limit+'&orderBy='+orderBy+'&orderDir='+orderDir+'&userId='+userId);
    };

    this.book = function(id) {
        return $http.get('services/books/'+id);
    };

    this.saveBook = function(book) {
        return $http.post('services/books', book);
    };

    this.artists = function() {
    	return $http.get('services/artists/books');
    };

    this.addBookToCollection = function(book) {
        return $http.post('services/books/addtocollec', book);
    };
} ]);


text:
import { useEffect } from "react";

import { useRefCache } from "../useRefCache";
import { delegateEvent } from "./utils";

/**
 * @remarks \@since 5.0.0
 */
export interface ScrollListenerHookOptions extends AddEventListenerOptions {
  /**
   * The event handler that will be fired when the page scrolls or if any child
   * element scrolls when the {@link capture} option is `true`.
   */
  onScroll: EventListener;

  /** @defaultValue `true` */
  enabled?: boolean;
}

/**
 *
 * @remarks \@since 5.0.0 Moved the `AddEventListenerOptions` to no longer be
 * part of an `options` object.
 */
export function useScrollListener({
  once,
  passive = true,
  signal,
  capture,
  enabled = true,
  onScroll,
}: ScrollListenerHookOptions): void {
  const scrollHandlerRef = useRefCache(onScroll);
  useEffect(() => {
    if (!enabled) {
      return;
    }

    const eventHandler = delegateEvent("scroll", window, true, {
      once,
      passive,
      signal,
      capture,
    });
    const scrollHandler = scrollHandlerRef.current;
    eventHandler.add(scrollHandler);

    return () => {
      eventHandler.remove(scrollHandler);
    };
  }, [capture, enabled, once, passive, scrollHandlerRef, signal]);
}