text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/services/secure_channel/single_client_proxy_impl.h"

#include "ash/services/secure_channel/file_transfer_update_callback.h"
#include "ash/services/secure_channel/public/mojom/secure_channel_types.mojom.h"
#include "base/callback.h"
#include "base/memory/ptr_util.h"

namespace ash::secure_channel {

// static
SingleClientProxyImpl::Factory* SingleClientProxyImpl::Factory::test_factory_ =
    nullptr;

// static
std::unique_ptr<SingleClientProxy> SingleClientProxyImpl::Factory::Create(
    SingleClientProxy::Delegate* delegate,
    std::unique_ptr<ClientConnectionParameters> client_connection_parameters) {
  if (test_factory_) {
    return test_factory_->CreateInstance(
        delegate, std::move(client_connection_parameters));
  }

  return base::WrapUnique(new SingleClientProxyImpl(
      delegate, std::move(client_connection_parameters)));
}

// static
void SingleClientProxyImpl::Factory::SetFactoryForTesting(Factory* factory) {
  test_factory_ = factory;
}

SingleClientProxyImpl::Factory::~Factory() = default;

SingleClientProxyImpl::SingleClientProxyImpl(
    SingleClientProxy::Delegate* delegate,
    std::unique_ptr<ClientConnectionParameters> client_connection_parameters)
    : SingleClientProxy(delegate),
      client_connection_parameters_(std::move(client_connection_parameters)),
      channel_(std::make_unique<ChannelImpl>(this /* delegate */)) {
  DCHECK(client_connection_parameters_);
  client_connection_parameters_->SetConnectionSucceeded(
      channel_->GenerateRemote(),
      message_receiver_remote_.BindNewPipeAndPassReceiver());
}

SingleClientProxyImpl::~SingleClientProxyImpl() = default;

const base::UnguessableToken& SingleClientProxyImpl::GetProxyId() {
  return client_connection_parameters_->id();
}

void SingleClientProxyImpl::HandleReceivedMessage(const std::string& feature,
                                                  const std::string& payload) {
  // Ignore messages intended for other clients.
  if (feature != client_connection_parameters_->feature())
    return;

  message_receiver_remote_->OnMessageReceived(payload);
}

void SingleClientProxyImpl::HandleRemoteDeviceDisconnection() {
  channel_->HandleRemoteDeviceDisconnection();
}

void SingleClientProxyImpl::OnSendMessageRequested(
    const std::string& message,
    base::OnceClosure on_sent_callback) {
  NotifySendMessageRequested(client_connection_parameters_->feature(), message,
                             std::move(on_sent_callback));
}

void SingleClientProxyImpl::RegisterPayloadFile(
    int64_t payload_id,
    mojom::PayloadFilesPtr payload_files,
    FileTransferUpdateCallback file_transfer_update_callback,
    base::OnceCallback<void(bool)> registration_result_callback) {
  RegisterPayloadFileWithDelegate(payload_id, std::move(payload_files),
                                  std::move(file_transfer_update_callback),
                                  std::move(registration_result_callback));
}

void SingleClientProxyImpl::GetConnectionMetadata(
    base::OnceCallback<void(mojom::ConnectionMetadataPtr)> callback) {
  GetConnectionMetadataFromDelegate(std::move(callback));
}

void SingleClientProxyImpl::OnClientDisconnected() {
  NotifyClientDisconnected();
}

void SingleClientProxyImpl::FlushForTesting() {
  DCHECK(message_receiver_remote_);
  message_receiver_remote_.FlushForTesting();  // IN-TEST
}

}  // namespace ash::secure_channel


text:
<?php
/**
 * @package Model
 * @internal
 */
abstract class Kwf_Model_Row_Abstract implements Kwf_Model_Row_Interface, Serializable
{
    private $_skipFilters = false; //für saveSkipFilters
    /**
     * @var Kwf_Model_Abstract
     **/
    protected $_model;
    private $_internalId;
    protected $_siblingRows;
    protected $_exprValues = array();
    private $_cleanData = array();
    static private $_internalIdCounter = 0;

    //damit im save() die childRows autom. mitgespeichert werden können
    private $_childRows = array();
    private $_isDeleted = false;
    private $_siblingRowsWhereSet = false;  //for free memory

    //public static $objectsCount;
    //public static $objectsByModel = array();
    //private $countKey;

    public function __construct(array $config)
    {
        //self::$objectsCount++;
        //$this->countKey = get_class($config['model']);
        //if ($this->countKey == 'Kwf_Model_Db') {
        //    $this->countKey = $config['model']->getTableName();
        //}
        //if (!isset(self::$objectsByModel[$this->countKey])) self::$objectsByModel[$this->countKey] = 0;
        //self::$objectsByModel[$this->countKey]++;

        if (isset($config['siblingRows'])) {
            $this->_siblingRows = (array)$config['siblingRows'];
            $this->_siblingRowsWhereSet = true;
        }

        if (isset($config['exprValues'])) {
            $this->_exprValues = (array)$config['exprValues'];
        }

        $this->_model = $config['model'];
        $this->_internalId = self::$_internalIdCounter++;

        $this->_init();

        //Kwf_Benchmark::count('Model_Row', get_class($this->_model).' '.$this->{$this->_model->getPrimaryKey()});
    }

    public function __destruct()
    {
        //self::$objectsCount--;
        //self::$objectsByModel[$this->countKey]--;
        //if (!self::$objectsByModel[$this->countKey]) unset(self::$objectsByModel[$this->countKey]);
    }

    public function serialize()
    {
        if (Kwf_Model_Abstract::getInstance(get_class($this->getModel())) !== $this->getModel()) {
            throw new Kwf_Exception("You can only serialize rows of models that where created with Kwf_Model_Abstract::getInstance()");
        }
        $data = array(
            'model' => get_class($this->getModel()),
            'siblingRows' => $this->_siblingRows
        );
        return serialize($data);
    }

    public function unserialize($str)
    {
        //self::$objectsCount++;

        $data = unserialize($str);
        $this->_siblingRows = $data['siblingRows'];
        $this->_model = Kwf_Model_Abstract::getInstance($data['model']);
        $this->_internalId = self::$_internalIdCounter++;
    }

    protected function _init()
    {
    }

    public function getInternalId()
    {
        return $this->_internalId;
    }

    public function setSiblingRows(array $rows)
    {
        $this->_siblingRowsWhereSet = true;
        $this->_siblingRows = $rows;
        return $this;
    }

    public function getSiblingRow($rule)
    {
        $rows = $this->_getSiblingRows();
        return $rows[$rule];
    }

    protected function _getSiblingRows()
    {
        if (!isset($this->_siblingRows)) {
            $this->_siblingRows = array();
            foreach ($this->_model->getSiblingModels() as $k=>$m) {
                if ($m instanceof Kwf_Model_SubModel_Interface) {
                    $r = $m->getRowBySiblingRow($this);
                } else {
                    $ref = $m->getReferenceByModelClass(get_class($this->_model), $k);
                    $r = null;
                    if ($this->{$this->_getPrimaryKey()}) {
                        $r = $m->getRow(array('equals'=>array($ref['column']=>$this->{$this->_getPrimaryKey()})));
                    }
                    if (!$r) {
                        $r = $m->createRow();
                        $r->{$ref['column']} = $this->{$this->_getPrimaryKey()};
                    }
                }
                $this->_siblingRows[$k] = $r;
            }
        }
        return $this->_siblingRows;
    }

    protected function _transformColumnName($name)
    {
        return $this->_model->transformColumnName($name);
    }

    public function __isset($name)
    {
        return $this->hasColumn($name);
    }

    public function __unset($name)
    {
        if (in_array($name, $this->_model->getExprColumns())) {
            throw new Kwf_Exception("Expr Columns are read only");
        }
        foreach ($this->_getSiblingRows() as $r) {
            if ($r->hasColumn($name)) {
                unset($r->$name);
                return;
            }
        }
        throw new Kwf_Exception("Invalid column '$name' for model '".get_class($this->getModel())."'");
    }

