text:
#ifndef CYBER_BLOCKER_BLOCKER_H_
#define CYBER_BLOCKER_BLOCKER_H_

#include <cstddef>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

namespace apollo {
namespace cyber {
namespace blocker {

class BlockerBase {
 public:
  virtual ~BlockerBase() = default;

  virtual void Reset() = 0;
  virtual void ClearObserved() = 0;
  virtual void ClearPublished() = 0;
  virtual void Observe() = 0;
  virtual bool IsObservedEmpty() const = 0;
  virtual bool IsPublishedEmpty() const = 0;
  virtual bool Unsubscribe(const std::string& callback_id) = 0;

  virtual size_t capacity() const = 0;
  virtual void set_capacity(size_t capacity) = 0;
  virtual const std::string& channel_name() const = 0;
};

struct BlockerAttr {
  BlockerAttr() : capacity(10), channel_name("") {}
  explicit BlockerAttr(const std::string& channel)
      : capacity(10), channel_name(channel) {}
  BlockerAttr(size_t cap, const std::string& channel)
      : capacity(cap), channel_name(channel) {}
  BlockerAttr(const BlockerAttr& attr)
      : capacity(attr.capacity), channel_name(attr.channel_name) {}

  size_t capacity;
  std::string channel_name;
};

template <typename T>
class Blocker : public BlockerBase {
  friend class BlockerManager;

 public:
  using MessageType = T;
  using MessagePtr = std::shared_ptr<T>;
  using MessageQueue = std::list<MessagePtr>;
  using Callback = std::function<void(const MessagePtr&)>;
  using CallbackMap = std::unordered_map<std::string, Callback>;
  using Iterator = typename std::list<std::shared_ptr<T>>::const_iterator;

  explicit Blocker(const BlockerAttr& attr);
  virtual ~Blocker();

  void Publish(const MessageType& msg);
  void Publish(const MessagePtr& msg);

  void ClearObserved() override;
  void ClearPublished() override;
  void Observe() override;
  bool IsObservedEmpty() const override;
  bool IsPublishedEmpty() const override;

  bool Subscribe(const std::string& callback_id, const Callback& callback);
  bool Unsubscribe(const std::string& callback_id) override;

  const MessageType& GetLatestObserved() const;
  const MessagePtr GetLatestObservedPtr() const;
  const MessagePtr GetOldestObservedPtr() const;
  const MessagePtr GetLatestPublishedPtr() const;

  Iterator ObservedBegin() const;
  Iterator ObservedEnd() const;

  size_t capacity() const override;
  void set_capacity(size_t capacity) override;
  const std::string& channel_name() const override;

 private:
  void Reset() override;
  void Enqueue(const MessagePtr& msg);
  void Notify(const MessagePtr& msg);

  BlockerAttr attr_;
  MessageQueue observed_msg_queue_;
  MessageQueue published_msg_queue_;
  mutable std::mutex msg_mutex_;

  CallbackMap published_callbacks_;
  mutable std::mutex cb_mutex_;

  MessageType dummy_msg_;
};

template <typename T>
Blocker<T>::Blocker(const BlockerAttr& attr) : attr_(attr), dummy_msg_() {}

template <typename T>
Blocker<T>::~Blocker() {
  published_msg_queue_.clear();
  observed_msg_queue_.clear();
  published_callbacks_.clear();
}

template <typename T>
void Blocker<T>::Publish(const MessageType& msg) {
  Publish(std::make_shared<MessageType>(msg));
}

template <typename T>
void Blocker<T>::Publish(const MessagePtr& msg) {
  Enqueue(msg);
  Notify(msg);
}

template <typename T>
void Blocker<T>::Reset() {
  {
    std::lock_guard<std::mutex> lock(msg_mutex_);
    observed_msg_queue_.clear();
    published_msg_queue_.clear();
  }
  {
    std::lock_guard<std::mutex> lock(cb_mutex_);
    published_callbacks_.clear();
  }
}

template <typename T>
void Blocker<T>::ClearObserved() {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  observed_msg_queue_.clear();
}

template <typename T>
void Blocker<T>::ClearPublished() {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  published_msg_queue_.clear();
}

template <typename T>
void Blocker<T>::Observe() {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  observed_msg_queue_ = published_msg_queue_;
}

template <typename T>
bool Blocker<T>::IsObservedEmpty() const {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  return observed_msg_queue_.empty();
}

template <typename T>
bool Blocker<T>::IsPublishedEmpty() const {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  return published_msg_queue_.empty();
}

template <typename T>
bool Blocker<T>::Subscribe(const std::string& callback_id,
                           const Callback& callback) {
  std::lock_guard<std::mutex> lock(cb_mutex_);
  if (published_callbacks_.find(callback_id) != published_callbacks_.end()) {
    return false;
  }
  published_callbacks_[callback_id] = callback;
  return true;
}

template <typename T>
bool Blocker<T>::Unsubscribe(const std::string& callback_id) {
  std::lock_guard<std::mutex> lock(cb_mutex_);
  return published_callbacks_.erase(callback_id) != 0;
}

template <typename T>
auto Blocker<T>::GetLatestObserved() const -> const MessageType& {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  if (observed_msg_queue_.empty()) {
    return dummy_msg_;
  }
  return *observed_msg_queue_.front();
}

template <typename T>
auto Blocker<T>::GetLatestObservedPtr() const -> const MessagePtr {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  if (observed_msg_queue_.empty()) {
    return nullptr;
  }
  return observed_msg_queue_.front();
}

template <typename T>
auto Blocker<T>::GetOldestObservedPtr() const -> const MessagePtr {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  if (observed_msg_queue_.empty()) {
    return nullptr;
  }
  return observed_msg_queue_.back();
}

template <typename T>
auto Blocker<T>::GetLatestPublishedPtr() const -> const MessagePtr {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  if (published_msg_queue_.empty()) {
    return nullptr;
  }
  return published_msg_queue_.front();
}

template <typename T>
auto Blocker<T>::ObservedBegin() const -> Iterator {
  return observed_msg_queue_.begin();
}

template <typename T>
auto Blocker<T>::ObservedEnd() const -> Iterator {
  return observed_msg_queue_.end();
}

template <typename T>
size_t Blocker<T>::capacity() const {
  return attr_.capacity;
}

template <typename T>
void Blocker<T>::set_capacity(size_t capacity) {
  std::lock_guard<std::mutex> lock(msg_mutex_);
  attr_.capacity = capacity;
  while (published_msg_queue_.size() > capacity) {
    published_msg_queue_.pop_back();
  }
}

template <typename T>
const std::string& Blocker<T>::channel_name() const {
  return attr_.channel_name;
}

template <typename T>
void Blocker<T>::Enqueue(const MessagePtr& msg) {
  if (attr_.capacity == 0) {
    return;
  }
  std::lock_guard<std::mutex> lock(msg_mutex_);
  published_msg_queue_.push_front(msg);
  while (published_msg_queue_.size() > attr_.capacity) {
    published_msg_queue_.pop_back();
  }
}

template <typename T>
void Blocker<T>::Notify(const MessagePtr& msg) {
  std::lock_guard<std::mutex> lock(cb_mutex_);
  for (const auto& item : published_callbacks_) {
    item.second(msg);
  }
}

}  // namespace blocker
}  // namespace cyber
}  // namespace apollo

#endif  // CYBER_BLOCKER_BLOCKER_H_


text:
require 'helper'

describe NFL::Client::Teams::Injuries do
  describe '#team_injuries' do
    before(:each) do
      @client = NFL::Client.new
    end

    describe 'with team parameter' do
      it 'gets the raw HTML' do
        path = 'www.nfl.com/teams/injuries?team=ATL'

        stub_request(:get, path) \
          .to_return(:status => 200, :body => fixture(path).read)

        options = {'team' => 'ATL'}

        @client.send(:team_injuries, options).should eq fixture(path).read
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
==================================================
``simpy.resources`` --- Shared resource primitives
==================================================

.. automodule:: simpy.resources

Resources --- ``simpy.resources.resource``
==========================================

.. automodule:: simpy.resources.resource

.. autoclass:: Resource
   :members:

.. autoclass:: PriorityResource
   :members:

.. autoclass:: PreemptiveResource
   :members:

.. autoclass:: Preempted
   :members:

.. autoclass:: Request
   :members:

.. autoclass:: PriorityRequest
   :members:

.. autoclass:: Release
   :members:

.. autoclass:: SortedQueue
   :members:

Containers --- ``simpy.resources.container``
============================================

.. automodule:: simpy.resources.container

.. autoclass:: Container
   :members:

.. autoclass:: ContainerPut
   :members:

.. autoclass:: ContainerGet
   :members:

Stores --- ``simpy.resources.store``
====================================

.. automodule:: simpy.resources.store

.. autoclass:: Store
   :members:

.. autoclass:: FilterStore
   :members:

.. autoclass:: StorePut
   :members:

.. autoclass:: StoreGet
   :members:

.. autoclass:: FilterStoreGet
   :members:

Base classes --- ``simpy.resources.base``
=========================================

.. automodule:: simpy.resources.base

.. autoclass:: BaseResource
   :members:

.. autoclass:: Put
   :members:

.. autoclass:: Get
   :members:


text:
<?php

/**
 * sfValidatorSblam checks if form is not a spam using SBLAM service
 *
 * @package    antispam
 * @subpackage validator
 * @author     Arkadiusz Tułodziecki
 */
class sfValidatorSblam extends sfValidatorSchema {
	const HAM = -2;
	const PROBABLY_HAM = -1;
	const SERVER_ERROR = 0;
	const PROBABLY_SPAM = 1;
	const SPAM = 2;

	/**
	 * Constructor.
	 *
	 * @param array  $fieldnames  An array of fields to check
	 * @param string $apikey      Generated in http://sblam.com/key.html SBLAM apikey
	 * @param mixed  $not_valid   Level (int) or levels (array) when Validator throw not Valid error
	 * @param array  $hosts       Optionaly array of alternative SBLAM server hosts
	 * @param array  $options     An array of options
	 * @param array  $messages    An array of error messages
	 *
	 * @see sfValidatorBase
	 */
	public function __construct($fieldnames = NULL, $apikey = NULL, $not_valid = self::SPAM, $hosts = NULL, $options = array(), $messages = array()) {
		$this->addOption('fieldnames', $fieldnames);
		$this->addOption('apikey', $apikey);
		$this->addOption('not_valid', $not_valid);
		$this->addOption('hosts', $hosts);

		parent::__construct(null, $options, $messages);
	}

	/**
	 * @see sfValidatorBase
	 */
	protected function doClean($values) {
		if (null === $values) {
			$values = array();
		}

		if (!is_array($values)) {
			throw new InvalidArgumentException('You must pass an array parameter to the clean() method');
		}

		$sblamclient = new SblamClient($this->getOption('hosts'));
		$test = $sblamclient->testPost($this->getOption('fieldnames'), $this->getOption('apikey'));

		$valid = true;
		$not_valid = $this->getOption('not_valid');
		if (is_array($not_valid) and in_array($test, $not_valid)) {
			$valid = false;
		}
		if (is_int($not_valid) and $test >= $not_valid) {
			$valid = false;
		}

		if (!$valid) {
			throw new sfValidatorError($this, 'invalid', array(
				'sblam_id'  => $sblamclient->getLastId(),
				'error'     => $sblamclient->getLastError(),
				'raporturl' => $sblamclient->getReportUrl(),
			));
		}

		return $values;
	}
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import WixComponent from '../BaseComponents/WixComponent';
import Checkbox from '../Checkbox';
import RadioButton from '../RadioGroup/RadioButton/RadioButton';
import Image from './Image';
import Text from '../Text';
import styles from './Selector.scss';
import ExtraText from './ExtraText';
import ExtraIcon from './ExtraIcon';
import ProgressBar from './ProgressBar';

const toggleStyle = {
  display: 'inline-block'
};

const imageStyle = {
  marginLeft: '2px',
  marginRight: '10px',
  display: 'flex'
};

class Selector extends WixComponent {
  static propTypes = {
    id: PropTypes.number.isRequired,
    title: PropTypes.string.isRequired,
    isSelected: PropTypes.bool,
    image: PropTypes.string,
    subTitle: PropTypes.string,
    onToggle: PropTypes.func,
    toggleType: PropTypes.oneOf(['checkbox', 'radio'])
  };

  static defaultProps = {
    isSelected: false,
    toggleType: 'checkbox'
  };

  state = {
    checked: false
  };

  toggle = id => {
    this.props.onToggle && this.props.onToggle(id);
  };

  render() {
    const {
      imageSize,
      imageSrc,
      title,
      subTitle,
      isSelected,
      id,
      children,
      toggleType
    } = this.props;
    let toggle;
    if (toggleType === 'checkbox') {
      toggle = <Checkbox dataHook="toggle" style={toggleStyle} checked={isSelected} onChange={() => this.toggle(id)}/>;
    } else {
      toggle = <RadioButton dataHook="toggle" style={toggleStyle} checked={isSelected} onChange={() => this.toggle(id)}/>;
    }
    return (

 this.toggle(id)}
        >

          {toggle}
          {imageSrc ?
<Image imageSrc={imageSrc} imageSize={imageSize}/>
 : ''}

<Text appearance="T1">{title}</Text>

            {subTitle ?
<Text appearance="T3">{subTitle}</Text>
 : ''}

          {children}

    );
  }
}

Selector.ExtraText = ExtraText;
Selector.ExtraIcon = ExtraIcon;
Selector.ProgressBar = ProgressBar;

export default Selector;


text:
/**
* Requests Module
*
* This module is responsible for providing full CRUD on the requests table.
*
* @module controllers/requests
* @requires ../lib/db
* @requires ../lib/tools
*/

import db from '../lib/db';
import tools from '../lib/tools';

// module exports
exports.create = create;
exports.read   = read;
exports.update = update;
exports.delete = del;

// GET /requests/:id?
// gets all requests.  Expects a query string with
// ?status = { 'open', 'closed' }
function read(req, res, next) {
  var sql,
      hasId = (req.params.id !== undefined);

  sql =
    'SELECT r.id, r.projectid, r.date, r.beneficiary, r.explanation, r.signatureA, ' +
      'r.signatureB, r.review, r.status, rd.item, rd.budgetcode, rd.quantity, ' +
      'rd.unit, rd.unitprice, rd.totalprice ' +
    'FROM request r JOIN requestdetail rd ON ' +
      'r.id = rd.requestid';

  if (hasId) {
    sql += ' WHERE r.id = ?;';
  }

  db.async.all(sql, [req.params.id])
  .then(function (rows) {

    if (hasId && !rows.length) {
      return res.status(404).send();
    }

    if (hasId) {
      var request = tools.collect(rows, 'details', [
        'totalprice', 'unitprice', 'unit', 'quantity', 'budgetcode', 'item'
      ]);

      return res.status(200).json(request);
    }

    // in this case, an empty result is a positive result
    // not an error.  No rows is a result.
    res.status(200).json(rows);
  })
  .catch(next)
  .done();
}

// POST /requests
// Expects a request body and request detail lines
function create(req, res, next) {
  var requestStmt,
      detailStmt,
      data = req.body,
      userid = req.session.user.id;

  requestStmt = db.prepare('INSERT INTO request (projectid, date, beneficiary, explanation, status, createdby) VALUES (?, ?, ?, ?, ?, ?);');
  detailStmt = db.prepare('INSERT INTO requestdetail (requestid, item, budgetcode, quantity, unit, unitprice, totalprice) VALUES (?, ?, ?, ?, ?, ?, ?);');

  // execute requests one at a time (synchronously)
  db.serialize(function () {

    requestStmt.run(data.projectid, data.date, data.beneficiary, data.explanation, 'open', userid, function (err) {
      if (err) { return next(err); }

      var requestid = this.lastID;

      req.body.details.forEach(function (row) {
        detailStmt.run(requestid, row.item, row.budgetcode, row.quantity, row.unit, row.unitprice, row.unitprice * row.quanity, function (err) {
          if (err) { return next(err); }
        });
      });

      // finalize detail statement
      detailStmt.finalize(function (err) {
        if (err) { return next(err); }

        // everything is good, send back the id for receipt rendering
        res.status(200).json({ id : requestid });
      });
    });
  });

  // finalize request statement
  requestStmt.finalize();
}

// PUT /requests/:id
// TODO
function update(req, res, next) {
  next();
}

// DELETE /requests/:id
function del(req, res, next) {

  db.async.run('DELETE FROM request WHERE id = ?', [req.params.id])
  .then(function () {
    res.status(200).send();
  })
  .catch(next)
  .done();
}


text:
package de.terministic.serein.core.selection.individual;

import java.util.Random;

import de.terministic.serein.api.EvolutionEnvironment;
import de.terministic.serein.api.FitnessComparator;
import de.terministic.serein.api.IndividualSelection;
import de.terministic.serein.api.Population;
import de.terministic.serein.core.Populations;

public abstract class AbstractIndividualSelection<P> implements IndividualSelection<P> {
	private int numberToSelect;
	protected Random random = new Random();
	protected FitnessComparator<P> comparator;
	protected EvolutionEnvironment<P> referenceEA;

	@Override
	public void setEnvironment(EvolutionEnvironment<P> environment) {
		if (environment != null){
			// use reference to initialize random number generator
			this.random = new Random(environment.getRandom().nextLong());
			this.referenceEA = environment;
		}

	}

	@Override
	public Population<P> selectIndividuals(Population<P> population) {
		Population<P> selected = Populations.emptyPopulation();

		for (int i = 0; i < getNumberToSelect(population); i++) {
			selected.add(this.selectIndividual(population));
		}

		return selected;
	}

	protected int getNumberToSelect(Population<P> population) {
		int count = numberToSelect;

		if (numberToSelect == 0) {
			count = population.size();
		}

		return count;
	}

	/**
	 *
	 * @return the number of parents selected during each selection process. A
	 *         zero has a special meaning of automated
	 */
	public int getNumberToSelect() {
		return numberToSelect;
	}

	/**
	 * Sets the number of parents select during each call to selectParents. If
	 * an value is set which is not an positive integer the number of selected
	 * parents is chosen automatically. In this case the number is equal to the
	 * size of the population from which the parents are chosen.
	 *
	 * @param parentCount
	 *            the number of parents to select
	 * @return true if the value was accepted otherwise an automatic value zero is
	 *         used
	 */
	public boolean setNumberToSelect(int parentCount) {
		boolean accepted;
		if (parentCount > 0) {
			this.numberToSelect = parentCount;
			accepted = true;
		} else {
			this.numberToSelect = 0;
			accepted = false;
		}
		return accepted;

	}

}


text:
require 'spec_helper'

describe WarriorsController, :type => :controller do

  before { Warrior.create }

  context 'GET /warriors' do
    it 'assings collection var' do
      get :index
      assigns(:warriors).should == Warrior.all
    end
  end

  context 'GET /warriors/new' do
    it 'fetches a new instance of warrior' do
      get :new
      assigns(:warrior).should be_new_record
    end

    it 'assigns member var' do
      get :new
      assigns(:warrior).should be_kind_of(Warrior)
    end
  end

  context 'POST /warriors' do
    it "shows warrior after creating" do
      post :create, warrior: {}
      response.should redirect_to(warrior_path(Warrior.last))
    end

    it "creates the warrior and assigns it to a member var" do
      post :create, warrior: {}
      assigns(:warrior).should be_a(Warrior)
      assigns(:warrior).should be_persisted
    end
  end

  context 'GET /warriors/:id' do
    it 'assigns the found warrior to member var' do
      Warrior.stub find: Warrior.first
      get :show, id: 1
      assigns(:warrior).should == Warrior.first
    end
  end

  context 'GET /warriors/:id/edit' do
    it 'assigns the found warrior to member var' do
      Warrior.stub find: Warrior.first
      get :edit, id: 1
      assigns(:warrior).should == Warrior.first
    end
  end

  context 'PUT /warriors/:id' do
    it 'assigns the found warrior to member var' do
      Warrior.stub find: Warrior.first
      put :update, id: 1
      assigns(:warrior).should == Warrior.first
    end

    it 'updates the member var' do
      pending 'must uncomment and refactor'
      #warrior = Warrior.last
      #Warrior.stub find: warrior
      #warrior.stub update_attributes: true
      #put :update, id: 1, warrior: {name: 'someothername'}
      #warrior.should_receive :update_attributes
    end

    it "shows warrior after updating" do
      Warrior.stub find: Warrior.last
      put :update, id: 1, warrior: {name: 'othername'}
      response.should redirect_to(warrior_path(Warrior.last))
    end
  end

  context 'DELETE /warriors/:id' do
    it 'assigns the found warrior to member var' do
      warrior = Warrior.create
      Warrior.stub find: warrior
      delete :destroy, id: 1
      assigns(:warrior).should == warrior
    end
  end

end


text:
<?php

class Ticket {
    const STATUS_OPEN = 'open';
    const STATUS_CLOSED = 'open';
    const SEVERITY_LOW = 'low';
    const SEVERITY_HIGH = 'high';
    protected $title;
    protected $severity;
    protected $status;
    protected $conn;

    public function __construct(\PDO $conn) {
        $this->conn = $conn;
    }

    public function setTitle($title) {
        $this->title = $title;
    }

    public function setSeverity($severity) {
        $this->severity = $severity;
    }

    public function setStatus($status) {
        $this->status = $status;
    }

    private function validate() {
        if (!empty($this->title)
            && !empty($this->status)
            && !empty($this->severity)
        ) {
            return true;
        }
        return false;
    }

    public function save() {
        if ($this->validate()) {
            $stmt = $this->conn->prepare('INSERT INTO
                ticket (title, severity, status)
                VALUES (:title, :severity, :status)'
            );
            $stmt->execute(array(
                ':title' => $this->title,
                ':severity' => $this->severity,
                ':status' => $this->status,
            ));

            return $this->conn->lastInsertId();
        }
        return 0;
    }

}

// Client
$conn = new PDO(
    'mysql:host=localhost;dbname=project;charset=utf8',
    'root', 'mysql'
);

$ticket = new Ticket($conn);
$ticket->setTitle('Checkout not working!');
$ticket->setStatus(Ticket::STATUS_OPEN);
$ticket->setSeverity(Ticket::SEVERITY_HIGH);
$ticket->save();


text:
package org.apereo.cas.web.support;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.AuthenticationResult;
import org.apereo.cas.authentication.AuthenticationResultBuilder;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.adaptive.geo.GeoLocationRequest;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.logout.LogoutRequest;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.ticket.ServiceTicket;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.profile.ProfileManager;
import org.pac4j.core.profile.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.CookieGenerator;
import org.springframework.webflow.context.ExternalContextHolder;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.core.collection.MutableAttributeMap;
import org.springframework.webflow.execution.FlowSession;
import org.springframework.webflow.execution.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.util.List;
import java.util.Optional;

/**
 * Common utilities for the web tier.
 *
 * @author Scott Battaglia
 * @since 3.1
 */
public final class WebUtils {

    /**
     * Request attribute that contains message key describing details of authorization failure.
     */
    public static final String CAS_ACCESS_DENIED_REASON = "CAS_ACCESS_DENIED_REASON";

    /**
     * Constant representing the request header for user agent.
     */
    public static final String USER_AGENT_HEADER = "user-agent";

    private static final Logger LOGGER = LoggerFactory.getLogger(WebUtils.class);

    private static final String UNKNOWN_USER = "audit:unknown";