    public function __get($name)
    {
        if (in_array($name, $this->_model->getExprColumns())) {
            if (!array_key_exists($name, $this->_exprValues)) {
                $this->_exprValues[$name] = $this->_model->getExprValue($this, $name);
            }
            return $this->_exprValues[$name];
        }
        foreach ($this->_getSiblingRows() as $r) {
            if ($r->hasColumn($name)) {
                return $r->$name;
            }
        }
        throw new Kwf_Exception("Invalid column '$name' for model '".get_class($this->getModel())."'");
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->_model->getExprColumns())) {
            throw new Kwf_Exception("Expr Columns are read only");
        }
        if ($this->_model->getOwnColumns() && !in_array($name, $this->_model->getOwnColumns())) {
            foreach ($this->_getSiblingRows() as $r) {
                if ($r->hasColumn($name)) {
                    $r->$name = $value;
                    return;
                }
            }
            throw new Kwf_Exception("Invalid column '$name' for model '".get_class($this->getModel())."'");
        }
    }

    protected function _postSet($name, $value)
    {
        if ($name == $this->_getPrimaryKey()) {
            foreach ($this->_getSiblingRows() as $k=>$r) {
                if (!$r->getModel() instanceof Kwf_Model_SubModel_Interface) {
                    $ref = $r->getModel()->getReferenceByModelClass(get_class($this->_model), $k);
                    $r->{$ref['column']} = $value;
                }
            }
        }
    }

    /**
     * Speichert in jedem Fall, auch wenn sich keine daten geändert haben.
     */
    final public function forceSave()
    {
        $this->_setDirty($this->_getPrimaryKey());
        return $this->save();
    }

    protected function _setDirty($column)
    {
        if (!array_key_exists($column, $this->_cleanData)) {
            $this->_cleanData[$column] = $this->$column;
        }
    }

    protected function _resetDirty()
    {
        $this->_cleanData = array();
        foreach ($this->_getSiblingRows() as $r) {
            $r->_resetDirty();
        }
    }

    /**
     * Ob die Row seblst dirty ist
     */
    protected function _isDirty()
    {
        return !empty($this->_cleanData);
    }

    /**
     * Ob die Row oder eine sibling row dirty ist
     */
    public final function isDirty()
    {
        if ($this->_isDirty()) return true;
        foreach ($this->_getSiblingRows() as $r) {
            if ($r->_isDirty()) return true;
        }
        foreach ($this->_childRows as $row) {
            if ($row->isDirty()) return true;
        }
        return false;
    }

    /**
     * dirty columns der row und der sibling rows
     */
    public function getDirtyColumns()
    {
        $ret = array_keys($this->_cleanData);
        foreach ($this->_getSiblingRows() as $r) {
            $ret = array_merge($ret, $r->getDirtyColumns());
        }
        return $ret;
    }

    /**
     * Returns the original value of a column, like it exists in the data source.
     *
     * After save() it will return the new value.
     */
    public function getCleanValue($name)
    {
        if (array_key_exists($name, $this->_cleanData)) {
            return $this->_cleanData[$name];
        }
        foreach ($this->_getSiblingRows() as $r) {
            if (array_key_exists($name, $r->_cleanData)) {
                return $r->_cleanData[$name];
            }
        }
        return $this->__get($name);
    }

    /**
     * Nötig wenn man in einer Form Cards hat (jede Card mit eigener Form) und die
     * Card-Forms als Sibling gespeichert werden. Da will man dann immer nur ein
     * Sibling speichern (das von der ausgewählten Card), aber beim load() will
     * man alle Siblings dabei haben. Wenn man dann diese Funktion überschreibt
     * kann man nur ein Sibling zurückgeben und genau das wird dann beim speichern
     * verwendet und beim load() wird _getSiblingRows() direkt verwendet.
     */
    protected function _getSiblingRowsForSave()
    {
        return $this->_getSiblingRows();
    }

    //calling _resetDirty has to be done *after* all saving finished (proxies, siblings)
    //to have cleanData available in eg. _afterSave
    //TODO: investigate if it would make sense to move _afterSave also out to have it consistent across proxies&siblings
    protected function _saveWithoutResetDirty()
    {
        foreach ($this->_getSiblingRowsForSave() as $k=>$r) {
            if (!$r->getModel() instanceof Kwf_Model_SubModel_Interface) {
                $ref = $r->getModel()->getReferenceByModelClass(get_class($this->_model), $k);
                if (!$r->{$ref['column']}) {
                    $r->{$ref['column']} = $this->{$this->_getPrimaryKey()};
                }
            }
            $r->_saveWithoutResetDirty();
        }
        return null;
    }

    //override _saveWithoutResetDirty instead, or better _afterSave/_beforeSave
    public final function save()
    {
        $ret = $this->_saveWithoutResetDirty();

        $this->_resetDirty();

        return $ret;
    }

    protected function _postInsert()
    {
    }

    public function delete()
    {
    }

    public function getModel()
    {
        return $this->_model;
    }

    protected function _getPrimaryKey()
    {
        return $this->_model->getPrimaryKey();
    }

    public function countChildRows($rule, $select = array())
    {
        if ($rule instanceof Kwf_Model_Abstract) {
            $m = $rule;
            $dependentOf = $this->_model;
        } else {
            $dependent = $this->_model->getDependentModelWithDependentOf($rule);
            $m = $dependent['model'];
            $dependentOf = $dependent['dependentOf'];
        }

        if ($m instanceof Kwf_Model_RowsSubModel_Interface) {
            //could be improved
            return count($m->getRowsByParentRow($this, $select));
        } else {
            if (!$select instanceof Kwf_Model_Select) {
                $select = $m->select($select);
            } else {
                $select = clone $select; //nicht select objekt ändern
            }
            $ref = $m->getReferenceByModelClass(get_class($dependentOf), isset($dependent['rule']) ? $dependent['rule'] : null);
            if (!$this->{$this->_getPrimaryKey()}) {
                return 0;
            }
            $select->whereEquals($ref['column'], $this->{$this->_getPrimaryKey()});
            return $m->countRows($select);
        }
    }

    public function getChildRows($rule, $select = array())
    {
        if ($rule instanceof Kwf_Model_Abstract) {
            $m = $rule;
            $dependentOf = $this->_model;
        } else {
            $dependent = $this->_model->getDependentModelWithDependentOf($rule);
            $m = $dependent['model'];
            $dependentOf = $dependent['dependentOf'];
        }

        if ($m instanceof Kwf_Model_RowsSubModel_Interface) {
            $ret = $m->getRowsByParentRow($this, $select);
        } else {
            if (!$select instanceof Kwf_Model_Select) {
                $select = $m->select($select);
            } else {
                $select = clone $select; //nicht select objekt ändern
            }
            $ref = $m->getReferenceByModelClass(get_class($dependentOf), isset($dependent['rule']) ? $dependent['rule'] : null);
            if (!$this->{$this->_getPrimaryKey()}) {
                return array();
            }
            $select->whereEquals($ref['column'], $this->{$this->_getPrimaryKey()});
            $ret = $m->getRows($select);
        }
        foreach ($ret as $r) {
            if (!in_array($r, $this->_childRows, true)) $this->_childRows[] = $r;
        }
        $ret->rewind();
        return $ret;
    }

    public function createChildRow($rule, array $data = array())
    {
        if ($rule instanceof Kwf_Model_Abstract) {
            $m = $rule;
        } else {
            $m = $this->_model->getDependentModel($rule);
        }

        if ($m instanceof Kwf_Model_RowsSubModel_Interface) {
            $ret = $m->createRowByParentRow($this, $data);
        } else {
            $ret = $m->createRow($data);
            $ref = $m->getReferenceByModelClass(get_class($this->_model), null);
            $ret->{$ref['column']} = $this->{$this->_getPrimaryKey()};
        }
        $this->_childRows[] = $ret;
        return $ret;
    }

    public function getParentRow($rule)
    {
        $ref = $this->_model->getReference($rule);
        if ($ref === Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT) {
            if (!($this instanceof  Kwf_Model_RowsSubModel_Row_Interface)) {
                throw new Kwf_Exception("row '".get_class($this)."' must implement Kwf_Model_RowsSubModel_Row_Interface");
            }
            return $this->getSubModelParentRow();
        }
        if (!isset($ref['column'])) {
            throw new Kwf_Exception("column for reference '$rule' not set");
        }
        $id = $this->{$ref['column']};
        if (!$id) return null;
        if (isset($ref['refModelClass'])) {
            $refModel = Kwf_Model_Abstract::getInstance($ref['refModelClass']);
        } else if (isset($ref['refModel'])) {
            $refModel = $ref['refModel'];
        } else {
            throw new Kwf_Exception("refModel or refModelClass for reference '$rule' not set");
        }
        return $refModel->getRow($id);
    }

    public function toDebug()
    {
        $i = get_class($this);
        try {
            if (method_exists($this, '__toString')) {
                $i .= " (".$this->__toString().")\n";
            }
        } catch (Kwf_Exception $e) {}
        $ret = print_r($this->toArray(), true);
        $ret = preg_replace('#^Array#', $i, $ret);
        $ret .= "Model: ".get_class($this->getModel());
        $ret = "<pre>$ret</pre>";
        return $ret;
    }

    public function __toString()
    {
        $field = $this->getModel()->getToStringField();
        if ($field && isset($this->$field)) {
            return $this->$field;
        }
        throw new Kwf_Exception('Either override __toString() or define $_toStringField in Model '.get_class($this->getModel()).'');
    }

    /**
     * Um in Model_Field vor dem speichern den wert setzen zu können
     */
    protected function _beforeSaveSiblingMaster()
    {
        foreach ($this->_getSiblingRows() as $k=>$r) {
            $r->_beforeSaveSiblingMaster();
        }
    }

    protected function _beforeSave()
    {
        $this->_updateFilters(false);
        foreach ($this->_childRows as $row) {
            if ($row->_isDeleted) continue;
            //if (method_exists($row->getModel(), 'createRowByParentRow')) {
            if ($row->getModel() instanceof Kwf_Model_RowsSubModel_Interface) {
                //FieldRows müssen *vor* der row gespeichert werden, damit das data Feld die korrekten Werte hat
                $row->save();
            }
        }
    }

    protected function _callObserver($fn)
    {
        Kwf_Component_ModelObserver::getInstance()->add($fn, $this);
    }

    protected function _afterSave()
    {
        foreach ($this->_childRows as $row) {
            if ($row->_isDeleted) continue;
            if (!($row->getModel() instanceof Kwf_Model_RowsSubModel_Interface)) {
                if (!$row->{$row->_getPrimaryKey()}) {
                    //Tabellen Relationen müssen *nach* der row gespeichert werden,
                    //da beim hinzufügen die id noch nicht verfügbar ist
                    $ref = $row->getModel()->getReferenceByModelClass(get_class($this->_model), null);
                    $row->{$ref['column']} = $this->{$this->_getPrimaryKey()};
                }
                if ($row->isDirty()) {
                    $row->save();
                }
            }
        }
        $this->_updateFilters(true);

        $this->_callReferencedModelsRowUpdated('save');

        $this->_callObserver('save');
    }

    private function _callReferencedModelsRowUpdated($action)
    {
        $called = array();
        foreach ($this->getModel()->getDependentModels() as $depName=>$m) {
            if (!in_array($m, $called, true)) {
                $m->dependentModelRowUpdated($this, $action);
                $called[] = $m;
            }
        }

        $called = array();
        foreach ($this->getModel()->getReferences() as $refName) {
            if ($this->getModel()->getReference($refName) === Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT) {
                continue;
            }
            $m = $this->getModel()->getReferencedModel($refName);
            if (!in_array($m, $called, true)) {
                $m->childModelRowUpdated($this, $action);
                $called[] = $m;
            }
        }
    }

    protected function _beforeUpdate()
    {
    }

    protected function _afterUpdate()
    {
        $this->_callObserver('update');
        $this->_updateFilters(true);
    }

    protected function _beforeInsert()
    {
    }

    protected function _afterInsert()
    {
        $this->_callObserver('insert');
    }

    protected function _beforeDelete()
    {
        $filters = $this->getModel()->getFilters();
        foreach($filters as $k=>$f) {
            if ($f instanceof Kwf_Filter_Row_Abstract) {
                $f->onDeleteRow($this);
            }
        }
        $this->_callObserver('delete'); //before to have the data still in the row
    }

    protected function _afterDelete()
    {
        $this->_isDeleted = true;
        $this->_callReferencedModelsRowUpdated('delete');
    }

    protected function _updateFilters($filterAfterSave = false)
    {
        if ($this->_skipFilters) return; //für saveSkipFilters

        $filters = $this->getModel()->getFilters();
        foreach($filters as $k=>$f) {
            if ($f instanceof Kwf_Filter_Row_Abstract) {
                if ($f->skipFilter($this, $k)) continue;
                if ($f->filterAfterSave() != $filterAfterSave) continue;
                $this->$k = $f->filter($this);
            } else {
                $this->$k = $f->filter($this->__toString());
            }
            if ($filterAfterSave) {
                $this->_skipFilters = true;
                $this->save();
            }
        }
    }

    //Speichern und abei die Filter nicht verwenden
    //wird benötigt bei der Nummerierung um eine Endlusschleife zu verhindern
    public function saveSkipFilters()
    {
        $this->_skipFilters = true;
        $this->save();
        $this->_skipFilters = false;
    }

    public function getTable()
    {
        return $this->getModel()->getTable();
    }

    public function toArray()
    {
        $ret = array();
        foreach ($this->_getSiblingRows() as $r) {
            $ret = array_merge($ret, $r->toArray());
        }
        return $ret;
    }

    // ist momentan nur fürs duplicate.
    protected function _toArrayWithoutPrimaryKeys()
    {
        $ret = $this->toArray();
        unset($ret[$this->getModel()->getPrimaryKey()]);
        foreach ($this->_getSiblingRows() as $r) {
            $primaryKey = $r->getModel()->getPrimaryKey();
            if ($primaryKey) {
                unset($ret[$primaryKey]);
            }
        }
        return $ret;
    }

    //kopiert von model, da in row _getSiblingRows überschrieben sein kann
    public function hasColumn($col)
    {
        if (!$this->getModel()->getOwnColumns()) return true;
        if (in_array($col, $this->getModel()->getOwnColumns())) return true;
        if (in_array($col, $this->getModel()->getExprColumns())) return true;
        foreach ($this->_getSiblingRows() as $r) {
            if ($r->hasColumn($col)) return true;
        }
        return false;
    }

    /**
     * Hilfsfunktion die von duplicate aufgerufen werden kann
     */
    protected final function _duplicateDependentModel($newRow, $rule, $select = array())
    {
        $rowset = $this->getChildRows($rule, $select);
        foreach ($rowset as $row) {
            $ref = $row->getModel()->getReferenceByModelClass(get_class($this->getModel()), null);
            $data = array();
            $data[$ref['column']] = $newRow->{$this->_getPrimaryKey()};
            $row->duplicate($data);
        }
    }

    public function duplicate(array $data = array())
    {
        $data = array_merge($this->_toArrayWithoutPrimaryKeys(), $data);
        $new = $this->getModel()->createRow($data);
        $new->save();
        return $new;
    }

    /**
     * @internal
     */
    public function freeMemory()
    {
        if (!$this->_siblingRowsWhereSet) {
            $this->_siblingRows = null;
        }
        $this->_childRows = array();
    }

    public function getByColumnMapping($mapping, $column)
    {
        $c = $this->getModel()->getColumnMapping($mapping, $column);
        return $this->$c;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package weatherpony.partial.asmedit;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;

public class ProxyListing{
	static final ProxyListing instance = new ProxyListing();
	private HashMap<Data, Integer> reverse = new HashMap();
	private ArrayList<Data> direct = new ArrayList();
	private static final String base = "proxyNum";
	private ProxyListing(){

		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
			@Override
			public void run(){
				File saveFile = new File("PML_proxyList.txt");
				if(saveFile.exists())
					saveFile.delete();
				try{
					BufferedWriter out = new BufferedWriter(new FileWriter(saveFile));
					out.append("The method proxies generated last runtime by PML corresponded to methods as follows. (this is in case something crashed)");
					out.newLine();
					int size = direct.size();
					for(int cur=0;cur<size;cur++){
						out.append(base).append(Integer.toString(cur+1)).append(": ").append(direct.get(cur).toString());
						out.newLine();
					}
					out.close();
				}catch(Throwable e){
					System.err.println("PML Proxy list was unable to save to file. Printing info below instead:");
					PrintStream out = System.err;
					out.append("    The method proxies generated this runtime by PML corresponded to methods as follows. (this is in case something crashed)");
					out.println();
					int size = direct.size();
					for(int cur=0;cur<size;cur++){
						out.append("    ");
						out.append(base).append(Integer.toString(size)).append(": ").append(direct.get(cur).toString());
						out.println();
					}
				}
			}
		}));

	}
	String generateClassName(String fromClass, String method, String desc){
		Data value = new Data(fromClass, method, desc);
		if(reverse.containsValue(value))
			return base + reverse.get(value);
		int size = direct.size();

		reverse.put(value, size);
		direct.add(value);

		return base + size;
	}
	public Data getDataFromName(String name){
		if(name.startsWith(base)){
			String end = name.replaceFirst(base, "");
			try{
				return direct.get(Integer.parseInt(end));
			}catch(Exception e){

			}
		}
		return null;
	}
	public static final class Data{
		public final String clazz,method,desc;
		Data(String clazz, String method, String desc){
			this.clazz = clazz;
			this.method = method;
			this.desc = desc;
		}
		public String getMethod(){
			return (clazz+method+desc);
		}
		@Override
		public String toString(){
			return getMethod();
		}
		@Override
		public int hashCode(){
			return clazz.hashCode() + method.hashCode() + desc.hashCode();
		}
		@Override
		public boolean equals(Object comp){
			if(comp instanceof Data){
				Data comp2 = (Data)comp;
				return this.clazz.equals(comp2.clazz) && this.method.equals(comp2.method) && this.desc.equals(comp2.desc);
			}else if(comp instanceof String){
				return (clazz+method+desc).equals(comp);
			}else
				return false;
		}
	}
}