    private static final String PUBLIC_WORKSTATION_ATTRIBUTE = "publicWorkstation";
    private static final String PARAMETER_AUTHENTICATION = "authentication";
    private static final String PARAMETER_AUTHENTICATION_RESULT_BUILDER = "authenticationResultBuilder";
    private static final String PARAMETER_AUTHENTICATION_RESULT = "authenticationResult";
    private static final String PARAMETER_CREDENTIAL = "credential";
    private static final String PARAMETER_UNAUTHORIZED_REDIRECT_URL = "unauthorizedRedirectUrl";
    private static final String PARAMETER_TICKET_GRANTING_TICKET_ID = "ticketGrantingTicketId";
    private static final String PARAMETER_REGISTERED_SERVICE = "registeredService";
    private static final String PARAMETER_SERVICE = "service";
    private static final String PARAMETER_SERVICE_TICKET_ID = "serviceTicketId";
    private static final String PARAMETER_LOGOUT_REQUESTS = "logoutRequests";

    /**
     * Instantiates a new web utils instance.
     */
    private WebUtils() {
    }

    /**
     * Gets the http servlet request from the context.
     *
     * @param context the context
     * @return the http servlet request
     */
    public static HttpServletRequest getHttpServletRequest(
            final RequestContext context) {
        Assert.isInstanceOf(ServletExternalContext.class, context
                        .getExternalContext(),
                "Cannot obtain HttpServletRequest from event of type: "
                        + context.getExternalContext().getClass().getName());

        return (HttpServletRequest) context.getExternalContext().getNativeRequest();
    }

    /**
     * Gets the http servlet request from the current servlet context.
     *
     * @return the http servlet request
     */
    public static HttpServletRequest getHttpServletRequest() {
        final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
        if (servletExternalContext != null) {
            return (HttpServletRequest) servletExternalContext.getNativeRequest();
        } else {
            return null;
        }
    }

    /**
     * Gets http servlet request from request attributes.
     *
     * @return the http servlet request from request attributes
     */
    public static HttpServletRequest getHttpServletRequestFromRequestAttributes() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    /**
     * Gets http servlet response from request attributes.
     *
     * @return the http servlet response from request attributes
     */
    public static HttpServletResponse getHttpServletResponseFromRequestAttributes() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
    }

    /**
     * Gets the http servlet response from the context.
     *
     * @param context the context
     * @return the http servlet response
     */
    public static HttpServletResponse getHttpServletResponse(
            final RequestContext context) {
        Assert.isInstanceOf(ServletExternalContext.class, context.getExternalContext(),
                "Cannot obtain HttpServletResponse from event of type: " + context.getExternalContext().getClass().getName());
        return (HttpServletResponse) context.getExternalContext().getNativeResponse();
    }

    /**
     * Gets the http servlet response from the current servlet context.
     *
     * @return the http servlet response
     */
    public static HttpServletResponse getHttpServletResponse() {
        final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
        if (servletExternalContext != null) {
            return (HttpServletResponse) servletExternalContext.getNativeResponse();
        } else {
            return null;
        }
    }

    /**
     * Gets the service from the request based on given extractors.
     *
     * @param argumentExtractors the argument extractors
     * @param request            the request
     * @return the service, or null.
     */
    public static WebApplicationService getService(
            final List<ArgumentExtractor> argumentExtractors,
            final HttpServletRequest request) {
        return argumentExtractors.stream().map(argumentExtractor -> argumentExtractor.extractService(request))
                .filter(service -> service != null).findFirst().orElse(null);
    }

    /**
     * Gets the service.
     *
     * @param argumentExtractors the argument extractors
     * @param context            the context
     * @return the service
     */
    public static WebApplicationService getService(
            final List<ArgumentExtractor> argumentExtractors,
            final RequestContext context) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        return getService(argumentExtractors, request);
    }

    /**
     * Gets the service from the flow scope.
     *
     * @param context the context
     * @return the service
     */
    public static WebApplicationService getService(final RequestContext context) {
        return context != null ? (WebApplicationService) context.getFlowScope().get(PARAMETER_SERVICE) : null;
    }

    /**
     * Gets the registered service from the flow scope.
     *
     * @param context the context
     * @return the service
     */
    public static RegisteredService getRegisteredService(final RequestContext context) {
        return context != null ? (RegisteredService) context.getFlowScope().get(PARAMETER_REGISTERED_SERVICE) : null;
    }

    /**
     * Put ticket granting ticket in request and flow scopes.
     *
     * @param context the context
     * @param ticket  the ticket value
     */
    public static void putTicketGrantingTicketInScopes(
            final RequestContext context, final TicketGrantingTicket ticket) {
        final String ticketValue = ticket != null ? ticket.getId() : null;
        putTicketGrantingTicketInScopes(context, ticketValue);
    }

    /**
     * Put ticket granting ticket in request and flow scopes.
     *
     * @param context     the context
     * @param ticketValue the ticket value
     */
    public static void putTicketGrantingTicketInScopes(
            final RequestContext context, final String ticketValue) {
        putTicketGrantingTicketIntoMap(context.getRequestScope(), ticketValue);
        putTicketGrantingTicketIntoMap(context.getFlowScope(), ticketValue);
    }

    /**
     * Put ticket granting ticket into map that is either backed by the flow/request scope.
     * Will override the previous value and blank out the setting if value is null or empty.
     *
     * @param map         the map
     * @param ticketValue the ticket value
     */
    public static void putTicketGrantingTicketIntoMap(final MutableAttributeMap map,
                                                      final String ticketValue) {
        map.put(PARAMETER_TICKET_GRANTING_TICKET_ID, ticketValue);
    }

    /**
     * Gets the ticket granting ticket id from the request and flow scopes.
     *
     * @param context the context
     * @return the ticket granting ticket id
     */
    public static String getTicketGrantingTicketId(
            final RequestContext context) {
        final String tgtFromRequest = (String) context.getRequestScope().get(PARAMETER_TICKET_GRANTING_TICKET_ID);
        final String tgtFromFlow = (String) context.getFlowScope().get(PARAMETER_TICKET_GRANTING_TICKET_ID);

        return tgtFromRequest != null ? tgtFromRequest : tgtFromFlow;

    }

    /**
     * Put service ticket in request scope.
     *
     * @param context     the context
     * @param ticketValue the ticket value
     */
    public static void putServiceTicketInRequestScope(
            final RequestContext context, final ServiceTicket ticketValue) {
        context.getRequestScope().put(PARAMETER_SERVICE_TICKET_ID, ticketValue.getId());
    }

    /**
     * Gets the service ticket from request scope.
     *
     * @param context the context
     * @return the service ticket from request scope
     */
    public static String getServiceTicketFromRequestScope(final RequestContext context) {
        return context.getRequestScope().getString(PARAMETER_SERVICE_TICKET_ID);
    }

    /**
     * Adds the unauthorized redirect url to the flow scope.
     *
     * @param context the request context
     * @param url     the uri to redirect the flow
     */
    public static void putUnauthorizedRedirectUrlIntoFlowScope(final RequestContext context, final URI url) {
        context.getFlowScope().put(PARAMETER_UNAUTHORIZED_REDIRECT_URL, url);
    }

    /**
     * Put logout requests into flow scope.
     *
     * @param context  the context
     * @param requests the requests
     */
    public static void putLogoutRequests(final RequestContext context, final List<LogoutRequest> requests) {
        context.getFlowScope().put(PARAMETER_LOGOUT_REQUESTS, requests);
    }

    /**
     * Gets the logout requests from flow scope.
     *
     * @param context the context
     * @return the logout requests
     */
    public static List<LogoutRequest> getLogoutRequests(final RequestContext context) {
        return (List<LogoutRequest>) context.getFlowScope().get(PARAMETER_LOGOUT_REQUESTS);
    }

    /**
     * Put service into flowscope.
     *
     * @param context the context
     * @param service the service
     */
    public static void putService(final RequestContext context, final Service service) {
        context.getFlowScope().put(PARAMETER_SERVICE, service);
    }

    /**
     * Put warning cookie value into flowscope.
     *
     * @param context     the context
     * @param cookieValue the cookie value
     */
    public static void putWarningCookie(final RequestContext context, final Boolean cookieValue) {
        context.getFlowScope().put("warnCookieValue", cookieValue);
    }

    /**
     * Put registered service into flowscope.
     *
     * @param context           the context
     * @param registeredService the service
     */
    public static void putRegisteredService(final RequestContext context,
                                            final RegisteredService registeredService) {
        context.getFlowScope().put(PARAMETER_REGISTERED_SERVICE, registeredService);
    }

    /**
     * Gets credential from the context.
     *
     * @param context the context
     * @return the credential, or null if it cant be found in the context or if it has no id.
     */
    public static Credential getCredential(final RequestContext context) {
        final Credential cFromRequest = (Credential) context.getRequestScope().get(PARAMETER_CREDENTIAL);
        final Credential cFromFlow = (Credential) context.getFlowScope().get(PARAMETER_CREDENTIAL);

        Credential credential = cFromRequest != null ? cFromRequest : cFromFlow;

        if (credential == null) {
            final FlowSession session = context.getFlowExecutionContext().getActiveSession();
            credential = session.getScope().get(PARAMETER_CREDENTIAL, Credential.class);
        }
        if (credential != null && StringUtils.isBlank(credential.getId())) {
            return null;
        }
        return credential;
    }

    /**
     * Return the username of the authenticated user (based on pac4j security).
     *
     * @return the authenticated username.
     */
    public static String getAuthenticatedUsername() {
        final HttpServletRequest request = getHttpServletRequest();
        final HttpServletResponse response = getHttpServletResponse();
        if (request != null && response != null) {
            final J2EContext context = new J2EContext(request, response);
            final ProfileManager manager = new ProfileManager(context);
            final Optional<UserProfile> profile = manager.get(true);
            if (profile != null && profile.isPresent()) {
                final String id = profile.get().getId();
                if (id != null) {
                    return id;
                }
            }
        }
        return UNKNOWN_USER;
    }

    /**
     * Is authenticating at a public workstation?
     *
     * @param ctx the ctx
     * @return true if the cookie value is present
     */
    public static boolean isAuthenticatingAtPublicWorkstation(final RequestContext ctx) {
        if (ctx.getFlowScope().contains(PUBLIC_WORKSTATION_ATTRIBUTE)) {
            LOGGER.debug("Public workstation flag detected. SSO session will be considered renewed.");
            return true;
        }
        return false;
    }

    /**
     * Put public workstation into the flow if request parameter present.
     *
     * @param context the context
     */
    public static void putPublicWorkstationToFlowIfRequestParameterPresent(final RequestContext context) {
        if (StringUtils.isNotBlank(context.getExternalContext().getRequestParameterMap().get(PUBLIC_WORKSTATION_ATTRIBUTE))) {
            context.getFlowScope().put(PUBLIC_WORKSTATION_ATTRIBUTE, Boolean.TRUE);
        }
    }

    /**
     * Put warn cookie if request parameter present.
     *
     * @param warnCookieGenerator the warn cookie generator
     * @param context             the context
     */
    public static void putWarnCookieIfRequestParameterPresent(final CookieGenerator warnCookieGenerator, final RequestContext context) {
        if (warnCookieGenerator != null) {
            LOGGER.debug("Evaluating request to determine if warning cookie should be generated");
            final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
            if (StringUtils.isNotBlank(context.getExternalContext().getRequestParameterMap().get("warn"))) {
                warnCookieGenerator.addCookie(response, "true");
            } else {
                warnCookieGenerator.removeCookie(response);
            }
        } else {
            LOGGER.debug("No warning cookie generator is defined");
        }
    }

    /**
     * Put authentication into conversation scope.
     *
     * @param authentication the authentication
     * @param ctx            the ctx
     */
    public static void putAuthentication(final Authentication authentication, final RequestContext ctx) {
        ctx.getConversationScope().put(PARAMETER_AUTHENTICATION, authentication);
    }

    /**
     * Gets authentication from conversation scope.
     *
     * @param ctx the ctx
     * @return the authentication
     */
    public static Authentication getAuthentication(final RequestContext ctx) {
        return ctx.getConversationScope().get(PARAMETER_AUTHENTICATION, Authentication.class);
    }

    /**
     * Put authentication result builder.
     *
     * @param builder the builder
     * @param ctx     the ctx
     */
    public static void putAuthenticationResultBuilder(final AuthenticationResultBuilder builder, final RequestContext ctx) {
        ctx.getConversationScope().put(PARAMETER_AUTHENTICATION_RESULT_BUILDER, builder);
    }

    /**
     * Gets authentication result builder.
     *
     * @param ctx the ctx
     * @return the authentication result builder
     */
    public static AuthenticationResultBuilder getAuthenticationResultBuilder(final RequestContext ctx) {
        return ctx.getConversationScope().get(PARAMETER_AUTHENTICATION_RESULT_BUILDER, AuthenticationResultBuilder.class);
    }

    /**
     * Put authentication result.
     *
     * @param authenticationResult the authentication result
     * @param context              the context
     */
    public static void putAuthenticationResult(final AuthenticationResult authenticationResult, final RequestContext context) {
        context.getConversationScope().put(PARAMETER_AUTHENTICATION_RESULT, authenticationResult);
    }

    /**
     * Gets authentication result builder.
     *
     * @param ctx the ctx
     * @return the authentication context builder
     */
    public static AuthenticationResult getAuthenticationResult(final RequestContext ctx) {
        return ctx.getConversationScope().get(PARAMETER_AUTHENTICATION_RESULT, AuthenticationResult.class);
    }

    /**
     * Gets http servlet request user agent.
     *
     * @param request the request
     * @return the http servlet request user agent
     */
    public static String getHttpServletRequestUserAgent(final HttpServletRequest request) {
        if (request != null) {
            return request.getHeader(USER_AGENT_HEADER);
        }
        return null;
    }

    /**
     * Gets http servlet request user agent.
     *
     * @return the http servlet request user agent
     */
    public static String getHttpServletRequestUserAgent() {
        return getHttpServletRequestUserAgent(getHttpServletRequest());
    }

    /**
     * Gets http servlet request geo location.
     *
     * @return the http servlet request geo location
     */
    public static GeoLocationRequest getHttpServletRequestGeoLocation() {
        final int latIndex = 0;
        final int longIndex = 1;
        final int accuIndex = 2;
        final int timeIndex = 3;

        final HttpServletRequest request = WebUtils.getHttpServletRequest();
        final GeoLocationRequest loc = new GeoLocationRequest();
        if (request != null) {
            final String geoLocationParam = request.getParameter("geolocation");
            if (StringUtils.isNotBlank(geoLocationParam)) {
                final String[] geoLocation = geoLocationParam.split(",");
                loc.setLatitude(geoLocation[latIndex]);
                loc.setLongitude(geoLocation[longIndex]);
                loc.setAccuracy(geoLocation[accuIndex]);
                loc.setTimestamp(geoLocation[timeIndex]);
            }
        }
        return loc;
    }

    /**
     * Put geo location tracking into flow scope.
     *
     * @param context the context
     * @param value   the value
     */
    public static void putGeoLocationTrackingIntoFlowScope(final RequestContext context, final Object value) {
        context.getFlowScope().put("trackGeoLocation", value);
    }

    /**
     * Put recaptcha site key into flow scope.
     *
     * @param context the context
     * @param value   the value
     */
    public static void putRecaptchaSiteKeyIntoFlowScope(final RequestContext context, final Object value) {
        context.getFlowScope().put("recaptchaSiteKey", value);
    }

    /**
     * Put static authentication into flow scope.
     *
     * @param context the context
     * @param value   the value
     */
    public static void putStaticAuthenticationIntoFlowScope(final RequestContext context, final Object value) {
        context.getFlowScope().put("staticAuthentication", value);
    }

    /**
     * Put tracking id into flow scope.
     *
     * @param context the context
     * @param value   the value
     */
    public static void putGoogleAnalyticsTrackingIdIntoFlowScope(final RequestContext context, final Object value) {
        context.getFlowScope().put("googleAnalyticsTrackingId", value);
    }

    /**
     * Put unauthorized redirect url into flowscope.
     *
     * @param context                 the context
     * @param unauthorizedRedirectUrl the url to redirect to
     */
    public static void putUnauthorizedRedirectUrl(final RequestContext context,
                                                  final URI unauthorizedRedirectUrl) {
        context.getFlowScope().put(PARAMETER_UNAUTHORIZED_REDIRECT_URL, unauthorizedRedirectUrl);
    }

    /**
     * Put principal.
     *
     * @param requestContext          the request context
     * @param authenticationPrincipal the authentication principal
     */
    public static void putPrincipal(final RequestContext requestContext, final Principal authenticationPrincipal) {
        requestContext.getFlowScope().put("principal", authenticationPrincipal);
    }
}


text:
#ifndef GDCMSWAPPER_H
#define GDCMSWAPPER_H

#include "gdcmSwapCode.h"

namespace gdcm
{

#ifdef GDCM_WORDS_BIGENDIAN
class SwapperDoOp
{
public:
  template <typename T> static T Swap(T val) {return val;}
  template <typename T> static void SwapArray(T *, unsigned int ) {}
};

class SwapperNoOp
{
public:
  template <typename T> static T Swap(T val);
  template <typename T>
  static void SwapArray(T *array, unsigned int n)
  {
    // TODO: need to unroll loop:
    for(unsigned int i = 0; i < n; ++i)
    {
      array[i] = Swap<T>(array[i]);
    }
  }
};
#else
class SwapperNoOp
{
public:
  template <typename T> static T Swap(T val) {return val;}
  template <typename T> static void SwapArray(T *, size_t ) {}
};

class SwapperDoOp
{
public:
  template <typename T> static T Swap(T val);
  template <typename T>
  static void SwapArray(T *array, size_t n)
  {
    // TODO: need to unroll loop:
    for(size_t i = 0; i < n; ++i)
    {
      array[i] = Swap<T>(array[i]);
    }
  }
};
#endif

} // end namespace gdcm

#include "gdcmSwapper.txx"

#endif //GDCMSWAPPER_H


text:
<?php

import('announcement.PKPAnnouncement');

class PKPAnnouncementDAO extends DAO {
	/**
	 * Retrieve an announcement by announcement ID.
	 * @param $announcementId int
	 * @return Announcement
	 */
	function &getAnnouncement($announcementId) {
		$result =& $this->retrieve(
			'SELECT * FROM announcements WHERE announcement_id = ?', $announcementId
		);

		$returner = null;
		if ($result->RecordCount() != 0) {
			$returner =& $this->_returnAnnouncementFromRow($result->GetRowAssoc(false));
		}
		$result->Close();
		return $returner;
	}

	/**
	 * Retrieve announcement Assoc ID by announcement ID.
	 * @param $announcementId int
	 * @return int
	 */
	function getAnnouncementAssocId($announcementId) {
		$result =& $this->retrieve(
			'SELECT assoc_id FROM announcements WHERE announcement_id = ?', $announcementId
		);

		return isset($result->fields[0]) ? $result->fields[0] : 0;
	}

	/**
	 * Retrieve announcement Assoc ID by announcement ID.
	 * @param $announcementId int
	 * @return int
	 */
	function getAnnouncementAssocType($announcementId) {
		$result =& $this->retrieve(
			'SELECT assoc_type FROM announcements WHERE announcement_id = ?', $announcementId
		);

		return isset($result->fields[0]) ? $result->fields[0] : 0;
	}

	/**
	 * Get the list of localized field names for this table
	 * @return array
	 */
	function getLocaleFieldNames() {
		return array('title', 'descriptionShort', 'description');
	}

	/**
	 * Internal function to return an Announcement object from a row.
	 * @param $row array
	 * @return Announcement
	 */
	function &_returnAnnouncementFromRow(&$row) {
		$announcement = new Announcement();
		$announcement->setId($row['announcement_id']);
		$announcement->setAssocType($row['assoc_type']);
		$announcement->setAssocId($row['assoc_id']);
		$announcement->setTypeId($row['type_id']);
		$announcement->setDateExpire($this->dateFromDB($row['date_expire']));
		$announcement->setDatePosted($this->datetimeFromDB($row['date_posted']));

		$this->getDataObjectSettings('announcement_settings', 'announcement_id', $row['announcement_id'], $announcement);

		return $announcement;
	}

	/**
	 * Update the settings for this object
	 * @param $announcement object
	 */
	function updateLocaleFields(&$announcement) {
		$this->updateDataObjectSettings('announcement_settings', $announcement, array(
			'announcement_id' => $announcement->getId()
		));
	}

	/**
	 * Insert a new Announcement.
	 * @param $announcement Announcement
	 * @return int
	 */
	function insertAnnouncement(&$announcement) {
		$this->update(
			sprintf('INSERT INTO announcements
				(assoc_type, assoc_id, type_id, date_expire, date_posted)
				VALUES
				(?, ?, ?, %s, %s)',
				$this->datetimeToDB($announcement->getDateExpire()), $this->datetimeToDB($announcement->getDatetimePosted())),
			array(
				$announcement->getAssocType(),
				$announcement->getAssocId(),
				$announcement->getTypeId()
			)
		);
		$announcement->setId($this->getInsertAnnouncementId());
		$this->updateLocaleFields($announcement);
		return $announcement->getId();
	}

	/**
	 * Update an existing announcement.
	 * @param $announcement Announcement
	 * @return boolean
	 */
	function updateObject(&$announcement) {
		$returner = $this->update(
			sprintf('UPDATE announcements
				SET
					assoc_type = ?,
					assoc_id = ?,
					type_id = ?,
					date_expire = %s
				WHERE announcement_id = ?',
				$this->datetimeToDB($announcement->getDateExpire())),
			array(
				$announcement->getAssocType(),
				$announcement->getAssocId(),
				$announcement->getTypeId(),
				$announcement->getId()
			)
		);
		$this->updateLocaleFields($announcement);
		return $returner;
	}

	function updateAnnouncement(&$announcement) {
		if (Config::getVar('debug', 'deprecation_warnings')) trigger_error('Deprecated function.');
		return $this->updateObject($announcement);
	}

	/**
	 * Delete an announcement.
	 * @param $announcement Announcement
	 * @return boolean
	 */
	function deleteObject($announcement) {
		return $this->deleteAnnouncementById($announcement->getId());
	}

	function deleteAnnouncement($announcement) {
		if (Config::getVar('debug', 'deprecation_warnings')) trigger_error('Deprecated function.');
		return $this->deleteObject($announcement);
	}

	/**
	 * Delete an announcement by announcement ID.
	 * @param $announcementId int
	 * @return boolean
	 */
	function deleteAnnouncementById($announcementId) {
		$this->update('DELETE FROM announcement_settings WHERE announcement_id = ?', $announcementId);
		return $this->update('DELETE FROM announcements WHERE announcement_id = ?', $announcementId);
	}

	/**
	 * Delete announcements by announcement type ID.
	 * @param $typeId int
	 * @return boolean
	 */
	function deleteAnnouncementByTypeId($typeId) {
		$announcements =& $this->getAnnouncementsByTypeId($typeId);
		while (($announcement =& $announcements->next())) {
			$this->deleteObject($announcement);
			unset($announcement);
		}
	}

	/**
	 * Delete announcements by Assoc ID
	 * @param $assocType int
	 * @param $assocId int
	 */
	 function deleteAnnouncementsByAssocId($assocType, $assocId) {
		$announcements =& $this->getAnnouncementsByAssocId($assocType, $assocId);
		while (($announcement =& $announcements->next())) {
			$this->deleteAnnouncementById($announcement->getId());
			unset($announcement);
		}
		return true;
	 }