text:
require "conf/Configuration"
require "vpc/loader/Loader"
require "ec2/EC2"

require "json"
require "uri"

module Cumulus
  module VPC

    # Public: An object representing configuration for a VPC endpoint
    class EndpointConfig
      attr_reader :service_name
      attr_accessor :policy
      attr_reader :route_tables

      # Public: Constructor
      #
      # json - a hash containing the JSON configuration for the endpoint
      def initialize(json = nil)
        if !json.nil?
          @service_name = json["service-name"]
          @policy = json["policy"]
          @route_tables = json["route-tables"] || []
        end
      end

      def to_hash
        {
          "service-name" => @service_name,
          "policy" => @policy,
          "route-tables" => @route_tables.sort,
        }.reject { |k, v| v.nil? }
      end

      def populate!(aws, route_table_map)
        @service_name = aws.service_name
        @policy = aws.parsed_policy["Version"]
        @route_tables = aws.route_table_ids.map { |rt_id| route_table_map[rt_id] || rt_id }

        self
      end

      # Public: Produce an array of differences between this local configuration and the
      # configuration in AWS
      #
      # aws - the AWS resource
      #
      # Returns an array of the EndpointDiffs that were found
      def diff(aws)
        diffs = []

        # policy
        aws_policy_statements = aws.parsed_policy["Statement"]
        local_policy_statements = Loader.policy(@policy)["Statement"]
        policy_diff = EndpointDiff.policy(aws_policy_statements, local_policy_statements)

        if policy_diff
          diffs << policy_diff
        end

        # routes
        aws_rts = aws.route_table_ids.map { |rt_id| EC2::id_route_tables[rt_id] }
        aws_rt_names = aws_rts.map { |rt| rt.name || rt.route_table_id }

        rt_diff = EndpointDiff.route_tables(aws_rt_names, @route_tables)
        if rt_diff
          diffs << rt_diff
        end

        diffs
      end

    end
  end
end


text:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Evolution.Domain.Entity.SystemManage;
using Evolution.Data.Entity;

namespace Evolution.EFConfiguration.SystemManage
{
    public class UserLogOnEFConfiguration : EFConfigurationBase<UserLogOnEntity>
    {
        public override void Configure(EntityTypeBuilder<UserLogOnEntity> entity)
        {
            entity.ToTable("Sys_UserLogOn");
            base.Configure(entity);
            entity.Property(t => t.AllowEndTime).HasColumnName("F_AllowEndTime");
            entity.Property(t => t.AllowStartTime).HasColumnName("F_AllowStartTime");
            entity.Property(t => t.AnswerQuestion).HasColumnName("F_AnswerQuestion");
            entity.Property(t => t.ChangePasswordDate).HasColumnName("F_ChangePasswordDate");
            entity.Property(t => t.CheckIPAddress).HasColumnName("F_CheckIPAddress");
            entity.Property(t => t.FirstVisitTime).HasColumnName("F_FirstVisitTime");
            entity.Property(t => t.Language).HasColumnName("F_Language");
            entity.Property(t => t.LastVisitTime).HasColumnName("F_LastVisitTime");
            entity.Property(t => t.LockEndDate).HasColumnName("F_LockEndDate");
            entity.Property(t => t.LockStartDate).HasColumnName("F_LockStartDate");
            entity.Property(t => t.LogOnCount).HasColumnName("F_LogOnCount");
            entity.Property(t => t.MultiUserLogin).HasColumnName("F_MultiUserLogin");
            entity.Property(t => t.PreviousVisitTime).HasColumnName("F_PreviousVisitTime");
            entity.Property(t => t.Question).HasColumnName("F_Question");
            entity.Property(t => t.Theme).HasColumnName("F_Theme");
            entity.Property(t => t.UserId).HasColumnName("F_UserId");
            entity.Property(t => t.UserOnLine).HasColumnName("F_UserOnLine");
            entity.Property(t => t.UserPassword).HasColumnName("F_UserPassword");
            entity.Property(t => t.UserSecretkey).HasColumnName("F_UserSecretkey");
            entity.Property(t => t.TenantId).HasColumnName("F_TenantId");
        }

    }
}


text:
package scala.meta
package internal
package quasiquotes.tokens

import org.scalameta.convert._
import scala.reflect.macros.whitebox.Context
import scala.meta.syntactic.TokenLiftables
import scala.meta.internal.dialects.InstantiateDialect
import scala.meta.syntactic.{Token, Tokens, Input}
import scala.meta.syntactic.{Token => MetaToken}

/**
 * Object used to extract the underlying code for each token.
 * Two tokens are considered equal (in pattern matching) if they both come from the same code.
 */
object TokenExtractor {
  def unapply(t: Token) = Some(t.code)
}