	/**
	 * Retrieve an array of announcements matching a particular assoc ID.
	 * @param $assocType int
	 * @return object DAOResultFactory containing matching Announcements
	 */
	function &getAnnouncementsByAssocId($assocType, $assocId, $rangeInfo = null) {
		$result =& $this->retrieveRange(
			'SELECT *
			FROM announcements
			WHERE assoc_type = ? AND assoc_id = ?
			ORDER BY announcement_id DESC',
			array($assocType, $assocId),
			$rangeInfo
		);

		$returner = new DAOResultFactory($result, $this, '_returnAnnouncementFromRow');
		return $returner;
	}

	/**
	 * Retrieve an array of announcements matching a particular type ID.
	 * @param $typeId int
	 * @return object DAOResultFactory containing matching Announcements
	 */
	function &getAnnouncementsByTypeId($typeId, $rangeInfo = null) {
		$result =& $this->retrieveRange(
			'SELECT * FROM announcements WHERE type_id = ? ORDER BY announcement_id DESC', $typeId, $rangeInfo
		);

		$returner = new DAOResultFactory($result, $this, '_returnAnnouncementFromRow');
		return $returner;
	}

	/**
	 * Retrieve an array of numAnnouncements announcements matching a particular Assoc ID.
	 * @param $assocType int
	 * @return object DAOResultFactory containing matching Announcements
	 */
	function &getNumAnnouncementsByAssocId($assocType, $assocId, $numAnnouncements, $rangeInfo = null) {
		$result =& $this->retrieveRange(
			'SELECT *
			FROM announcements
			WHERE assoc_type = ?
				AND assoc_id = ?
			ORDER BY announcement_id DESC LIMIT ?',
			array($assocType, $assocId, $numAnnouncements),
			$rangeInfo
		);

		$returner = new DAOResultFactory($result, $this, '_returnAnnouncementFromRow');
		return $returner;
	}

	/**
	 * Retrieve an array of announcements with no/valid expiry date matching a particular Assoc ID.
	 * @param $assocType int
	 * @return object DAOResultFactory containing matching Announcements
	 */
	function &getAnnouncementsNotExpiredByAssocId($assocType, $assocId, $rangeInfo = null) {
		$result =& $this->retrieveRange(
			'SELECT *
			FROM announcements
			WHERE assoc_type = ?
				AND assoc_id = ?
				AND (date_expire IS NULL OR date_expire > CURRENT_DATE)
			ORDER BY announcement_id DESC',
			array($assocType, $assocId),
			$rangeInfo
		);

		$returner = new DAOResultFactory($result, $this, '_returnAnnouncementFromRow');
		return $returner;
	}

	/**
	 * Retrieve an array of numAnnouncements announcements with no/valid expiry date matching a particular Assoc ID.
	 * @param $assocType int
	 * @return object DAOResultFactory containing matching Announcements
	 */
	function &getNumAnnouncementsNotExpiredByAssocId($assocType, $assocId, $numAnnouncements, $rangeInfo = null) {
		$result =& $this->retrieveRange(
			'SELECT *
			FROM announcements
			WHERE assoc_type = ?
				AND assoc_id = ?
				AND (date_expire IS NULL OR date_expire > CURRENT_DATE)
			ORDER BY announcement_id DESC LIMIT ?',
			array($assocType, $assocId, $numAnnouncements), $rangeInfo
		);

		$returner = new DAOResultFactory($result, $this, '_returnAnnouncementFromRow');
		return $returner;
	}

	/**
	 * Retrieve most recent announcement by Assoc ID.
	 * @param $assocType int
	 * @return Announcement
	 */
	function &getMostRecentAnnouncementByAssocId($assocType, $assocId) {
		$result =& $this->retrieve(
			'SELECT *
			FROM announcements
			WHERE assoc_type = ?
				AND assoc_id = ?
			ORDER BY announcement_id DESC LIMIT 1',
			array($assocType, $assocId)
		);

		$returner = null;
		if ($result->RecordCount() != 0) {
			$returner =& $this->_returnAnnouncementFromRow($result->GetRowAssoc(false));
		}
		$result->Close();
		return $returner;
	}

	/**
	 * Get the ID of the last inserted announcement.
	 * @return int
	 */
	function getInsertAnnouncementId() {
		return $this->getInsertId('announcements', 'announcement_id');
	}
}

?>