class ReificationMacros(val c: Context) extends TokenLiftables
                                           with InstantiateDialect {

  import c.universe._
  val XtensionQuasiquoteTerm = "shadow scala.meta quasiquotes"

  def apply(args: c.Tree*)(dialect: c.Tree): c.Tree = expand
  def unapply(scrutinee: c.Tree)(dialect: c.Tree): c.Tree = expand

  // Extract the interesting parts of toks"..."
  private lazy val q"$_($_.apply(..${parts: List[String]})).$_.$method[..$_](..$args)($dialectTree)" = c.macroApplication

  private val quasiquotePrefix = c.freshName("quasiquote")
  private def bindingName(i: Int) = TermName(quasiquotePrefix + "$x$" + i)

  private def arg(i: Int): c.Tree = method match {
    case TermName("apply") =>
      args(i)

    case TermName("unapply") =>
      val name = bindingName(i)
      pq"$name @ _"
  }

  implicit class XtensionInputLike[T](inputLike: T) {
    def tokens(implicit convert: Convert[T, Input], dialect: Dialect): Tokens = convert(inputLike).tokens
  }

  /**
   * Gets the tokens for each part of the input, and glue them together in a single `Tokens`
   * by inserting special `Token.Unquote` tokens between them.
   * The tree of the Unquote token is a scala.meta tree that represents the index of the
   * argument.
   */
  private lazy val toks: Tokens = {
    implicit val dialect: Dialect = scala.meta.dialects.Quasiquote(instantiateDialect(dialectTree))

    /** Removes the heading BOF and trailing EOF from a sequence of tokens */
    def trim(toks: Tokens): Tokens = toks match {
      case (_: MetaToken.BOF) +: toks :+ (_: MetaToken.EOF) => Tokens(toks: _*)
      case _                                                => toks
    }

    val result =
      parts.init.zipWithIndex.flatMap {
        case (part, i) =>
          // TODO: Ugh, creating synthetic inputs with semi-meaningless text just to satisfy the framework.
          // This really shows the need in virtual tokens...
          val argAsString = arg(i).toString
          trim(part.tokens) :+ MetaToken.Unquote(Input.String(argAsString), dialect, 0, argAsString.length - 1, arg(i))
      } ++ trim(parts.last.tokens)

    Tokens(result: _*)
  }

  def expand: c.Tree = {
    method match {
      case TermName("apply") =>
        q"$toks"

      case TermName("unapply") =>
        def countEllipsisUnquote(toks: Seq[Token]): Int = toks match {
          case (_: MetaToken.Ellipsis) +: (_: MetaToken.Unquote) +: rest =>
            1 + countEllipsisUnquote(rest)
          case other +: rest =>
            countEllipsisUnquote(rest)
          case _ =>
            0
        }

        if (countEllipsisUnquote(toks) > 1) {
          c.abort(c.macroApplication.pos, "cannot use splicing more than once per quasiquote")
        }

        def patternForToken(t: Token) = t match {
          case t: MetaToken.Unquote => pq"${t.tree.asInstanceOf[c.Tree]}"
          case t                    => pq"_root_.scala.meta.internal.quasiquotes.tokens.TokenExtractor(${t.code})"
        }

        // Split the input in three parts: (before, ..unquote, after).
        // Since `Tokens` is a`Seq`, we will be able to deconstruct an instance of
        // `Tokens` using before +: ..unquote :+ after.
        val splitted = {
          def split(toks: Seq[Token]): (Tokens, Option[Token], Tokens) = toks match {
            case (_: MetaToken.Ellipsis) +: (u: MetaToken.Unquote) +: rest =>
              (Tokens(), Some(u), Tokens(rest: _*))

            case t +: rest =>
              val (before, middle, after) = split(rest)
              (t +: before, middle, after)

            case Seq() =>
              (Tokens(), None, Tokens())
          }

          split(toks)
        }

        val pattern =
          splitted match {
            // corresponds to `case toks"..$foo" => ...`
            case (Tokens(), Some(middle), Tokens()) =>
              patternForToken(middle)

            // corresponds to `case toks"foo $bar baz" => ...`
            case (before, None, _) =>
              val subPatterns = before map patternForToken
              q"_root_.scala.meta.syntactic.Tokens(..$subPatterns)"

            // corresponds to `case toks"foo $bar ..$baz" => ...`
            case (before, Some(middle), Tokens()) =>
              val beforePatterns = before map patternForToken
              (beforePatterns foldRight patternForToken(middle)) {
                case (pat, acc) => pq"$pat +: $acc"
              }

            // corresponds to `case toks"foo $bar ..$baz $quux blah"
            case (before, Some(middle), after) =>
              val beforePatterns = before map patternForToken
              val afterPatterns  = after map patternForToken

              val withBeforePatterns = (beforePatterns foldRight patternForToken(middle)) {
                case (pat, acc) => pq"$pat +: $acc"
              }

              (afterPatterns foldLeft withBeforePatterns) {
                case (acc, pat) => pq"$acc :+ $pat"
              }
          }

        // Find the number of the (unique) Unquote token that is preceded by an Ellipsis
        // We use this information to wrap the value matched in `Tokens()` (otherwise we
        // would get a Token.Projected[Token])
        val dottedUnquote =
          splitted match {
            case (before, Some(_), _) => before count (_.isInstanceOf[MetaToken.Unquote])
            case _ => -1
          }

        val (thenp, elsep) =
          if (parts.size == 1) (q"true", q"false")
          else {
            val bindings = parts.init.zipWithIndex map {
              case (_, i) =>
                val name = bindingName(i)
                if (i == dottedUnquote) q"_root_.scala.meta.syntactic.Tokens($name: _*)"
                else q"$name"
            }
            (q"_root_.scala.Some(..$bindings)", q"_root_.scala.None")
          }

        // If our pattern is simply toks"..$foo", we don't emit a default case
        // to avoid generating a warning during the compilation of the expansion.
        val cases =
          if (parts.size == 2 && dottedUnquote == 0)
            q"""in match { case $pattern => $thenp }"""
          else
            q"""in match {
                  case $pattern => $thenp
                  case _        => $elsep
                }"""

        q"""
          new {
            def unapply(in: _root_.scala.meta.Tokens) = $cases
          }.unapply(..$args)
        """
    }
  }
}


text:
package org.kuali.kfs.pdp.businessobject.lookup;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.fp.businessobject.DisbursementPayee;
import org.kuali.kfs.fp.businessobject.lookup.AbstractPayeeLookupableHelperServiceImpl;
import org.kuali.kfs.pdp.PdpConstants;
import org.kuali.kfs.pdp.PdpKeyConstants;
import org.kuali.kfs.pdp.businessobject.ACHPayee;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.vnd.businessobject.VendorDetail;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kim.impl.KIMPropertyConstants;
import org.kuali.rice.kns.web.ui.ResultRow;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.exception.ValidationException;
import org.kuali.rice.krad.lookup.CollectionIncomplete;
import org.kuali.rice.krad.util.BeanPropertyComparator;
import org.kuali.rice.krad.util.GlobalVariables;

/**
 * Payee lookupable for PDP Payee ACH. Builds off of DV Payee lookup by taking off payment reason code, and adding adding entity id
 * to search and return url
 */
public class ACHPayeeLookupableHelperServiceImpl extends AbstractPayeeLookupableHelperServiceImpl {

    /**
     * @see org.kuali.kfs.fp.businessobject.lookup.DisbursementPayeeLookupableHelperServiceImpl#getSearchResults(java.util.Map)
     *
     * KRAD Conversion: Lookupable performs customization of the search results and performs a sort
     * by retrieving the default sort columns using data dictionary service..
     *
     * Uses data dictionary.
     */
    @Override
    public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {
        List<DisbursementPayee> searchResults = new ArrayList<DisbursementPayee>();

        String payeeTypeCode = fieldValues.get(KFSPropertyConstants.PAYEE_TYPE_CODE);
        if (StringUtils.isBlank(payeeTypeCode)) {
            GlobalVariables.getMessageMap().putInfo(KFSPropertyConstants.PAYEE_TYPE_CODE, PdpKeyConstants.MESSAGE_PDP_ACH_PAYEE_LOOKUP_NO_PAYEE_TYPE);
        }

        if (StringUtils.isNotBlank(fieldValues.get(KFSPropertyConstants.VENDOR_NUMBER)) || StringUtils.isNotBlank(fieldValues.get(KFSPropertyConstants.VENDOR_NAME)) || (StringUtils.isNotBlank(payeeTypeCode) && PdpConstants.PayeeIdTypeCodes.VENDOR_ID.equals(payeeTypeCode))) {
            searchResults.addAll(this.getVendorsAsPayees(fieldValues));
        }
        else if (StringUtils.isNotBlank(fieldValues.get(KIMPropertyConstants.Person.EMPLOYEE_ID)) || StringUtils.isNotBlank(fieldValues.get(KIMPropertyConstants.Person.ENTITY_ID)) || (StringUtils.isNotBlank(payeeTypeCode) && (PdpConstants.PayeeIdTypeCodes.EMPLOYEE.equals(payeeTypeCode) || PdpConstants.PayeeIdTypeCodes.ENTITY.equals(payeeTypeCode)))) {
            searchResults.addAll(this.getPersonAsPayees(fieldValues));
        }
        else {
            searchResults.addAll(this.getVendorsAsPayees(fieldValues));
            searchResults.addAll(this.getPersonAsPayees(fieldValues));
        }

        CollectionIncomplete results = new CollectionIncomplete(searchResults, Long.valueOf(searchResults.size()));

        // sort list if default sort column given
        List<String> defaultSortColumns = getDefaultSortColumns();
        if (defaultSortColumns.size() > 0) {
            Collections.sort(results, new BeanPropertyComparator(getDefaultSortColumns(), true));
        }

        return results;
    }

    /**
     * Override to set entity id as the payee id and set the pdp payee type
     *
     * @see org.kuali.kfs.fp.businessobject.lookup.DisbursementPayeeLookupableHelperServiceImpl#getPayeeFromPerson(org.kuali.rice.kim.api.identity.Person,
     *      java.util.Map)
     */
    @Override
    protected DisbursementPayee getPayeeFromPerson(Person personDetail, Map<String, String> fieldValues) {
        DisbursementPayee payee = super.getPayeeFromPerson(personDetail, fieldValues);

        String payeeTypeCode = fieldValues.get(KFSPropertyConstants.PAYEE_TYPE_CODE);

        ACHPayee achPayee = new ACHPayee();

        if (PdpConstants.PayeeIdTypeCodes.ENTITY.equals(payeeTypeCode)) {
            achPayee.setPayeeIdNumber(personDetail.getEntityId());
            achPayee.setPayeeTypeCode(PdpConstants.PayeeIdTypeCodes.ENTITY);
        }
        else {
            achPayee.setPayeeIdNumber(personDetail.getEmployeeId());
            achPayee.setPayeeTypeCode(PdpConstants.PayeeIdTypeCodes.EMPLOYEE);
        }

        achPayee.setPayeeName(payee.getPayeeName());
        achPayee.setPrincipalId(payee.getPrincipalId());
        achPayee.setTaxNumber(payee.getTaxNumber());
        achPayee.setAddress(payee.getAddress());
        achPayee.setActive(payee.isActive());

        return achPayee;
    }

    /**
     * @see org.kuali.kfs.fp.businessobject.lookup.DisbursementPayeeLookupableHelperServiceImpl#getPayeeFromVendor(org.kuali.kfs.vnd.businessobject.VendorDetail,
     *      java.util.Map)
     */
    @Override
    protected DisbursementPayee getPayeeFromVendor(VendorDetail vendorDetail, Map<String, String> fieldValues) {
        DisbursementPayee payee = super.getPayeeFromVendor(vendorDetail, fieldValues);

        ACHPayee achPayee = new ACHPayee();

        achPayee.setPayeeIdNumber(payee.getPayeeIdNumber());
        achPayee.setPayeeTypeCode(PdpConstants.PayeeIdTypeCodes.VENDOR_ID);
        achPayee.setPayeeName(payee.getPayeeName());
        achPayee.setPrincipalId(payee.getPrincipalId());
        achPayee.setTaxNumber(payee.getTaxNumber());
        achPayee.setAddress(payee.getAddress());
        achPayee.setActive(payee.isActive());

        return achPayee;
    }

    /**
     * @see org.kuali.kfs.fp.businessobject.lookup.DisbursementPayeeLookupableHelperServiceImpl#validateSearchParameters(java.util.Map)
     */
    @Override
    public void validateSearchParameters(Map fieldValues) {
        super.validateSearchParameters(fieldValues);

        String vendorName = (String) fieldValues.get(KFSPropertyConstants.VENDOR_NAME);
        String vendorNumber = (String) fieldValues.get(KFSPropertyConstants.VENDOR_NUMBER);
        String employeeId = (String) fieldValues.get(KIMPropertyConstants.Person.EMPLOYEE_ID);
        String entityId = (String) fieldValues.get(KIMPropertyConstants.Person.ENTITY_ID);
        String payeeTypeCode = (String) fieldValues.get(KFSPropertyConstants.PAYEE_TYPE_CODE);

        // only can use the vendor name and vendor number fields or the employee id field, but not both.
        boolean isVendorInfoEntered = StringUtils.isNotBlank(vendorName) || StringUtils.isNotBlank(vendorNumber);
        if (StringUtils.isNotBlank(entityId) && isVendorInfoEntered) {
            String messageKey = KFSKeyConstants.ERROR_DV_VENDOR_EMPLOYEE_CONFUSION;

            String vendorNameLabel = this.getAttributeLabel(KFSPropertyConstants.VENDOR_NAME);
            String vendorNumberLabel = this.getAttributeLabel(KFSPropertyConstants.VENDOR_NUMBER);
            String entityIdLabel = this.getAttributeLabel(KIMPropertyConstants.Person.ENTITY_ID);

            GlobalVariables.getMessageMap().putError(KIMPropertyConstants.Person.ENTITY_ID, messageKey, entityIdLabel, vendorNameLabel, vendorNumberLabel);
        }

        boolean isEmployeeInfoEntered = StringUtils.isNotBlank(employeeId) || StringUtils.isNotBlank(entityId);
        boolean payeeTypeEntered = StringUtils.isNotBlank(payeeTypeCode);

        if (payeeTypeEntered && PdpConstants.PayeeIdTypeCodes.VENDOR_ID.equals(payeeTypeCode) && isEmployeeInfoEntered) {
            String messageKey = PdpKeyConstants.ERROR_PAYEE_LOOKUP_VENDOR_EMPLOYEE_CONFUSION;

            String employeeIdLabel = this.getAttributeLabel(KIMPropertyConstants.Person.EMPLOYEE_ID);
            String entityIdLabel = this.getAttributeLabel(KIMPropertyConstants.Person.ENTITY_ID);
            String payeeTypeLabel = this.getAttributeLabel(KFSPropertyConstants.PAYEE_TYPE_CODE);

            GlobalVariables.getMessageMap().putError(KFSPropertyConstants.PAYEE_TYPE_CODE, messageKey, payeeTypeLabel, payeeTypeCode, employeeIdLabel, entityIdLabel);
        }
        else if (payeeTypeEntered && (PdpConstants.PayeeIdTypeCodes.EMPLOYEE.equals(payeeTypeCode) || PdpConstants.PayeeIdTypeCodes.ENTITY.equals(payeeTypeCode)) && isVendorInfoEntered) {
            String messageKey = PdpKeyConstants.ERROR_PAYEE_LOOKUP_VENDOR_EMPLOYEE_CONFUSION;

            String vendorNameLabel = this.getAttributeLabel(KFSPropertyConstants.VENDOR_NAME);
            String vendorNumberLabel = this.getAttributeLabel(KFSPropertyConstants.VENDOR_NUMBER);
            String payeeTypeLabel = this.getAttributeLabel(KFSPropertyConstants.PAYEE_TYPE_CODE);

            GlobalVariables.getMessageMap().putError(KFSPropertyConstants.PAYEE_TYPE_CODE, messageKey, payeeTypeLabel, payeeTypeCode, vendorNameLabel, vendorNumberLabel);
        }

        if (GlobalVariables.getMessageMap().hasErrors()) {
            throw new ValidationException("errors in search criteria");
        }
    }
    /**
        * Override to not filter rows based on payment reason
        *
         * @see org.kuali.kfs.fp.businessobject.lookup.DisbursementPayeeLookupableHelperServiceImpl#filterReturnUrl(java.util.List,
         *      java.util.List, java.lang.String)
         *
         * KRAD Conversion: Performs customization of the result list of rows.
         *
         * No use of data dictionary
         */
        @Override

        protected void filterReturnUrl(List<ResultRow> resultRowList, List<DisbursementPayee> payeeList, String paymentReasonCode) {
        }
}


text:
name "haproxy"
default_version "1.6.4"

dependency "zlib"
dependency "pcre"
dependency "openssl"

license "GPLv2"
license_file "LICENSE"

# HTTPS is available but certificate validation fails on OS X
source url: "http://www.haproxy.org/download/1.6/src/haproxy-#{version}.tar.gz",
       sha256: "e5fa3c604f1fe9ecb6974ccda6705c105ebee14b3a913069fb08f00e860cd230"

relative_path "haproxy-#{version}"

build do
  env = with_standard_compiler_flags(with_embedded_path)
  #
  # Many of these are the same environment variables that debian sets
  # PREFIX and TARGET are mandatory to get it building under omnibus.
  #
  build_options = {
   "PREFIX" => "#{install_dir}/embedded",
   # Use libpcre for regex, libpcre > 8.32 required
   # for JIT
   "USE_PCRE" => "1",
   "USE_PCRE_JIT" => "1",
   "USE_ZLIB" => "1",
   "USE_OPENSSL" => "1",
  }
  # Required to resolve hostnames to IPv6 addresses
  # off-by-default because of prolems on older glibc's
  # TODO(ssd): Should we turn this off on RHEL5?
  build_options['USE_GETADDRINFO'] = "1"
  if intel?
    build_options["USE_REGPARM"] = "1"
  end
  build_options['TARGET'] = if ohai["kernel"] && ohai["kernel"]["name"] == "Linux"
                              version = Gem::Version.new(String(ohai["kernel"]["release"]).split("-").first)
                              case
                              when version >= Gem::Version.new("2.6.28")
                                "linux2628"
                              when version >= Gem::Version.new("2.6")
                                "linux26"
                              else
                                "linux24e"
                              end
                            else
                              "generic"
                            end
  build_args = ""
  build_options.each { |k,v| build_args << " #{k}=#{v}"}
  make "haproxy #{build_args}", env: env
  make "install #{build_args}", env: env
end


text:
#include "Log.h"

#include <memory>
#include <string>

namespace i2p {
namespace util {
namespace log {

static std::shared_ptr<Log> g_Log = nullptr;
sink_ptr g_LogSink;

//
// LogStreamImpl <- LogStream
//
LogStreamImpl::LogStreamImpl(
    std::mutex& mtx,
    log_t& l,
    LogLevel level)
    : m_Str(new std::stringbuf),
      m_Access(mtx),
      m_Log(l),
      m_Level(level),
      m_Enable(true) {
      // m_Log.add_global_attribute("Logger", m_ParentName);
}

LogStreamImpl::~LogStreamImpl() {
  delete m_Str;
}

void LogStreamImpl::WaitForReady() {
  {
    std::lock_guard<std::mutex> lock(m_Access);
  }
}

LogStreamImpl::int_type LogStreamImpl::overflow(
    int_type ch) {
  return std::streambuf::overflow(ch);
}

int LogStreamImpl::sync() {
  int ret = 0;
  ret = m_Str->pubsync();
  Flush();
  m_Access.unlock();
  return ret;
}

// not thread safe
std::streamsize LogStreamImpl::xsputn(
    const LogStreamImpl::char_type* s,
    std::streamsize count) {
  return m_Str->sputn(s, count);
}

// not thread safe
void LogStreamImpl::Flush() {
  if (g_Log->Silent()) {
    // don't log if we are silent
    return;
  }
  BOOST_LOG_SEV(m_Log, m_Level) << m_Str;
  delete m_Str;
  m_Str = new std::stringbuf;
  g_LogSink->flush();
}

//
// LogStream
//
LogStream::LogStream(
    LogStreamImpl* impl)
    : std::ostream(impl),
      m_Impl(impl) {}

LogStream::~LogStream() {
  delete m_Impl;
}

LogStream& LogStream::Flush() {
  g_LogSink->flush();
  return *this;
}

bool LogStream::IsEnabled() {
  return m_Impl->IsEnabled();
}

void LogStream::Disable() {
  m_Impl->Disable();
}

void LogStream::Enable() {
  m_Impl->Enable();
}

/**
 * TODO(unassigned): implement
 * LogStream& LogStream::Meta(
 *     const std::string& key,
 *     std::string value) {
 *   //TODO(unassigned): this doesn't do anything yet
 *   m_Impl->MetaImpl(key, value);
 *   return *this;
 * }
*/

//
// LoggerImpl <- Logger
//
LoggerImpl::LoggerImpl(
    const std::string& name,
    const std::string& channel)
    : log(boost::log::keywords::channel = channel),
      m_Debug(new LogStreamImpl(m_DebugMtx, log, eLogDebug)),
      m_Info(new LogStreamImpl(m_InfoMtx, log, eLogInfo)),
      m_Warn(new LogStreamImpl(m_WarnMtx, log, eLogWarning)),
      m_Error(new LogStreamImpl(m_ErrorMtx, log, eLogError)) {
  log.add_attribute(
      "LogName",
      boost::log::attributes::constant< std::string >(name));
}

LoggerImpl::LoggerImpl()
    : LoggerImpl("default", "default") {}

LogStream& LoggerImpl::Debug() {
  return GetLogger(m_Debug, m_DebugMtx);
}

LogStream& LoggerImpl::Info() {
  return GetLogger(m_Info, m_InfoMtx);
}

LogStream& LoggerImpl::Warning() {
  return GetLogger(m_Warn, m_WarnMtx);
}

LogStream& LoggerImpl::Error() {
  return GetLogger(m_Error, m_ErrorMtx);
}

LogStream& LoggerImpl::GetLogger(
    LogStream& l,
    std::mutex & mtx) {
  mtx.lock();
  return l;
}

//
// Logger
//
Logger::Logger(
    LoggerImpl* impl)
    : m_Impl(impl) {}

Logger::~Logger() {
  delete m_Impl;
}

LogStream& Logger::Error() {
  return m_Impl->Error();
}

LogStream& Logger::Warning() {
  return m_Impl->Warning();
}

LogStream& Logger::Info() {
  return m_Impl->Info();
}

LogStream& Logger::Debug() {
  return m_Impl->Debug();
}

void Logger::Flush() {
  g_LogSink->flush();
}

//
// LogImpl <- Log
//
LogImpl::LogImpl(
    LogLevel minlev,
    std::ostream* out) {
  m_Silent = false;
  m_LogCore = boost::log::core::get();
  m_LogBackend = boost::make_shared<backend_t>();
  m_LogBackend->add_stream(
      boost::shared_ptr<std::ostream>(
          out,
          boost::null_deleter()));
  g_LogSink = boost::shared_ptr<sink_t>(
      new sink_t(
          m_LogBackend));
  g_LogSink->set_filter(
      boost::log::expressions::attr<LogLevel>(
          "Severity") >= minlev);
  g_LogSink->set_formatter(&LogImpl::Format);
  m_LogCore->add_sink(g_LogSink);
  m_LogCore->add_global_attribute(
      "Timestamp",
      boost::log::attributes::local_clock());
}

void LogImpl::Format(
    boost::log::record_view const& rec,
    boost::log::formatting_ostream &s) {
  // const boost::log::attribute_value_set& attrs = rec.attribute_values();
  static std::locale loc(
      std::clog.getloc(),
      new boost::posix_time::time_facet("%Y:%m:%d|%T.%f"));
  std::stringstream ss;
  ss.imbue(loc);
  ss << boost::log::extract<boost::posix_time::ptime>("Timestamp", rec) << ' ';
  s << ss.str();
  s << boost::log::extract<std::string>("Channel", rec) << ":";
  s << boost::log::extract<std::string>("LogName", rec) << "\t\t";
  s << boost::log::extract<LogLevel>("Severity", rec) << "\t\t";
  s << rec[boost::log::expressions::smessage];
}

void LogImpl::Flush() {
  g_LogSink->flush();
}

void LogImpl::Stop() {
  m_Silent = true;
}

bool LogImpl::IsSilent() {
  return m_Silent;
}

//
// Log
//
Log::Log(
    LogLevel minlev,
    std::ostream* out) {
  m_LogImpl = std::make_shared<LogImpl>(minlev, out);
  m_DefaultLogger = std::make_shared<Logger>(new LoggerImpl);
}

std::shared_ptr<Log> Log::Get() {
  // make default logger if we don't have a logger
  if (g_Log == nullptr)
    g_Log = std::make_shared<Log>(eLogDebug, &std::clog);
  return g_Log;
}

std::shared_ptr<Logger> Log::Default() {
  return m_DefaultLogger;
}

std::unique_ptr<Logger> Log::New(
    const std::string& name,
    const std::string& channel) {
  return std::unique_ptr<Logger>(
      new Logger(
          new LoggerImpl(
              name,
              channel)));
}

void Log::Stop() {
  m_LogImpl->Stop();
}

bool Log::Silent() {
  return m_LogImpl->IsSilent();
}

std::ostream& operator<<(
    std::ostream& out,
    LogLevel lev) {
  static const char* levels[] = {
    "DBG",  // debug
    "NFO",  // info
    "WRN",  // warning
    "ERR"   // error
  };
  if (static_cast<std::size_t>(lev) < sizeof(levels) / sizeof(*levels)) {
    out << levels[lev];
  } else {
    out << "?" << static_cast<int>(lev) << "?";
  }
  return out;
}

}  // namespace log
}  // namespace util
}  // namespace i2p