text:
{-# LANGUAGE TypeFamilies, KindSignatures, StandaloneDeriving, RankNTypes, TypeOperators, FlexibleContexts, LambdaCase #-}
{-# LANGUAGE ExistentialQuantification #-}

{-| observed sharing.

<http://www.ittc.ku.edu/~andygill/papers/reifyGraph.pdf>

-}
module Data.HFunctor.ObserveSharing where
--import Commands.Extra (forceStableName )
import Data.HPrelude
import Data.HFunctor.Recursion
import Data.Some

import Data.Hashable
--import qualified Data.HashMap.Lazy as Map
import           Data.HashMap.Lazy (HashMap)

--import Control.Monad.Trans.State
--import           Data.Function                   ((&))
import System.Mem.StableName

{-

data SomeStableName = forall x. SomeStableName (StableName x)

instance Eq SomeStableName where
 SomeStableName s1 == SomeStableName s2 = eqStableName s1 s2

instance Hashable SomeStableName where
  hashWithSalt salt (SomeStableName s) = hashWithSalt salt s

{-| 'hsearch' where @k@ is a 'StableName' and @v@ is @t@.

-}
hsearchByStableName
 :: ( (h ~ HBase t) , HTraversable h, HCoRecursive t
    )
 => (forall x. t x -> Bool)     -- ^ True means we should track this case
 -> (forall x. t x -> IO (HashMap (SomeStableName) (Some t)))
hsearchByStableName= undefined
-- hsearchByStableName f = hsearch g
--  where
--  g x = if f x
--   then do
--        s <- forceStableName x
--        return $ Just (SomeStableName s, Some x)
--   else return Nothing

{-|

-}
hsearch
 :: ( Monad m , Eq k, Hashable k
    , (h ~ HBase t) , HTraversable h, HCoRecursive t
    )
 => (forall x. t x -> m (Maybe (k, v))) -- like a Prism.
 -> (forall x. t x -> m (HashMap k v))
hsearch = undefined

-}


text:
#ifdef FSYS_EXT2FS

#include "shared.h"
#include "filesys.h"

static int mapblock1, mapblock2;

/* sizes are always in bytes, BLOCK values are always in DEV_BSIZE (sectors) */
#define DEV_BSIZE 512

/* include/linux/fs.h */
#define BLOCK_SIZE 1024		/* initial block size for superblock read */
/* made up, defaults to 1 but can be passed via mount_opts */
#define WHICH_SUPER 1
/* kind of from fs/ext2/super.c */
#define SBLOCK (WHICH_SUPER * BLOCK_SIZE / DEV_BSIZE)	/* = 2 */

/* include/asm-i386/types.h */
typedef __signed__ char __s8;
typedef unsigned char __u8;
typedef __signed__ short __s16;
typedef unsigned short __u16;
typedef __signed__ int __s32;
typedef unsigned int __u32;

/*
 * Constants relative to the data blocks, from ext2_fs.h
 */
#define EXT2_NDIR_BLOCKS                12
#define EXT2_IND_BLOCK                  EXT2_NDIR_BLOCKS
#define EXT2_DIND_BLOCK                 (EXT2_IND_BLOCK + 1)
#define EXT2_TIND_BLOCK                 (EXT2_DIND_BLOCK + 1)
#define EXT2_N_BLOCKS                   (EXT2_TIND_BLOCK + 1)

/* include/linux/ext2_fs.h */
struct ext2_super_block
  {
    __u32 s_inodes_count;	/* Inodes count */
    __u32 s_blocks_count;	/* Blocks count */
    __u32 s_r_blocks_count;	/* Reserved blocks count */
    __u32 s_free_blocks_count;	/* Free blocks count */
    __u32 s_free_inodes_count;	/* Free inodes count */
    __u32 s_first_data_block;	/* First Data Block */
    __u32 s_log_block_size;	/* Block size */
    __s32 s_log_frag_size;	/* Fragment size */
    __u32 s_blocks_per_group;	/* # Blocks per group */
    __u32 s_frags_per_group;	/* # Fragments per group */
    __u32 s_inodes_per_group;	/* # Inodes per group */
    __u32 s_mtime;		/* Mount time */
    __u32 s_wtime;		/* Write time */
    __u16 s_mnt_count;		/* Mount count */
    __s16 s_max_mnt_count;	/* Maximal mount count */
    __u16 s_magic;		/* Magic signature */
    __u16 s_state;		/* File system state */
    __u16 s_errors;		/* Behaviour when detecting errors */
    __u16 s_pad;
    __u32 s_lastcheck;		/* time of last check */
    __u32 s_checkinterval;	/* max. time between checks */
    __u32 s_creator_os;		/* OS */
    __u32 s_rev_level;		/* Revision level */
    __u16 s_def_resuid;		/* Default uid for reserved blocks */
    __u16 s_def_resgid;		/* Default gid for reserved blocks */
    __u32 s_reserved[235];	/* Padding to the end of the block */
  };

struct ext2_group_desc
  {
    __u32 bg_block_bitmap;	/* Blocks bitmap block */
    __u32 bg_inode_bitmap;	/* Inodes bitmap block */
    __u32 bg_inode_table;	/* Inodes table block */
    __u16 bg_free_blocks_count;	/* Free blocks count */
    __u16 bg_free_inodes_count;	/* Free inodes count */
    __u16 bg_used_dirs_count;	/* Directories count */
    __u16 bg_pad;
    __u32 bg_reserved[3];
  };

struct ext2_inode
  {
    __u16 i_mode;		/* File mode */
    __u16 i_uid;		/* Owner Uid */
    __u32 i_size;		/* 4: Size in bytes */
    __u32 i_atime;		/* Access time */
    __u32 i_ctime;		/* 12: Creation time */
    __u32 i_mtime;		/* Modification time */
    __u32 i_dtime;		/* 20: Deletion Time */
    __u16 i_gid;		/* Group Id */
    __u16 i_links_count;	/* 24: Links count */
    __u32 i_blocks;		/* Blocks count */
    __u32 i_flags;		/* 32: File flags */
    union
      {
	struct
	  {
	    __u32 l_i_reserved1;
	  }
	linux1;
	struct
	  {
	    __u32 h_i_translator;
	  }
	hurd1;
	struct
	  {
	    __u32 m_i_reserved1;
	  }
	masix1;
      }
    osd1;			/* OS dependent 1 */
    __u32 i_block[EXT2_N_BLOCKS];	/* 40: Pointers to blocks */
    __u32 i_version;		/* File version (for NFS) */
    __u32 i_file_acl;		/* File ACL */
    __u32 i_dir_acl;		/* Directory ACL */
    __u32 i_faddr;		/* Fragment address */
    union
      {
	struct
	  {
	    __u8 l_i_frag;	/* Fragment number */
	    __u8 l_i_fsize;	/* Fragment size */
	    __u16 i_pad1;
	    __u32 l_i_reserved2[2];
	  }
	linux2;
	struct
	  {
	    __u8 h_i_frag;	/* Fragment number */
	    __u8 h_i_fsize;	/* Fragment size */
	    __u16 h_i_mode_high;
	    __u16 h_i_uid_high;
	    __u16 h_i_gid_high;
	    __u32 h_i_author;
	  }
	hurd2;
	struct
	  {
	    __u8 m_i_frag;	/* Fragment number */
	    __u8 m_i_fsize;	/* Fragment size */
	    __u16 m_pad1;
	    __u32 m_i_reserved2[2];
	  }
	masix2;
      }
    osd2;			/* OS dependent 2 */
  };

/* linux/limits.h */
#define NAME_MAX         255	/* # chars in a file name */

/* linux/posix_type.h */
typedef long linux_off_t;

/* linux/ext2fs.h */
#define EXT2_NAME_LEN 255
struct ext2_dir_entry
  {
    __u32 inode;		/* Inode number */
    __u16 rec_len;		/* Directory entry length */
    __u8 name_len;		/* Name length */
    __u8 file_type;
    char name[EXT2_NAME_LEN];	/* File name */
  };

/* linux/ext2fs.h */
/*
 * EXT2_DIR_PAD defines the directory entries boundaries
 *
 * NOTE: It must be a multiple of 4
 */
#define EXT2_DIR_PAD                    4
#define EXT2_DIR_ROUND                  (EXT2_DIR_PAD - 1)
#define EXT2_DIR_REC_LEN(name_len)      (((name_len) + 8 + EXT2_DIR_ROUND) & \
                                         ~EXT2_DIR_ROUND)

/* ext2/super.c */
#define log2(n) ffz(~(n))

#define EXT2_SUPER_MAGIC      0xEF53	/* include/linux/ext2_fs.h */
#define EXT2_ROOT_INO              2	/* include/linux/ext2_fs.h */
#define PATH_MAX                1024	/* include/linux/limits.h */
#define MAX_LINK_COUNT             5	/* number of symbolic links to follow */

/* made up, these are pointers into FSYS_BUF */
/* read once, always stays there: */
#define SUPERBLOCK \
    ((struct ext2_super_block *)(FSYS_BUF))
#define GROUP_DESC \
    ((struct ext2_group_desc *) \
     ((int)SUPERBLOCK + sizeof(struct ext2_super_block)))
#define INODE \
    ((struct ext2_inode *)((int)GROUP_DESC + EXT2_BLOCK_SIZE(SUPERBLOCK)))
#define DATABLOCK1 \
    ((int)((int)INODE + sizeof(struct ext2_inode)))
#define DATABLOCK2 \
    ((int)((int)DATABLOCK1 + EXT2_BLOCK_SIZE(SUPERBLOCK)))

/* linux/ext2_fs.h */
#define EXT2_ADDR_PER_BLOCK(s)          (EXT2_BLOCK_SIZE(s) / sizeof (__u32))
#define EXT2_ADDR_PER_BLOCK_BITS(s)		(log2(EXT2_ADDR_PER_BLOCK(s)))

/* linux/ext2_fs.h */
#define EXT2_BLOCK_SIZE_BITS(s)        ((s)->s_log_block_size + 10)
/* kind of from ext2/super.c */
#define EXT2_BLOCK_SIZE(s)	(1 << EXT2_BLOCK_SIZE_BITS(s))
/* linux/ext2fs.h */
#define EXT2_DESC_PER_BLOCK(s) \
     (EXT2_BLOCK_SIZE(s) / sizeof (struct ext2_group_desc))
/* linux/stat.h */
#define S_IFMT  00170000
#define S_IFLNK  0120000
#define S_IFREG  0100000
#define S_IFDIR  0040000
#define S_ISLNK(m)	(((m) & S_IFMT) == S_IFLNK)
#define S_ISREG(m)      (((m) & S_IFMT) == S_IFREG)
#define S_ISDIR(m)      (((m) & S_IFMT) == S_IFDIR)

/* include/asm-i386/bitops.h */
/*
 * ffz = Find First Zero in word. Undefined if no zero exists,
 * so code should check against ~0UL first..
 */
static __inline__ unsigned long
ffz (unsigned long word)
{
  __asm__ ("bsfl %1,%0"
:	   "=r" (word)
:	   "r" (~word));
  return word;
}

/* check filesystem types and read superblock into memory buffer */
int
ext2fs_mount (void)
{
  int retval = 1;

  if ((((current_drive & 0x80) || (current_slice != 0))
       && (current_slice != PC_SLICE_TYPE_EXT2FS)
       && (current_slice != PC_SLICE_TYPE_LINUX_RAID)
       && (! IS_PC_SLICE_TYPE_BSD_WITH_FS (current_slice, FS_EXT2FS))
       && (! IS_PC_SLICE_TYPE_BSD_WITH_FS (current_slice, FS_OTHER)))
      || part_length < (SBLOCK + (sizeof (struct ext2_super_block) / DEV_BSIZE))
      || !devread (SBLOCK, 0, sizeof (struct ext2_super_block),
		   (char *) SUPERBLOCK)
      || SUPERBLOCK->s_magic != EXT2_SUPER_MAGIC)
      retval = 0;

  return retval;
}

/* Takes a file system block number and reads it into BUFFER. */
static int
ext2_rdfsb (int fsblock, int buffer)
{
#ifdef E2DEBUG
  printf ("fsblock %d buffer %d\n", fsblock, buffer);
#endif /* E2DEBUG */
  return devread (fsblock * (EXT2_BLOCK_SIZE (SUPERBLOCK) / DEV_BSIZE), 0,
		  EXT2_BLOCK_SIZE (SUPERBLOCK), (char *) buffer);
}

/* from
  ext2/inode.c:ext2_bmap()
*/
/* Maps LOGICAL_BLOCK (the file offset divided by the blocksize) into
   a physical block (the location in the file system) via an inode. */
static int
ext2fs_block_map (int logical_block)
{

#ifdef E2DEBUG
  unsigned char *i;
  for (i = (unsigned char *) INODE;
       i < ((unsigned char *) INODE + sizeof (struct ext2_inode));
       i++)
    {
      printf ("%c", "0123456789abcdef"[*i >> 4]);
      printf ("%c", "0123456789abcdef"[*i % 16]);
      if (!((i + 1 - (unsigned char *) INODE) % 16))
	{
	  printf ("\n");
	}
      else
	{
	  printf (" ");
	}
    }
  printf ("logical block %d\n", logical_block);
#endif /* E2DEBUG */

  /* if it is directly pointed to by the inode, return that physical addr */
  if (logical_block < EXT2_NDIR_BLOCKS)
    {
#ifdef E2DEBUG
      printf ("returning %d\n", (unsigned char *) (INODE->i_block[logical_block]));
      printf ("returning %d\n", INODE->i_block[logical_block]);
#endif /* E2DEBUG */
      return INODE->i_block[logical_block];
    }
  /* else */
  logical_block -= EXT2_NDIR_BLOCKS;
  /* try the indirect block */
  if (logical_block < EXT2_ADDR_PER_BLOCK (SUPERBLOCK))
    {
      if (mapblock1 != 1
	  && !ext2_rdfsb (INODE->i_block[EXT2_IND_BLOCK], DATABLOCK1))
	{
	  errnum = ERR_FSYS_CORRUPT;
	  return -1;
	}
      mapblock1 = 1;
      return ((__u32 *) DATABLOCK1)[logical_block];
    }
  /* else */
  logical_block -= EXT2_ADDR_PER_BLOCK (SUPERBLOCK);
  /* now try the double indirect block */
  if (logical_block < (1 << (EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK) * 2)))
    {
      int bnum;
      if (mapblock1 != 2
	  && !ext2_rdfsb (INODE->i_block[EXT2_DIND_BLOCK], DATABLOCK1))
	{
	  errnum = ERR_FSYS_CORRUPT;
	  return -1;
	}
      mapblock1 = 2;
      if ((bnum = (((__u32 *) DATABLOCK1)
		   [logical_block >> EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK)]))
	  != mapblock2
	  && !ext2_rdfsb (bnum, DATABLOCK2))
	{
	  errnum = ERR_FSYS_CORRUPT;
	  return -1;
	}
      mapblock2 = bnum;
      return ((__u32 *) DATABLOCK2)
	[logical_block & (EXT2_ADDR_PER_BLOCK (SUPERBLOCK) - 1)];
    }
  /* else */
  mapblock2 = -1;
  logical_block -= (1 << (EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK) * 2));
  if (mapblock1 != 3
      && !ext2_rdfsb (INODE->i_block[EXT2_TIND_BLOCK], DATABLOCK1))
    {
      errnum = ERR_FSYS_CORRUPT;
      return -1;
    }
  mapblock1 = 3;
  if (!ext2_rdfsb (((__u32 *) DATABLOCK1)
		   [logical_block >> (EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK)
				      * 2)],
		   DATABLOCK2))
    {
      errnum = ERR_FSYS_CORRUPT;
      return -1;
    }
  if (!ext2_rdfsb (((__u32 *) DATABLOCK2)
		   [(logical_block >> EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK))
		    & (EXT2_ADDR_PER_BLOCK (SUPERBLOCK) - 1)],
		   DATABLOCK2))
    {
      errnum = ERR_FSYS_CORRUPT;
      return -1;
    }
  return ((__u32 *) DATABLOCK2)
    [logical_block & (EXT2_ADDR_PER_BLOCK (SUPERBLOCK) - 1)];
}

/* preconditions: all preconds of ext2fs_block_map */
int
ext2fs_read (char *buf, int len)
{
  int logical_block;
  int offset;
  int map;
  int ret = 0;
  int size = 0;

#ifdef E2DEBUG
  static char hexdigit[] = "0123456789abcdef";
  unsigned char *i;
  for (i = (unsigned char *) INODE;
       i < ((unsigned char *) INODE + sizeof (struct ext2_inode));
       i++)
    {
      printf ("%c", hexdigit[*i >> 4]);
      printf ("%c", hexdigit[*i % 16]);
      if (!((i + 1 - (unsigned char *) INODE) % 16))
	{
	  printf ("\n");
	}
      else
	{
	  printf (" ");
	}
    }
#endif /* E2DEBUG */
  while (len > 0)
    {
      /* find the (logical) block component of our location */
      logical_block = filepos >> EXT2_BLOCK_SIZE_BITS (SUPERBLOCK);
      offset = filepos & (EXT2_BLOCK_SIZE (SUPERBLOCK) - 1);
      map = ext2fs_block_map (logical_block);
#ifdef E2DEBUG
      printf ("map=%d\n", map);
#endif /* E2DEBUG */
      if (map < 0)
	break;

      size = EXT2_BLOCK_SIZE (SUPERBLOCK);
      size -= offset;
      if (size > len)
	size = len;

      if (map == 0) {
        memset ((char *) buf, 0, size);
      } else {
        disk_read_func = disk_read_hook;

        devread (map * (EXT2_BLOCK_SIZE (SUPERBLOCK) / DEV_BSIZE),
	         offset, size, buf);

        disk_read_func = NULL;
      }

      buf += size;
      len -= size;
      filepos += size;
      ret += size;
    }

  if (errnum)
    ret = 0;

  return ret;
}

/* Based on:
   def_blk_fops points to
   blkdev_open, which calls (I think):
   sys_open()
   do_open()
   open_namei()
   dir_namei() which accesses current->fs->root
     fs->root was set during original mount:
     (something)... which calls (I think):
     ext2_read_super()
     iget()
     __iget()
     read_inode()
     ext2_read_inode()
       uses desc_per_block_bits, which is set in ext2_read_super()
       also uses group descriptors loaded during ext2_read_super()
   lookup()
   ext2_lookup()
   ext2_find_entry()
   ext2_getblk()

*/

static inline
int ext2_is_fast_symlink (void)
{
  int ea_blocks;
  ea_blocks = INODE->i_file_acl ? EXT2_BLOCK_SIZE (SUPERBLOCK) / DEV_BSIZE : 0;
  return INODE->i_blocks == ea_blocks;
}

/* preconditions: ext2fs_mount already executed, therefore supblk in buffer
 *   known as SUPERBLOCK
 * returns: 0 if error, nonzero iff we were able to find the file successfully
 * postconditions: on a nonzero return, buffer known as INODE contains the
 *   inode of the file we were trying to look up
 * side effects: messes up GROUP_DESC buffer area
 */
int
ext2fs_dir (char *dirname)
{
  int current_ino = EXT2_ROOT_INO;	/* start at the root */
  int updir_ino = current_ino;	/* the parent of the current directory */
  int group_id;			/* which group the inode is in */
  int group_desc;		/* fs pointer to that group */
  int desc;			/* index within that group */
  int ino_blk;			/* fs pointer of the inode's information */
  int str_chk = 0;		/* used to hold the results of a string compare */
  struct ext2_group_desc *gdp;
  struct ext2_inode *raw_inode;	/* inode info corresponding to current_ino */

  char linkbuf[PATH_MAX];	/* buffer for following symbolic links */
  int link_count = 0;

  char *rest;
  char ch;			/* temp char holder */

  int off;			/* offset within block of directory entry (off mod blocksize) */
  int loc;			/* location within a directory */
  int blk;			/* which data blk within dir entry (off div blocksize) */
  long map;			/* fs pointer of a particular block from dir entry */
  struct ext2_dir_entry *dp;	/* pointer to directory entry */
#ifdef E2DEBUG
  unsigned char *i;
#endif	/* E2DEBUG */

  /* loop invariants:
     current_ino = inode to lookup
     dirname = pointer to filename component we are cur looking up within
     the directory known pointed to by current_ino (if any)
   */

  while (1)
    {
#ifdef E2DEBUG
      printf ("inode %d\n", current_ino);
      printf ("dirname=%s\n", dirname);
#endif /* E2DEBUG */

      /* look up an inode */
      group_id = (current_ino - 1) / (SUPERBLOCK->s_inodes_per_group);
      group_desc = group_id >> log2 (EXT2_DESC_PER_BLOCK (SUPERBLOCK));
      desc = group_id & (EXT2_DESC_PER_BLOCK (SUPERBLOCK) - 1);
#ifdef E2DEBUG
      printf ("ipg=%d, dpb=%d\n", SUPERBLOCK->s_inodes_per_group,
	      EXT2_DESC_PER_BLOCK (SUPERBLOCK));
      printf ("group_id=%d group_desc=%d desc=%d\n", group_id, group_desc, desc);
#endif /* E2DEBUG */
      if (!ext2_rdfsb (
			(WHICH_SUPER + group_desc + SUPERBLOCK->s_first_data_block),
			(int) GROUP_DESC))
	{
	  return 0;
	}
      gdp = GROUP_DESC;
      ino_blk = gdp[desc].bg_inode_table +
	(((current_ino - 1) % (SUPERBLOCK->s_inodes_per_group))
	 >> log2 (EXT2_BLOCK_SIZE (SUPERBLOCK) / sizeof (struct ext2_inode)));
#ifdef E2DEBUG
      printf ("inode table fsblock=%d\n", ino_blk);
#endif /* E2DEBUG */
      if (!ext2_rdfsb (ino_blk, (int) INODE))
	{
	  return 0;
	}

      /* reset indirect blocks! */
      mapblock2 = mapblock1 = -1;

      raw_inode = INODE +
	((current_ino - 1)
	 & (EXT2_BLOCK_SIZE (SUPERBLOCK) / sizeof (struct ext2_inode) - 1));
#ifdef E2DEBUG
      printf ("ipb=%d, sizeof(inode)=%d\n",
	      (EXT2_BLOCK_SIZE (SUPERBLOCK) / sizeof (struct ext2_inode)),
	      sizeof (struct ext2_inode));
      printf ("inode=%x, raw_inode=%x\n", INODE, raw_inode);
      printf ("offset into inode table block=%d\n", (int) raw_inode - (int) INODE);
      for (i = (unsigned char *) INODE; i <= (unsigned char *) raw_inode;
	   i++)
	{
	  printf ("%c", "0123456789abcdef"[*i >> 4]);
	  printf ("%c", "0123456789abcdef"[*i % 16]);
	  if (!((i + 1 - (unsigned char *) INODE) % 16))
	    {
	      printf ("\n");
	    }
	  else
	    {
	      printf (" ");
	    }
	}
      printf ("first word=%x\n", *((int *) raw_inode));
#endif /* E2DEBUG */

      /* copy inode to fixed location */
      memmove ((void *) INODE, (void *) raw_inode, sizeof (struct ext2_inode));

#ifdef E2DEBUG
      printf ("first word=%x\n", *((int *) INODE));
#endif /* E2DEBUG */

      /* If we've got a symbolic link, then chase it. */
      if (S_ISLNK (INODE->i_mode))
	{
	  int len;
	  if (++link_count > MAX_LINK_COUNT)
	    {
	      errnum = ERR_SYMLINK_LOOP;
	      return 0;
	    }

	  /* Find out how long our remaining name is. */
	  len = 0;
	  while (dirname[len] && !isspace (dirname[len]))
	    len++;

	  /* Get the symlink size. */
	  filemax = (INODE->i_size);
	  if (filemax + len > sizeof (linkbuf) - 2)
	    {
	      errnum = ERR_FILELENGTH;
	      return 0;
	    }

	  if (len)
	    {
	      /* Copy the remaining name to the end of the symlink data.
	         Note that DIRNAME and LINKBUF may overlap! */
	      memmove (linkbuf + filemax, dirname, len);
	    }
	  linkbuf[filemax + len] = '\0';

	  /* Read the symlink data. */
	  if (! ext2_is_fast_symlink ())
	    {
	      /* Read the necessary blocks, and reset the file pointer. */
	      len = grub_read (linkbuf, filemax);
	      filepos = 0;
	      if (!len)
		return 0;
	    }
	  else
	    {
	      /* Copy the data directly from the inode. */
	      len = filemax;
	      memmove (linkbuf, (char *) INODE->i_block, len);
	    }

#ifdef E2DEBUG
	  printf ("symlink=%s\n", linkbuf);
#endif

	  dirname = linkbuf;
	  if (*dirname == '/')
	    {
	      /* It's an absolute link, so look it up in root. */
	      current_ino = EXT2_ROOT_INO;
	      updir_ino = current_ino;
	    }
	  else
	    {
	      /* Relative, so look it up in our parent directory. */
	      current_ino = updir_ino;
	    }

	  /* Try again using the new name. */
	  continue;
	}

      /* if end of filename, INODE points to the file's inode */
      if (!*dirname || isspace (*dirname))
	{
	  if (!S_ISREG (INODE->i_mode))
	    {
	      errnum = ERR_BAD_FILETYPE;
	      return 0;
	    }

	  filemax = (INODE->i_size);
	  return 1;
	}

      /* else we have to traverse a directory */
      updir_ino = current_ino;

      /* skip over slashes */
      while (*dirname == '/')
	dirname++;

      /* if this isn't a directory of sufficient size to hold our file, abort */
      if (!(INODE->i_size) || !S_ISDIR (INODE->i_mode))
	{
	  errnum = ERR_BAD_FILETYPE;
	  return 0;
	}

      /* skip to next slash or end of filename (space) */
      for (rest = dirname; (ch = *rest) && !isspace (ch) && ch != '/';
	   rest++);

      /* look through this directory and find the next filename component */
      /* invariant: rest points to slash after the next filename component */
      *rest = 0;
      loc = 0;

      do
	{

#ifdef E2DEBUG
	  printf ("dirname=%s, rest=%s, loc=%d\n", dirname, rest, loc);
#endif /* E2DEBUG */

	  /* if our location/byte offset into the directory exceeds the size,
	     give up */
	  if (loc >= INODE->i_size)
	    {
	      if (print_possibilities < 0)
		{
# if 0
		  putchar ('\n');
# endif
		}
	      else
		{
		  errnum = ERR_FILE_NOT_FOUND;
		  *rest = ch;
		}
	      return (print_possibilities < 0);
	    }

	  /* else, find the (logical) block component of our location */
	  blk = loc >> EXT2_BLOCK_SIZE_BITS (SUPERBLOCK);

	  /* we know which logical block of the directory entry we are looking
	     for, now we have to translate that to the physical (fs) block on
	     the disk */
	  map = ext2fs_block_map (blk);
#ifdef E2DEBUG
	  printf ("fs block=%d\n", map);
#endif /* E2DEBUG */
	  mapblock2 = -1;
	  if ((map < 0) || !ext2_rdfsb (map, DATABLOCK2))
	    {
	      errnum = ERR_FSYS_CORRUPT;
	      *rest = ch;
	      return 0;
	    }
	  off = loc & (EXT2_BLOCK_SIZE (SUPERBLOCK) - 1);
	  dp = (struct ext2_dir_entry *) (DATABLOCK2 + off);
	  /* advance loc prematurely to next on-disk directory entry  */
	  loc += dp->rec_len;

	  /* NOTE: ext2fs filenames are NOT null-terminated */

#ifdef E2DEBUG
	  printf ("directory entry ino=%d\n", dp->inode);
	  if (dp->inode)
	    printf ("entry=%s\n", dp->name);
#endif /* E2DEBUG */

	  if (dp->inode)
	    {
	      int saved_c = dp->name[dp->name_len];

	      dp->name[dp->name_len] = 0;
	      str_chk = substring (dirname, dp->name);

# ifndef STAGE1_5
	      if (print_possibilities && ch != '/'
		  && (!*dirname || str_chk <= 0))
		{
		  if (print_possibilities > 0)
		    print_possibilities = -print_possibilities;
		  print_a_completion (dp->name);
		}
# endif

	      dp->name[dp->name_len] = saved_c;
	    }

	}
      while (!dp->inode || (str_chk || (print_possibilities && ch != '/')));

      current_ino = dp->inode;
      *(dirname = rest) = ch;
    }
  /* never get here */
}

#endif /* FSYS_EXT2_FS */


text:
<layout id="LapNotifyLayout">
	<label id="lapLabel" x="center" y="40"     text="Lap" font="Gfx.FONT_MEDIUM" color="Gfx.COLOR_WHITE" justification="Gfx.TEXT_JUSTIFY_CENTER" />
    <label id="lap"      x="center" y="center" text=""    font="Gfx.FONT_NUMBER_THAI_HOT" color="Gfx.COLOR_BLUE" justification="Gfx.TEXT_JUSTIFY_CENTER" />
</layout>


text:
package arp

import "fmt"

const _Operation_name = "OperationRequestOperationReply"

var _Operation_index = [...]uint8{0, 16, 30}

func (i Operation) String() string {
	i -= 1
	if i >= Operation(len(_Operation_index)-1) {
		return fmt.Sprintf("Operation(%d)", i+1)
	}
	return _Operation_name[_Operation_index[i]:_Operation_index[i+1]]
}


text:
import Clockpicker from './Clockpicker'

import { use, registerComponent } from '../../utils/plugins'

const Plugin = {
    install(Vue) {
        registerComponent(Vue, Clockpicker)
    }
}

use(Plugin)

export default Plugin

export {
    Clockpicker as BClockpicker
}


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var Q = require('q');  /* jshint ignore:line */
var _ = require('lodash');  /* jshint ignore:line */
var Page = require('../../../base/Page');  /* jshint ignore:line */
var deserialize = require(
    '../../../base/deserialize');  /* jshint ignore:line */
var serialize = require('../../../base/serialize');  /* jshint ignore:line */
var values = require('../../../base/values');  /* jshint ignore:line */

var EventList;
var EventPage;
var EventInstance;
var EventContext;

/* jshint ignore:start */
/**
 * @constructor Twilio.Monitor.V1.EventList
 * @description Initialize the EventList
 *
 * @param {Twilio.Monitor.V1} version - Version of the resource
 */