//
// Deprecated
//
void DeprecatedStartLog(
    const std::string& fullFilePath) {
  std::cerr << "Not opening log file: " << fullFilePath << std::endl;
}

void DeprecatedStartLog(
    std::ostream* s) {
  *s << "Deprecated Logging not implemented" << std::endl;
}

void DeprecatedStopLog() {}


text:
'use strict';
var util         = require('util');
var _            = require('lodash');
var EventEmitter = require('events').EventEmitter;
var debug        = require('debug')('meshblu-arduino:index');
var Kryten = require('kryten');
var BLESerialPort = require('ble-serial').SerialPort;
var Firmata = require('firmata').Board;
var kryten = new Kryten({
    io: new Firmata(new BLESerialPort({}))
  });
var defaultSchema = require('./schema.json')
var prev = {};
var FORMSCHEMA = ["*"];
var testOptions = defaultSchema.testOptions;

function Plugin(){
  this.options = testOptions;
  this.messageSchema = defaultSchema.MESSAGE_SCHEMA;
  this.optionsSchema = defaultSchema.OPTIONS_SCHEMA;
  return this;
}
util.inherits(Plugin, EventEmitter);

Plugin.prototype.update = function(properties){
  var self = this;
  self.emit('update', properties);
};

Plugin.prototype.startKryten = function () {
  var self = this;
  self.emit('update', {});

  kryten.on('ready', function(){
    kryten.on('schema', function(schema) {
      Plugin.prototype.update({
        "messageSchema": schema.MESSAGE_SCHEMA,
        "messageFormSchema": schema.FORMSCHEMA,
        "optionsSchema": defaultSchema.OPTIONS_SCHEMA,
        "optionsForm": defaultSchema.OPTIONS_FORM
      });
    });

    kryten.on('data', function(data){
      self.emit('message', {
        "devices": "*",
        "payload": data
      })
    });
  });
};

Plugin.prototype.startKryten();

Plugin.prototype.onMessage = function(message){
  kryten.onMessage(message);
};

Plugin.prototype.setOptions = function(device){
  var self = this;
  self.options = device.options || testOptions;
  if(!_.isEqual(self.options, prev)){
    kryten.configure(self.options);
    prev = self.options;
  }
};

Plugin.prototype.onConfig = function(device){
  var self = this;
  self.setOptions(device);
};

module.exports = {
  messageSchema: defaultSchema.MESSAGE_SCHEMA,
  optionsSchema: defaultSchema.OPTIONS_SCHEMA,
  options: testOptions,
  Plugin: Plugin
};


text:
angular.module('oauth2-provider', ['http-auth-interceptor', 'oauth2-service'])

.config(function(authServiceProvider) {
  authServiceProvider.clientId = "the_client";
  authServiceProvider.secret = "";
  authServiceProvider.providerUrl = "/oauth2-provider/oauth";
})

.run(function($rootScope, authService, authInterceptor) {
  $rootScope.$on('event:auth-login-required', function() {
    authService.refresh().then(null, function() { console.log("failed"); });
  });
})

.controller('LoginCtrl', function($scope, authService) {
  $scope.user = {
    login: function() {
      authService.login($scope.user.username, $scope.user.password);
    },
    isLogged: authService.isLogged
  }
})

.controller('ResourceCtrl', function($scope, $http) {
  $scope.update = function(index) {
    $http.get("rest/resource")
      .success(function(data) {
        $scope['resources' + index] = data;
      }).error(function(data) {
        console.log(data);
      });
  }
  $scope.updateAll = function() {
  	for (var i = 1; i < 4; i++) {
  	  $scope.update(i);
  	}
  }
})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 56(3-4): 429 (1993)

#### Original name
Ramularia deusta var. alba U. Braun

### Remarks
null


text:
from factory import ParserFactory
from parsers import NcaafParser


text:
/************************** CHANGES *************************************
0.0.1       06.09.2010      FPT Team      Initial Version
0.1.0       06.11.2010      FPT Team      Finalize to 0.1.0
0.1.3       09.16.2010      FPT Team      Updated to support little endian
0.2.0       09.27.2010      FPT Team      Finalize to 0.2.0
0.2.1       01.28.2011      FPT Team      Updated the preprocesor
                                          condition to enter Debug state
0.2.2       02.21.2011      FPT Team      Removed endianness condition
                                          preprocessor
0.2.3       09.15.2011      FPT Team      Update to support K70
0.2.4       11.15.2011      FPT Team      Update to support FTFx_KX_1024K_0K_16K_4K_0K
                                          derivative.
0.2.5       12.27.2011      FPT Team      Update to support more Kinetis derivatives.
*************************************************************************/
/* include the header files */
#include "SSD_Types.h"
#include "SSD_FTFx.h"
#include "SSD_FTFx_Internal.h"

/************************************************************************
*
*  Function Name    : FlashProgramOnce.c
*  Description      : Program data into a dedicated 64 bytes region in
*                     the P-Flash IFR which stores critical information
*                     for the user
*  Arguments        : PFLASH_SSD_CONFIG, UINT8*, pFLASHCOMMANDSEQUENCE
*  Return Value     : UINT32
*
*************************************************************************/

UINT32 FlashProgramOnce(PFLASH_SSD_CONFIG PSSDConfig, \
                                   UINT8* pDataArray, \
                                   pFLASHCOMMANDSEQUENCE FlashCommandSequence)
{
    UINT8  counter;          /* outer loop counter */
#if ((FTFx_KX_512K_512K_16K_4K_4K == FLASH_DERIVATIVE) || (FTFx_KX_1024K_0K_16K_4K_0K == FLASH_DERIVATIVE)) //Added by ARM
    UINT8  pCommandArray[12];/* command sequence array */
#else
    UINT8  pCommandArray[8]; /* command sequence array */
#endif
    UINT32 returnCode;       /* return code variable */
    UINT8 i;                 /* variable to store record number index */

    /* set the default return code as FTFx_OK */
    returnCode = FTFx_OK;
    /* set the counter value for 0 */
    counter = 0;
    /* calculate record number index */
    i = (64 / (RDONCE_INDEX_MAX + 1));

    /* preparing passing parameter for program once command */
    /* 1st element for the FCCOB register */
    pCommandArray[0] = FTFx_PROGRAM_ONCE;

    while (counter <= RDONCE_INDEX_MAX)
    {
        /* preparing the rest of the parameters to be passed for the FCCOB registers */
        pCommandArray[1] = counter;
        pCommandArray[2] = 0x00;
        pCommandArray[3] = 0x00;
        pCommandArray[4] = pDataArray[counter*i];
        pCommandArray[5] = pDataArray[counter*i + 1];
        pCommandArray[6] = pDataArray[counter*i + 2];
        pCommandArray[7] = pDataArray[counter*i + 3];
#if ((FTFx_KX_512K_512K_16K_4K_4K == FLASH_DERIVATIVE) || (FTFx_KX_1024K_0K_16K_4K_0K == FLASH_DERIVATIVE))
        pCommandArray[8] = pDataArray[counter*i + 4];
        pCommandArray[9] = pDataArray[counter*i + 5];
        pCommandArray[10] = pDataArray[counter*i + 6];
        pCommandArray[11] = pDataArray[counter*i + 7];
#endif

        /* calling flash command sequence API to execute the command */
        returnCode = FlashCommandSequence(PSSDConfig, i + 3, pCommandArray);

        /* checking for the success of command execution */
        if(FTFx_OK != returnCode)
        {
            break;
        }
        else
        {
            /* do nothing */
        }
        /* decrement the counter value */
        counter++;
    }

    /* Enter Debug state if enabled */
    if (TRUE == (PSSDConfig->DebugEnable))
    {
#if ((CPU_CORE == ARM_CM4) && (COMPILER == IAR))    /* Kx Products */
        asm
        (
            " BKPT #0 \n "           /* enter Debug state */
        );
#endif
    }

    return(returnCode);
}
/* end of file */


text:
package azblob_test

import (
	"context"

	"github.com/Azure/azure-storage-blob-go/2016-05-31/azblob"
	chk "gopkg.in/check.v1" // go get gopkg.in/check.v1
)

type AppendBlobURLSuite struct{}

var _ = chk.Suite(&AppendBlobURLSuite{})

func (b *AppendBlobURLSuite) TestAppendBlock(c *chk.C) {
	bsu := getBSU()
	container, _ := createNewContainer(c, bsu)
	defer delContainer(c, container)

	blob := container.NewAppendBlobURL(generateBlobName())

	resp, err := blob.Create(context.Background(), azblob.BlobHTTPHeaders{}, nil, azblob.BlobAccessConditions{})
	c.Assert(err, chk.IsNil)
	c.Assert(resp.StatusCode(), chk.Equals, 201)

	appendResp, err := blob.AppendBlock(context.Background(), getReaderToRandomBytes(1024), azblob.BlobAccessConditions{})
	c.Assert(err, chk.IsNil)
	c.Assert(appendResp.Response().StatusCode, chk.Equals, 201)
	c.Assert(appendResp.BlobAppendOffset(), chk.Equals, "0")
	c.Assert(appendResp.BlobCommittedBlockCount(), chk.Equals, "1")
	c.Assert(appendResp.ETag(), chk.Not(chk.Equals), azblob.ETagNone)
	c.Assert(appendResp.LastModified().IsZero(), chk.Equals, false)
	c.Assert(appendResp.ContentMD5(), chk.Not(chk.Equals), "")
	c.Assert(appendResp.RequestID(), chk.Not(chk.Equals), "")
	c.Assert(appendResp.Version(), chk.Not(chk.Equals), "")
	c.Assert(appendResp.Date().IsZero(), chk.Equals, false)

	appendResp, err = blob.AppendBlock(context.Background(), getReaderToRandomBytes(1024), azblob.BlobAccessConditions{})
	c.Assert(err, chk.IsNil)
	c.Assert(appendResp.BlobAppendOffset(), chk.Equals, "1024")
	c.Assert(appendResp.BlobCommittedBlockCount(), chk.Equals, "2")
}


text:
    #pragma warning(push)
    #pragma warning(disable:4309)
#endif
#include <external/amdt_base_tools/Include/gtGRBaseToolsDLLBuild.h>
#ifdef _WIN32
    #pragma warning(pop)
#endif

// Standard C definitions (including NULL definition):
#if defined(__linux__)
    #define __STDC_LIMIT_MACROS
#endif
#include <stddef.h>