/* jshint ignore:end */
EventList = function EventList(version) {
  /* jshint ignore:start */
  /**
   * @function events
   * @memberof Twilio.Monitor.V1
   * @instance
   *
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Monitor.V1.EventContext}
   */
  /* jshint ignore:end */
  function EventListInstance(sid) {
    return EventListInstance.get(sid);
  }

  EventListInstance._version = version;
  // Path Solution
  EventListInstance._solution = {};
  EventListInstance._uri = _.template(
    '/Events' // jshint ignore:line
  )(EventListInstance._solution);
  /* jshint ignore:start */
  /**
   * Streams EventInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function each
   * @memberof Twilio.Monitor.V1.EventList
   * @instance
   *
   * @param {object|function} opts - ...
   * @param {string} [opts.actorSid] - The actor_sid
   * @param {string} [opts.eventType] - The event_type
   * @param {string} [opts.resourceSid] - The resource_sid
   * @param {string} [opts.sourceIpAddress] - The source_ip_address
   * @param {Date} [opts.startDate] - The start_date
   * @param {Date} [opts.endDate] - The end_date
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         each() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize=50] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no pageSize is defined but a limit is defined,
   *         each() will attempt to read the limit with the most efficient
   *         page size, i.e. min(limit, 1000)
   * @param {Function} [opts.callback] -
   *         Function to process each record. If this and a positional
   * callback are passed, this one will be used
   * @param {Function} [opts.done] -
   *          Function to be called upon completion of streaming
   * @param {Function} [callback] - Function to process each record
   */
  /* jshint ignore:end */
  EventListInstance.each = function each(opts, callback) {
    opts = opts || {};
    if (_.isFunction(opts)) {
      opts = { callback: opts };
    } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) {
      opts.callback = callback;
    }

    if (_.isUndefined(opts.callback)) {
      throw new Error('Callback function must be provided');
    }

    var done = false;
    var currentPage = 1;
    var currentResource = 0;
    var limits = this._version.readLimits({
      limit: opts.limit,
      pageSize: opts.pageSize
    });

    function onComplete(error) {
      done = true;
      if (_.isFunction(opts.done)) {
        opts.done(error);
      }
    }

    function fetchNextPage(fn) {
      var promise = fn();
      if (_.isUndefined(promise)) {
        onComplete();
        return;
      }

      promise.then(function(page) {
        _.each(page.instances, function(instance) {
          if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
            done = true;
            return false;
          }

          currentResource++;
          opts.callback(instance, onComplete);
        });

        if ((limits.pageLimit && limits.pageLimit <= currentPage)) {
          onComplete();
        } else if (!done) {
          currentPage++;
          fetchNextPage(_.bind(page.nextPage, page));
        }
      });

      promise.catch(onComplete);
    }

    fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
  };

  /* jshint ignore:start */
  /**
   * @description Lists EventInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function list
   * @memberof Twilio.Monitor.V1.EventList
   * @instance
   *
   * @param {object|function} opts - ...
   * @param {string} [opts.actorSid] - The actor_sid
   * @param {string} [opts.eventType] - The event_type
   * @param {string} [opts.resourceSid] - The resource_sid
   * @param {string} [opts.sourceIpAddress] - The source_ip_address
   * @param {Date} [opts.startDate] - The start_date
   * @param {Date} [opts.endDate] - The end_date
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         list() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no page_size is defined but a limit is defined,
   *         list() will attempt to read the limit with the most
   *         efficient page size, i.e. min(limit, 1000)
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  EventListInstance.list = function list(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    var deferred = Q.defer();
    var allResources = [];
    opts.callback = function(resource, done) {
      allResources.push(resource);

      if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
        done();
      }
    };

    opts.done = function(error) {
      if (_.isUndefined(error)) {
        deferred.resolve(allResources);
      } else {
        deferred.reject(error);
      }
    };

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    this.each(opts);
    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single page of EventInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function page
   * @memberof Twilio.Monitor.V1.EventList
   * @instance
   *
   * @param {object|function} opts - ...
   * @param {string} [opts.actorSid] - The actor_sid
   * @param {string} [opts.eventType] - The event_type
   * @param {string} [opts.resourceSid] - The resource_sid
   * @param {string} [opts.sourceIpAddress] - The source_ip_address
   * @param {Date} [opts.startDate] - The start_date
   * @param {Date} [opts.endDate] - The end_date
   * @param {string} [opts.pageToken] - PageToken provided by the API
   * @param {number} [opts.pageNumber] -
   *          Page Number, this value is simply for client state
   * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  EventListInstance.page = function page(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'ActorSid': _.get(opts, 'actorSid'),
      'EventType': _.get(opts, 'eventType'),
      'ResourceSid': _.get(opts, 'resourceSid'),
      'SourceIpAddress': _.get(opts, 'sourceIpAddress'),
      'StartDate': serialize.iso8601Date(_.get(opts, 'startDate')),
      'EndDate': serialize.iso8601Date(_.get(opts, 'endDate')),
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({
      uri: this._uri,
      method: 'GET',
      params: data
    });

    promise = promise.then(function(payload) {
      deferred.resolve(new EventPage(
        this._version,
        payload,
        this._solution
      ));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single target page of EventInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function getPage
   * @memberof Twilio.Monitor.V1.EventList
   * @instance
   *
   * @param {string} [opts.actorSid] - The actor_sid
   * @param {string} [opts.eventType] - The event_type
   * @param {string} [opts.resourceSid] - The resource_sid
   * @param {string} [opts.sourceIpAddress] - The source_ip_address
   * @param {Date} [opts.startDate] - The start_date
   * @param {Date} [opts.endDate] - The end_date
   * @param {string} [targetUrl] - API-generated URL for the requested results page
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  EventListInstance.getPage = function getPage(targetUrl, callback) {
    var deferred = Q.defer();

    var promise = this._version._domain.twilio.request({
      method: 'GET',
      uri: targetUrl
    });

    promise = promise.then(function(payload) {
      deferred.resolve(new EventPage(
        this._version,
        payload,
        this._solution
      ));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Constructs a event
   *
   * @function get
   * @memberof Twilio.Monitor.V1.EventList
   * @instance
   *
   * @param {string} sid - The sid
   *
   * @returns {Twilio.Monitor.V1.EventContext}
   */
  /* jshint ignore:end */
  EventListInstance.get = function get(sid) {
    return new EventContext(
      this._version,
      sid
    );
  };

  return EventListInstance;
};

/* jshint ignore:start */
/**
 * @constructor Twilio.Monitor.V1.EventPage
 * @augments Page
 * @description Initialize the EventPage
 *
 * @param {Twilio.Monitor.V1} version - Version of the resource
 * @param {object} response - Response from the API
 * @param {object} solution - Path solution
 *
 * @returns EventPage
 */
/* jshint ignore:end */
EventPage = function EventPage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
};

_.extend(EventPage.prototype, Page.prototype);
EventPage.prototype.constructor = EventPage;

/* jshint ignore:start */
/**
 * Build an instance of EventInstance
 *
 * @function getInstance
 * @memberof Twilio.Monitor.V1.EventPage
 * @instance
 *
 * @param {object} payload - Payload response from the API
 *
 * @returns EventInstance
 */
/* jshint ignore:end */
EventPage.prototype.getInstance = function getInstance(payload) {
  return new EventInstance(
    this._version,
    payload
  );
};

/* jshint ignore:start */
/**
 * @constructor Twilio.Monitor.V1.EventInstance
 * @description Initialize the EventContext
 *
 * @property {string} accountSid - The account_sid
 * @property {string} actorSid - The actor_sid
 * @property {string} actorType - The actor_type
 * @property {string} description - The description
 * @property {string} eventData - The event_data
 * @property {Date} eventDate - The event_date
 * @property {string} eventType - The event_type
 * @property {string} resourceSid - The resource_sid
 * @property {string} resourceType - The resource_type
 * @property {string} sid - The sid
 * @property {string} source - The source
 * @property {string} sourceIpAddress - The source_ip_address
 * @property {string} url - The url
 * @property {string} links - The links
 *
 * @param {Twilio.Monitor.V1} version - Version of the resource
 * @param {object} payload - The instance payload
 * @param {sid} sid - The sid
 */
/* jshint ignore:end */
EventInstance = function EventInstance(version, payload, sid) {
  this._version = version;

  // Marshaled Properties
  this.accountSid = payload.account_sid; // jshint ignore:line
  this.actorSid = payload.actor_sid; // jshint ignore:line
  this.actorType = payload.actor_type; // jshint ignore:line
  this.description = payload.description; // jshint ignore:line
  this.eventData = payload.event_data; // jshint ignore:line
  this.eventDate = deserialize.iso8601DateTime(payload.event_date); // jshint ignore:line
  this.eventType = payload.event_type; // jshint ignore:line
  this.resourceSid = payload.resource_sid; // jshint ignore:line
  this.resourceType = payload.resource_type; // jshint ignore:line
  this.sid = payload.sid; // jshint ignore:line
  this.source = payload.source; // jshint ignore:line
  this.sourceIpAddress = payload.source_ip_address; // jshint ignore:line
  this.url = payload.url; // jshint ignore:line
  this.links = payload.links; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {
    sid: sid || this.sid,
  };
};

Object.defineProperty(EventInstance.prototype,
  '_proxy', {
  get: function() {
    if (!this._context) {
      this._context = new EventContext(
        this._version,
        this._solution.sid
      );
    }

    return this._context;
  }
});

/* jshint ignore:start */
/**
 * fetch a EventInstance
 *
 * @function fetch
 * @memberof Twilio.Monitor.V1.EventInstance
 * @instance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed EventInstance
 */
/* jshint ignore:end */
EventInstance.prototype.fetch = function fetch(callback) {
  return this._proxy.fetch(callback);
};

/* jshint ignore:start */
/**
 * @constructor Twilio.Monitor.V1.EventContext
 * @description Initialize the EventContext
 *
 * @param {Twilio.Monitor.V1} version - Version of the resource
 * @param {sid} sid - The sid
 */
/* jshint ignore:end */
EventContext = function EventContext(version, sid) {
  this._version = version;

  // Path Solution
  this._solution = {
    sid: sid,
  };
  this._uri = _.template(
    '/Events/<%= sid %>' // jshint ignore:line
  )(this._solution);
};

/* jshint ignore:start */
/**
 * fetch a EventInstance
 *
 * @function fetch
 * @memberof Twilio.Monitor.V1.EventContext
 * @instance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed EventInstance
 */
/* jshint ignore:end */
EventContext.prototype.fetch = function fetch(callback) {
  var deferred = Q.defer();
  var promise = this._version.fetch({
    uri: this._uri,
    method: 'GET'
  });

  promise = promise.then(function(payload) {
    deferred.resolve(new EventInstance(
      this._version,
      payload,
      this._solution.sid
    ));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

module.exports = {
  EventList: EventList,
  EventPage: EventPage,
  EventInstance: EventInstance,
  EventContext: EventContext
};


text:
@implementation NSManagedObject (SetValues)

// http://www.cimgf.com/2011/06/02/saving-json-to-core-data/

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues dateFormatter:(NSDateFormatter *)dateFormatter mapping:(NSDictionary *)mapping
{
    [self safeSetValuesForKeysWithDictionary:keyedValues dateFormatter:dateFormatter mapping:mapping ignoredAttributes:nil];
}

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues dateFormatter:(NSDateFormatter *)dateFormatter mapping:(NSDictionary *)mapping ignoredAttributes:(NSArray *)ignoredAttributes
{
    NSDictionary *attributes = [[self entity] attributesByName];
    for (NSString *attribute in attributes) {
        if ([ignoredAttributes count] > 0 &&
            [[ignoredAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self == %@", attribute]] count] > 0) {
            continue;
        }
        id value = keyedValues[mapping[attribute]];
        if (value == nil) {
            continue;
        }
        NSAttributeType attributeType = [attributes[attribute] attributeType];
        if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) {
            value = [value stringValue];
        } else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) {
            value = @([value integerValue]);
        } else if ((attributeType == NSFloatAttributeType) &&  ([value isKindOfClass:[NSString class]])) {
            value = [value stringByReplacingOccurrencesOfString:@"," withString:@"."];
            value = @([[value stringByReplacingOccurrencesOfString:@"$" withString:@"" ]  doubleValue]);
        } else if ((attributeType == NSDateAttributeType) && ([value isKindOfClass:[NSString class]]) && (dateFormatter != nil)) {
            value = [dateFormatter dateFromString:value];
        } else if ((attributeType == NSStringAttributeType) &&  ([value isKindOfClass:[NSNull class]])) {
            value = nil;
        }
        [self setValue:value forKey:attribute];
    }
}

@end