// STL:
#include <string>

// A large unsigned integer that is returned by the sizeof() operator:
typedef size_t gtSizeType;

#ifndef FCC
#define FCC(ch4) ((((gtUInt32)(ch4) & 0xFF) << 24) |     \
                  (((gtUInt32)(ch4) & 0xFF00) << 8) |    \
                  (((gtUInt32)(ch4) & 0xFF0000) >> 8) |  \
                  (((gtUInt32)(ch4) & 0xFF000000) >> 24))
#endif

// ------------------- Linux Variant ----------------------

// The Linux variant on which the software is compiled:
// - GR_GENERIC_LINUX_VARIANT - Generic Linux variant (Red Hat, Suse, etc)
// - GR_MAC_OS_X_LINUX_VARIANT - Mac OS X
#define GR_GENERIC_LINUX_VARIANT 1
#define GR_MAC_OS_X_LINUX_VARIANT 2
#define GR_ANDROID_LINUX_VARIANT 3

// ------------------- Build targets ----------------------

// The supported build targets (operating system to which we build our binaries):
// - GR_WIN32 - Window
// - GR_LINUX - Linux
#define GR_WINDOWS_OS   1
#define GR_LINUX_OS     2

// The current build target will be contained in GR_BUILD_TARGET:
#if defined(_WIN32)
    #define GR_BUILD_TARGET GR_WINDOWS_OS
#elif defined (__APPLE__)
    #define GR_BUILD_TARGET GR_LINUX_OS
    #define GR_LINUX_VARIANT GR_MAC_OS_X_LINUX_VARIANT
#elif defined(__ANDROID__)
    #define GR_BUILD_TARGET GR_LINUX_OS
    #define GR_LINUX_VARIANT GR_ANDROID_LINUX_VARIANT
#elif defined(__linux__)
    #define GR_BUILD_TARGET GR_LINUX_OS
    #define GR_LINUX_VARIANT GR_GENERIC_LINUX_VARIANT
#else
    #error Error: build target is not defined!!
#endif

// ------------------- Address space ----------------------

// The supported address spaces:
// - GR_32_BIT_ADDRESS_SPACE - 32 bit address space.
// - GR_64_BIT_ADDRESS_SPACE - 64 bit address space.
#define GR_32_BIT_ADDRESS_SPACE     1
#define GR_64_BIT_ADDRESS_SPACE     2

// The address space will be contained in GR_ADDRESS_SPACE_TYPE:
#if GR_BUILD_TARGET == GR_WINDOWS_OS
    #ifdef _WIN64
        #define GR_ADDRESS_SPACE_TYPE GR_64_BIT_ADDRESS_SPACE
    #else
        #define GR_ADDRESS_SPACE_TYPE GR_32_BIT_ADDRESS_SPACE
    #endif
#elif GR_BUILD_TARGET == GR_LINUX_OS
    #include <stdint.h>
    #include <stdlib.h>
    #include <string.h>
    #include <limits.h>

    #if __WORDSIZE == 32
        #define GR_ADDRESS_SPACE_TYPE GR_32_BIT_ADDRESS_SPACE
    #elif __WORDSIZE == 64
        #define GR_ADDRESS_SPACE_TYPE GR_64_BIT_ADDRESS_SPACE
    #else
        #error Error: Unknown address space size!
    #endif

#endif

// ------------------- Used compiler ----------------------

#define GR_VISUAL_CPP_COMPILER  1
#define GR_GNU_CPP_COMPILER     2

#if defined(_MSC_VER)
    #define GR_CPP_COMPILER GR_VISUAL_CPP_COMPILER
    #define GR_VISUAL_CPP_COMPILER_VERSION _MSC_VER
#else
    #define GR_CPP_COMPILER GR_GNU_CPP_COMPILER
    #define GR_GNU_CPP_COMPILER_VERSION __GNUC__
    #define GR_GNU_CPP_COMPILER_MINOR_VERSION __GNUC_MINOR__
#endif

#if GR_CPP_COMPILER == GR_VISUAL_CPP_COMPILER
    #define GR_HAS_CPP0X 1
#else
    #if defined(__GXX_EXPERIMENTAL_CXX0X__)
        #define GR_HAS_CPP0X 1
    #endif
#endif

// ------------------- Build configurations ----------------------

// The supported build configurations:
#define GR_DEBUG_BUILD 1
#define GR_RELEASE_BUILD 2

// The used build configuration will be contained in GR_BUILD_CONFIGURATION:
#if defined(_DEBUG)
    #define GR_BUILD_CONFIGURATION GR_DEBUG_BUILD
#elif defined(NDEBUG)
    #define GR_BUILD_CONFIGURATION GR_RELEASE_BUILD
#else
    #error Error: Unknown build configuration!
#endif

// ------------------- Build Access ----------------------

// The supported build configurations:
#define GR_PUBLIC_ACCESS 1
#define GR_NDA_ACCESS 2
#define GR_INTERNAL_ACCESS 3

#if defined (GDT_INTERNAL)
    #define GR_BUILD_ACCESS GR_INTERNAL_ACCESS
#elif defined (GDT_NDA)
    #define GR_BUILD_ACCESS GR_NDA_ACCESS
#elif defined (GDT_PUBLIC)
    #define GR_BUILD_ACCESS GR_PUBLIC_ACCESS
#else
    #error Error: Unknown build access!
#endif

// ------------------- Data Types ----------------------

#if GR_BUILD_TARGET == GR_WINDOWS_OS
    #include <WinError.h>

    // Represents fixed size data types:
    typedef char gtByte;
    typedef unsigned char gtUByte;
    typedef __int16 gtInt16;
    typedef unsigned __int16 gtUInt16;
    typedef __int32 gtInt32;
    typedef unsigned __int32 gtUInt32;
    typedef __int64 gtInt64;
    typedef unsigned __int64 gtUInt64;
    typedef float gtFloat32;
    typedef size_t gtSize_t;
    typedef uintptr_t gtUIntPtr;
    typedef intptr_t gtIntPtr;

    // Maximal values per fixed data type:
    #define GT_INT16_MAX _I16_MAX
    #define GT_UINT16_MAX _UI16_MAX
    #define GT_INT32_MAX _I32_MAX
    #define GT_UINT32_MAX _UI32_MAX
    #define GT_INT64_MAX _I64_MAX
    #define GT_UINT64_MAX _UI64_MAX
    #define GT_FLOAT32_MAX FLT_MAX

    // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
    #define E_NOFILE _HRESULT_TYPEDEF_(0x80070002L)

    // HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)
    #define E_INVALIDPATH _HRESULT_TYPEDEF_(0x80070003L)

    // HRESULT_FROM_WIN32(ERROR_INVALID_DATA)
    #define E_INVALIDDATA _HRESULT_TYPEDEF_(0x8007000DL)

    // HRESULT_FROM_WIN32(ERROR_RESOURCE_NOT_AVAILABLE)
    #define E_NOTAVAILABLE _HRESULT_TYPEDEF_(0x80075006L)

    // HRESULT_FROM_WIN32(ERROR_NO_DATA)
    #define E_NODATA _HRESULT_TYPEDEF_(0x800700E8L)

    // HRESULT_FROM_WIN32(ERROR_LOCK_VIOLATION)
    #define E_LOCKED _HRESULT_TYPEDEF_(0x80070021L)

    // HRESULT_FROM_WIN32(ERROR_TIMEOUT)
    #define E_TIMEOUT _HRESULT_TYPEDEF_(0x800705B4L)

    // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)
    #define E_NOTSUPPORTED  _HRESULT_TYPEDEF_(0x80070032)

#else

    // Represents fixed size data types:
    typedef float gtFloat32;
    typedef char gtByte;
    typedef char gtByte;
    typedef unsigned char gtUByte;
    typedef __int16_t gtInt16;
    typedef __uint16_t gtUInt16;
    typedef __int32_t gtInt32;
    typedef __uint32_t gtUInt32;
    typedef __int64_t gtInt64;
    typedef __uint64_t gtUInt64;
    typedef size_t gtSize_t;
    typedef uintptr_t gtUIntPtr;
    typedef intptr_t gtIntPtr;

    // Char type:
    #ifdef GR_UNICODE
        typedef wchar_t gtChar;
    #else
        typedef char gtChar;
    #endif

    // Maximal values per fixed data type:
    #define GT_INT16_MAX INT16_MAX
    #define GT_UINT16_MAX UINT16_MAX
    #define GT_INT32_MAX INT32_MAX
    #define GT_UINT32_MAX UINT32_MAX
    #define GT_INT64_MAX INT64_MAX
    #define GT_UINT64_MAX UINT64_MAX
    #define GT_FLOAT32_MAX FLT_MAX

    // This value is missing from gcc 4.1.2 for some reason (4.1.1 has it):
    #ifndef FLT_MAX
        #define FLT_MAX __FLT_MAX__
    #endif
    #ifndef DBL_MAX
        #define DBL_MAX __DBL_MAX__
    #endif

    typedef gtInt32           HRESULT;

    #define SUCCEEDED(hr)   (((HRESULT)(hr)) >= 0)

    // The convention seems to be to take the value of the error (windows system error codes)
    // and then to add 0x80070000 to it to make the linux equivalent.
    // but that isn't even consistently done here.
    #define _HRESULT_TYPEDEF_(sc) ((HRESULT)sc)

    #define S_OK            _HRESULT_TYPEDEF_(0)
    #define S_FALSE         _HRESULT_TYPEDEF_(1)
    #define E_FAIL          _HRESULT_TYPEDEF_(0x80004005)
    #define E_INVALIDARG    _HRESULT_TYPEDEF_(0x80070057)
    #define E_OUTOFMEMORY   _HRESULT_TYPEDEF_(0x8007000E)
    #define E_UNEXPECTED    _HRESULT_TYPEDEF_(0x8000FFFF)
    #define E_ACCESSDENIED  _HRESULT_TYPEDEF_(0x80070005)
    #define E_HANDLE        _HRESULT_TYPEDEF_(0x80070006)
    #define E_ABORT         _HRESULT_TYPEDEF_(0x80004004)
    #define E_NOTIMPL       _HRESULT_TYPEDEF_(0x80004001)
    #define E_NOFILE        _HRESULT_TYPEDEF_(0x80070002)   // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
    #define E_INVALIDPATH   _HRESULT_TYPEDEF_(0x80070003)   // HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)
    #define E_INVALIDDATA   _HRESULT_TYPEDEF_(0x8007000D)   // HRESULT_FROM_WIN32(ERROR_INVALID_DATA)
    #define E_NOTAVAILABLE  _HRESULT_TYPEDEF_(0x80075006)   // HRESULT_FROM_WIN32(ERROR_RESOURCE_NOT_AVAILABLE)
    #define E_NODATA        _HRESULT_TYPEDEF_(0x800700E8)   // HRESULT_FROM_WIN32(ERROR_NO_DATA)
    #define E_LOCKED        _HRESULT_TYPEDEF_(0x80070021)   // HRESULT_FROM_WIN32(ERROR_LOCK_VIOLATION)
    #define E_TIMEOUT       _HRESULT_TYPEDEF_(0x800705B4)   // HRESULT_FROM_WIN32(ERROR_TIMEOUT)
    #define E_PENDING       _HRESULT_TYPEDEF_(0x8000000A)
    #define E_NOTSUPPORTED  _HRESULT_TYPEDEF_(0x80070032)   // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)

#endif

// Relative Virtual Address
typedef gtUInt32 gtRVAddr;
// Virtual Address
typedef gtUInt64 gtVAddr;

#define GT_INVALID_RVADDR ((gtRVAddr)(-1))
#define GT_INVALID_VADDR ((gtVAddr)(0))

#define GT_UNREFERENCED_PARAMETER(p) ((void)(p))

#define GT_CONTAINING_RECORD(address, type, field) ((type *)((gtByte*)(address) - (gtUIntPtr)(&((type *)0)->field)))

template <bool flag, class IsTrue, class IsFalse>
struct ConditionalType;

template <class IsTrue, class IsFalse>
struct ConditionalType<true, IsTrue, IsFalse>
{
    typedef IsTrue type;
};

template <class IsTrue, class IsFalse>
struct ConditionalType<false, IsTrue, IsFalse>
{
    typedef IsFalse type;
};

//
// Converts error codes to error description strings.
// The error codes are defined in gtDefinitions.h (above) and WinError.h.
//
GT_API const wchar_t* gtGetErrorString(const HRESULT errCode);

#endif  // __GTDEFINITIONS


text:
from __future__ import print_function
import argparse
import re
import os
import unicodedata
import sys

import pandas as pd

def good_tag(tag, valid_tags):
    """Returns True if tag contains of the valid tags.

    :param tag: string
    :param valid_tags: list of valid tags
    """
    for each in valid_tags:
        if each in str(tag):
            return True
    return False

def wiki_to_md(text):
    """Convert wiki formatting to markdown formatting.

    :param text: string of text to process

    :return: processed string
    """
    fn = []
    new_text = []
    fn_n = 1  # Counter for footnotes
    for line in text.split('\n'):
        # Replace wiki headers with markdown headers
        match = re.match('(!+)(\\s?)[^\\[]', line)
        if match:
            header, spaces = match.groups()
            new_str = '#' * len(header)
            line = re.sub('(!+)(\\s?)([^\\[])', new_str + ' ' + '\\3', line)
        # Underline (doesn't exist in MD)
        line = re.sub("__(.*?)__", "\\1", line)
        # Bold
        line = re.sub("''(.*?)''", "**\\1**", line)
        # Italics
        line = re.sub("//(.*?)//", "_\\1_", line)
        # Remove wiki links
        line = re.sub("\\[\\[(\\w+?)\\]\\]", "\\1", line)
        # Change links to markdown format
        line = re.sub("\\[\\[(.*)\\|(.*)\\]\\]", "[\\1](\\2)", line)
        # Code
        line = re.sub("\\{\\{\\{(.*?)\\}\\}\\}", "`\\1`", line)
        # Footnotes
        match = re.search("```(.*)```", line)
        if match:
            text = match.groups()[0]
            fn.append(text)
            line = re.sub("```(.*)```", '[^{}]'.format(fn_n), line)
            fn_n += 1
        new_text.append(line)

    # Append footnotes
    for i, each in enumerate(fn):
        new_text.append('[^{}]: {}'.format(i+1, each))
    return '\n'.join(new_text)

def sanitize(value):
    """Makes sure filenames are valid by replacing illegal characters

    :param value: string
    """
    value = unicode(value)
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = unicode(re.sub('[^\w\s-]', '', value).strip())
    return value

def main(args):

    output_path = args.outdir
    try:
        os.mkdir(output_path)
    except OSError:
        pass

    df = pd.read_csv(args.input_file)
    if args.tags:
        df = df[df.tags.apply(lambda x: good_tag(x, args.tags))]

    for row_id, row in df.iterrows():
        filename = sanitize(row.title)
        filename = '{}.{}'.format(filename, args.ext)
        with open(os.path.join(output_path, filename), 'w') as f:
            try:
                f.write(wiki_to_md(row.text))
            except:
                f.write('')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Convert TiddlyWiki tiddlers exported as CSV to "
                    "individual files.")
    parser.add_argument('--ext', '-e', dest='ext',
                        default='md',
                        help='File extension (defaults to "md")')
    parser.add_argument('--outdir', '-o',
                        default='output',
                        dest='outdir',
                        help='Output folder (defaults to "output")')
    parser.add_argument('--tags', '-t', dest='tags',
                        action='append',
                        help='Valid tag to export, can have multiple')
    parser.add_argument('input_file',
                        help='Exported CSV file')
    args = parser.parse_args()

    sys.exit(main(args))


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package JavaApplicationPizzariaSMA;

import UI.BackgroundImagemJFrame;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.tools.sniffer.Sniffer;
import jade.wrapper.AgentContainer;

/**
 *
 * @author jean
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    private static boolean _apresentacao = true;
    private static int _tempoSpawnCliente = 5;
    private static int _tempoEntregaPizzaMotoboy = 15;
    private static int _tempoSleepEtapasApresentacao = 30;

    private static AgentContainer cc;
    public static BackgroundImagemJFrame jframe;

    public static void main(String[] args) {
        // TODO code application logic here
        jframe = new BackgroundImagemJFrame();
        jframe.setApresentacao(_apresentacao);
        jframe.setTempoSpawnCliente(_tempoSpawnCliente);
        jframe.setTempoEntregaPizzaMotoboy(_tempoEntregaPizzaMotoboy);
        jframe.setTempoSleepEtapasApresentacao(_tempoSleepEtapasApresentacao);

        startJadePlatform();
    }

    private static void startJadePlatform()
    {
        //http://wenku.baidu.com/view/aacb10eeaeaad1f346933f1d.html
        try{
            //get a hold on jade runtime
            jade.core.Runtime rt = jade.core.Runtime.instance();
            //create a default profile
            Profile p = new ProfileImpl();
            //create a new non-main container, connecting to the default
            //main container(i.e. on this host, port 1099
            //ContainerController cc = rt.createAgentContainer(p);
            //cc = rt.createAgentContainer(p);
            cc = rt.createMainContainer(p);

            //create new agents and pass it a reference to an object
//            Object reference = new Object();
//            Object args[] = new Object[1];
//            args[0] = reference;
//            jade.wrapper.AgentController telefonistaSara = cc.createNewAgent("telefonistaSara", "JavaApplicationPizzariaSMA.Telefonista", args);
            JavaApplicationPizzariaSMA.Telefonista telefonistaSara = new Telefonista();
            telefonistaSara.setJFrame(jframe);
            jade.wrapper.AgentController telefonistaSaraAC = cc.acceptNewAgent("telefonistaSara", telefonistaSara);

//            //create new agents and pass it a reference to an object
//            Object referenceClienteJean = new Object();
//            Object argsClienteJean[] = new Object[1];
//            argsClienteJean[0] = referenceClienteJean;
//            jade.wrapper.AgentController clienteJean = cc.createNewAgent("clienteJean", "JavaApplicationPizzariaSMA.Cliente", argsClienteJean);

            JavaApplicationPizzariaSMA.Motoboy motoboy = new Motoboy();
            motoboy.setJFrame(jframe);
            jade.wrapper.AgentController motoboyJoaoAC = cc.acceptNewAgent("motoboyJoao", motoboy);

            JavaApplicationPizzariaSMA.Motoboy motoboyPedro = new Motoboy();
            motoboyPedro.setJFrame(jframe);
            jade.wrapper.AgentController motoboyPedroAC = cc.acceptNewAgent("motoboyPedro", motoboyPedro);

            JavaApplicationPizzariaSMA.Pizzaiolo pizzaiolo = new Pizzaiolo();
            pizzaiolo.setJFrame(jframe);
            jade.wrapper.AgentController pizzaioloAC = cc.acceptNewAgent("pizzaioloBeto", pizzaiolo);

            //Adiciona os agentes na lista para serem espionados
            //http://jade.tilab.com/doc/tools/sniffer/html/jdoc/jade/tools/sniffer/Sniffer.html#sniffMsg%28jade.util.leap.List,%20boolean%29
            jade.tools.sniffer.Sniffer sniffer = new Sniffer();
            jade.wrapper.AgentController snifferAC = cc.acceptNewAgent("sniffer", sniffer);
            snifferAC.start();

            //fire up agents
            pizzaioloAC.start();
            motoboyJoaoAC.start();
            motoboyPedroAC.start();
            telefonistaSaraAC.start();

            //Visibilidade Componentes tela
            jframe.jLabelModo.setVisible(true);
            jframe.jLabelModoResposta.setVisible(true);

            if(_apresentacao) //cria somente uma vez
            {
                //Visibilidade Componentes tela
                jframe.jLabelTempoSpawnClientes.setVisible(false);
                jframe.jLabelTempoSpawnClientesResposta.setVisible(false);
                jframe.jLabelTempoDelivery.setVisible(false);
                jframe.jLabelTempoDeliveryResposta.setVisible(false);
                jframe.jLabelTempoSleepEtapasApresentacao.setVisible(true);
                jframe.jLabelTempoSleepEtapasApresentacaoResposta.setVisible(true);
                jframe.jLabelPasso.setVisible(true);
                jframe.jLabelPassoResposta.setVisible(true);
                //Valores labels
                jframe.jLabelModoResposta.setText("Apresentação");
                jframe.jLabelTempoSleepEtapasApresentacaoResposta.setText(String.valueOf(_tempoSleepEtapasApresentacao));

                //Cria cliente
                JavaApplicationPizzariaSMA.Cliente cliente = new Cliente();
                cliente.setJFrame(jframe);
                jade.wrapper.AgentController clienteAC = cc.acceptNewAgent("cliente_0", cliente);

                //demorar um pouco para dar tempo de obter o sniff do cliente
                jframe.PassoDormir();

                clienteAC.start();

                jframe.AddClient(cliente.getName());
            }
            else //criar cliente a cada x segundos
            {
                //Visibilidade Componentes tela
                jframe.jLabelTempoSpawnClientes.setVisible(true);
                jframe.jLabelTempoSpawnClientesResposta.setVisible(true);
                jframe.jLabelTempoDelivery.setVisible(true);
                jframe.jLabelTempoDeliveryResposta.setVisible(true);
                jframe.jLabelTempoSleepEtapasApresentacao.setVisible(false);
                jframe.jLabelTempoSleepEtapasApresentacaoResposta.setVisible(false);
                //Valores labels
                jframe.jLabelModoResposta.setText("Normal");
                jframe.jLabelTempoSpawnClientesResposta.setText(String.valueOf(_tempoSpawnCliente));
                jframe.jLabelTempoDeliveryResposta.setText(String.valueOf(_tempoEntregaPizzaMotoboy));
                jframe.jLabelPasso.setVisible(false);
                jframe.jLabelPassoResposta.setVisible(false);

                TimerCriarCliente tcc = new TimerCriarCliente(_tempoSpawnCliente, cc, jframe);
            }

        }catch(Exception ex)
        {
            System.out.println(ex.getMessage());
            //Logger.getLogger(PlatformMediator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


text:
#ifndef __LIBRETRO_SDK_STDSTRING_H
#define __LIBRETRO_SDK_STDSTRING_H

#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

char *string_replace_substring(const char *in, const char *pattern,
      const char *by);

#ifdef __cplusplus
}
#endif

#endif