text:
<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Compress;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1 as PPhase1;
use Praxigento\BonusHybrid\Service\Calc\Compress\Z\Repo\Query\GetPhase1Pv as QBldGetPv;
use Praxigento\Downline\Repo\Query\Snap\OnDate\Builder as QBSnap;

class Phase1
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpDwnlTree;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1 */
    private $procPhase1;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Compress\Z\Repo\Query\GetPhase1Pv */
    private $qbGetPv;
    /** @var \Praxigento\Downline\Repo\Query\Snap\OnDate\Builder */
    private $qbSnapOnDate;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusBase\Repo\Dao\Rank */
    private $daoRank;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Compression\Phase1\Transfer\Pv */
    private $daoTransPv;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Downline\Api\Helper\Tree $hlpDwnlTree,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusBase\Repo\Dao\Rank $daoRank,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusHybrid\Repo\Dao\Compression\Phase1\Transfer\Pv $daoTransPv,
        \Praxigento\BonusHybrid\Service\Calc\Compress\Z\Repo\Query\GetPhase1Pv $qbGetPv,
        \Praxigento\Downline\Repo\Query\Snap\OnDate\Builder $qbSnapOnDate,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1 $procPhase1
    ) {
        $this->logger = $logger;
        $this->hlpDwnlTree = $hlpDwnlTree;
        $this->daoCalc = $daoCalc;
        $this->daoRank = $daoRank;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->daoTransPv = $daoTransPv;
        $this->qbGetPv = $qbGetPv;
        $this->qbSnapOnDate = $qbSnapOnDate;
        $this->servPeriodGet = $servPeriodGet;
        $this->procPhase1 = $procPhase1;
    }

    /**
     * Wrapper for compression sub-process.
     *
     * @param array $dwnlSnap see \Praxigento\Downline\Repo\Query\Snap\OnDate\Builder
     * @param array $pv [custId => pv]
     * @param int $calcId
     * @return array [$updates, $pvTransfers]
     */
    private function compress($dwnlSnap, $pv, $calcId)
    {
        $in = new \Praxigento\Core\Data();
        $in->set(PPhase1::IN_DWNL_PLAIN, $dwnlSnap);
        $in->set(PPhase1::IN_PV, $pv);
        $in->set(PPhase1::IN_CALC_ID, $calcId);
        $in->set(PPhase1::IN_KEY_CALC_ID, EBonDwnl::A_CALC_REF);
        $in->set(PPhase1::IN_KEY_CUST_ID, QBSnap::A_CUST_ID);
        $in->set(PPhase1::IN_KEY_PARENT_ID, QBSnap::A_PARENT_ID);
        $in->set(PPhase1::IN_KEY_DEPTH, QBSnap::A_DEPTH);
        $in->set(PPhase1::IN_KEY_PATH, QBSnap::A_PATH);
        $in->set(PPhase1::IN_KEY_PV, EBonDwnl::A_PV);
        $out = $this->procPhase1->exec($in);
        $updates = $out->get(PPhase1::OUT_COMPRESSED);
        $pvTransfers = $out->get(PPhase1::OUT_PV_TRANSFERS);
        $result = [$updates, $pvTransfers];
        return $result;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        $this->logger->info("Phase1 compression is started.");
        /* get dependent calculation data */
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $writeOffCalc */
        /** @var \Praxigento\BonusBase\Repo\Data\Period $compressPeriod */
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        list($writeOffCalc, $compressPeriod, $compressCalc) = $this->getCalcData();
        $compressPeriodId = $compressPeriod->getId();
        $dsBegin = $compressPeriod->getDstampBegin();
        $dsEnd = $compressPeriod->getDstampEnd();
        $writeOffCalcId = $writeOffCalc->getId();
        $compressCalcId = $compressCalc->getId();
        $this->logger->info("Phase1 compression period #$compressPeriodId ($dsBegin-$dsEnd)");
        /* load source data for calculation */
        /* TODO: move source data collection into sub-class */
        $dwnlSnap = $this->getDownlineSnapshot($dsEnd);
        $dataPv = $this->getPv($writeOffCalcId);
        /** @var \Praxigento\Downline\Repo\Data\Snap[] $updates */
        /** @var \Praxigento\BonusHybrid\Repo\Data\Compression\Phase1\Transfer\Pv[] $pvTransfers */
        list($updates, $pvTransfers) = $this->compress($dwnlSnap, $dataPv, $compressCalcId);
        /* save compressed downline & PV transfers into DB */
        $this->saveBonusDownline($updates, $compressCalcId);
        $this->savePvTransfers($pvTransfers);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($compressCalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("Phase1 compression is completed.");
    }

    /**
     * Get data for calculations/periods.
     *
     * @return array [$writeOffCalc, $compressPeriod, $compressCalc]
     * @throws \Exception
     */
    private function getCalcData()
    {
        /**
         * Get data for compression & PV write off calculations.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_PV_WRITE_OFF);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        $writeOffCalc = $resp->getBaseCalcData();
        /** @var \Praxigento\BonusBase\Repo\Data\Period $compressPeriod */
        $compressPeriod = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $depCalcData */
        $compressCalc = $resp->getDepCalcData();
        /**
         * Compose result.
         */
        $result = [$writeOffCalc, $compressPeriod, $compressCalc];
        return $result;
    }

    /**
     * Get ID for default rank.
     *
     * @return int
     */
    private function getDefaultRankId()
    {
        $result = $this->daoRank->getIdByCode(Cfg::RANK_DISTRIBUTOR);
        return $result;
    }

    /**
     * Get Downline Tree snapshot on the $datestamp. Result is an array [$customerId => [...], ...]
     *
     * @param $dateOn 'YYYYMMDD'
     *
     * @return array|null
     */
    private function getDownlineSnapshot($dateOn)
    {
        /* collect downline data to given date */
        $query = $this->qbSnapOnDate->build();
        $conn = $query->getConnection();
        $bind = [$this->qbSnapOnDate::BND_ON_DATE => $dateOn];
        $result = $conn->fetchAll($query, $bind);
        return $result;
    }

    /**
     * Get PV that are debited inside 'PV Write Off' operation related for the $calcId.
     * @param int $calcId
     * @return array
     */
    private function getPv($calcId)
    {
        $query = $this->qbGetPv->build();
        $conn = $query->getConnection();
        $bind = [QBldGetPv::BND_CALC_ID => $calcId];
        $data = $conn->fetchAll($query, $bind);
        $result = $this->hlpDwnlTree->mapValueById($data, QBldGetPv::A_CUST_ID, QBldGetPv::A_PV);
        return $result;
    }

    /**
     * @param array $snap snap data with PV (see
     *     \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase1::populateCompressedSnapWithPv)
     * @param int $calcId
     */
    private function saveBonusDownline($snap, $calcId)
    {
        /* 'distributor' is the minimal rank in compressed trees */
        $rankId = $this->getDefaultRankId();

        foreach ($snap as $one) {
            /* get working vars */
            $custId = $one[QBSnap::A_CUST_ID];
            $depth = $one[QBSnap::A_DEPTH];
            $parentId = $one[QBSnap::A_PARENT_ID];
            $path = $one[QBSnap::A_PATH];
            $pv = $one[EBonDwnl::A_PV];
            /* compose new entity to save */
            $entity = new EBonDwnl();
            $entity->setCalculationRef($calcId);
            $entity->setCustomerRef($custId);
            $entity->setDepth($depth);
            $entity->setOv(0);
            $entity->setParentRef($parentId);
            $entity->setPath($path);
            $entity->setPv($pv);
            $entity->setRankRef($rankId);
            $entity->setTv(0);
            $this->daoBonDwnl->create($entity);
        }
    }

    /**
     * @param \Praxigento\BonusHybrid\Repo\Data\Compression\Phase1\Transfer\Pv[] $data
     */
    private function savePvTransfers($data)
    {
        /** @var \Praxigento\BonusHybrid\Repo\Data\Compression\Phase1\Transfer\Pv $one */
        foreach ($data as $one) {
            $this->daoTransPv->create($one);
        }
    }
}


text:
import os
import uuid
#from osipkdpdpt.tools import row2dict, xls_reader
from datetime import datetime
from sqlalchemy import not_, func
from pyramid.view import (view_config,)
from pyramid.httpexceptions import ( HTTPFound, )
import colander
from deform import (Form, widget, ValidationFailure, )
from osipkd.models import DBSession
from osipkd.models.ar import ARPaymentTransaksi
#from osipkd.models.apbd_anggaran import Kegiatan, KegiatanSub, KegiatanItem
from osipkd.models.pemda import Unit
from osipkd.models.ak import Jurnal, JurnalItem, Rekening, RekeningSap, Sap

from datatables import ColumnDT, DataTables
from osipkd.views.base_view import BaseViews

SESS_ADD_FAILED = 'Tambah ar-payment-transaksi gagal'
SESS_EDIT_FAILED = 'Edit ar-payment-transaksi gagal'

def deferred_sumber_id(node, kw):
    values = kw.get('sumber_id', [])
    return widget.SelectWidget(values=values)

SUMBER_ID = (
    (1, 'Manual'),
    (2, 'PBB'),
    (3, 'BPHTB'),
    (4, 'PADL'))

class AddSchema(colander.Schema):
    unit_kd_widget = widget.AutocompleteInputWidget(
            values = '/unit/act/headofkode',
            min_length=1)

    unit_nm_widget = widget.AutocompleteInputWidget(
            values = '/unit/act/headofnama',
            min_length=1)

    kegiatan_nm_widget = widget.AutocompleteInputWidget(
            size=60,
            values = '/ag-kegiatan-sub/act/headofnama',
            min_length=1)

    kegiatan_kd_widget = widget.AutocompleteInputWidget(
            size=60,
            values = '/ag-kegiatan-sub/act/headofkode',
            min_length=1)

    rekening_nm_widget = widget.AutocompleteInputWidget(
            size=60,
            values = '/rekening/act/headofnama11',
            min_length=1)

    rekening_kd_widget = widget.AutocompleteInputWidget(
            size=60,
            values = '/rekening/act/headofkode11',
            min_length=1,
            )

    unit_id  = colander.SchemaNode(
                    colander.Integer(),
                    oid='unit_id',
                    title="SKPD")

    unit_kd  = colander.SchemaNode(
                    colander.String(),
                    oid='unit_kd',
                    title="SKPD",
                    widget = unit_kd_widget,)

    unit_nm  = colander.SchemaNode(
                    colander.String(),
                    oid='unit_nm',
                    title="SKPD",
                    widget = unit_nm_widget)

    """kegiatan_sub_id  = colander.SchemaNode(
                    colander.Integer(),
                    oid='kegiatan_sub_id',
                    title="SKPD")

    kegiatan_sub_kd  = colander.SchemaNode(
                    colander.String(),
                    oid='kegiatan_sub_kd',
                    title="Kegiatan",
                    widget = kegiatan_kd_widget,)

    kegiatan_sub_nm  = colander.SchemaNode(
                    colander.String(),
                    oid='kegiatan_sub_nm',
                    widget = kegiatan_nm_widget)
    """
    rekening_id  = colander.SchemaNode(
                    colander.Integer(),
                    oid='rekening_id')
    kode  = colander.SchemaNode(
                    colander.String(),
                    widget = rekening_kd_widget,
                    oid='kode',
                    title='Rekening',
                    )

    nama = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=128),
                    widget = rekening_nm_widget,
                    oid = 'nama')
    ref_kode = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=32),
                    title = "No Bank"
                    )
    ref_nama = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=64),
                    )

    tanggal = colander.SchemaNode(
                colander.Date(),
                )

    amount = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=32),
                    default = 0,
                    title = "Nilai"
                    )

    sumber_id  =  colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=32),
                    widget=widget.SelectWidget(values=SUMBER_ID),
                    title = "Sumber")
                    # deferred_source_type)

    bud_uid    = colander.SchemaNode(
                          colander.Integer(),
                          oid="bud_uid",
                          missing=colander.drop,
                          title="Bendahara")
    bud_nip    = colander.SchemaNode(
                          colander.String(),
                          oid="bud_nip",
                          missing=colander.drop,
                          title="Bendahara")
    bud_nama     = colander.SchemaNode(
                          colander.String(),
                          missing=colander.drop,
                          oid="bud_nama")
    ############## DI DROP DULU
    kecamatan_kd = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=32),
                    missing=colander.drop)
    kecamatan_nm = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=64),
                    missing=colander.drop)

    kelurahan_kd = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=32),
                    missing=colander.drop
                    )
    kelurahan_nm = colander.SchemaNode(
                    colander.String(),
                    validator=colander.Length(max=64),
                    missing=colander.drop)
    is_kota  = colander.SchemaNode(
                    colander.Boolean(),
                    missing = colander.drop
                    ) # deferred_source_type)

    disabled = colander.SchemaNode(
                    colander.Boolean(),
                    missing = colander.drop
                    ) # deferred_source_type)

class EditSchema(AddSchema):
    id = colander.SchemaNode(colander.String(),
            missing=colander.drop,
            widget=widget.HiddenWidget(readonly=True))

class view_ar_payment_item(BaseViews):
    ########
    # List #
    ########
    @view_config(route_name='ar-payment-transaksi', renderer='templates/ar-payment-transaksi/list.pt',
                 permission='read')
    def view_list(self):
        ses = self.request.session
        req = self.request
        params = req.params
        url_dict = req.matchdict
        return dict(project='EIS')

    ##########
    # Action #
    ##########
    @view_config(route_name='ar-payment-transaksi-act', renderer='json',
                 permission='read')
    def ar_payment_item_act(self):
        ses = self.request.session
        req = self.request
        params = req.params
        url_dict = req.matchdict
        kegiatan_sub_id = 'kegiatan_sub_id' in params and params['kegiatan_sub_id'] or 0
        if url_dict['act']=='grid':
            columns = []
            columns.append(ColumnDT('id'))
            #columns.append(ColumnDT('kegiatan_subs.kegiatans.kode'))
            #columns.append(ColumnDT('kegiatan_subs.no_urut'))
            columns.append(ColumnDT('kode'))
            columns.append(ColumnDT('nama'))
            columns.append(ColumnDT('ref_kode'))
            columns.append(ColumnDT('ref_nama'))
            columns.append(ColumnDT('tanggal', filter=self._DTstrftime))
            columns.append(ColumnDT('amount',  filter=self._number_format))
            columns.append(ColumnDT('posted'))
            query = DBSession.query(ARPaymentTransaksi).filter(
                      ARPaymentTransaksi.tahun == ses['tahun'],
                      ARPaymentTransaksi.unit_id == ses['unit_id'],
                      ARPaymentTransaksi.tanggal == ses['tanggal'],

                      )
            rowTable = DataTables(req, ARPaymentTransaksi, query, columns)
            return rowTable.output_result()

    #######
    # Add #
    #######
    def form_validator(self, form, value):
        if 'id' in form.request.matchdict:
            uid = form.request.matchdict['id']
            q = DBSession.query(ARPaymentTransaksi).filter_by(id=uid)
            row = q.first()
        else:
            row = None

    def get_form(self, class_form, row=None):
        schema = class_form(validator=self.form_validator)
        schema = schema.bind(sumber_id=SUMBER_ID)
        schema.request = self.request
        if row:
          schema.deserialize(row)
        return Form(schema, buttons=('simpan','batal'))

    def save(self, values, user, row=None):
        if not row:
            row = ARPaymentTransaksi()
            row.created    = datetime.now()
            row.create_uid = user.id
        row.from_dict(values)
        row.updated    = datetime.now()
        row.update_uid = user.id
        tanggal     = datetime.strptime(values['tanggal'], '%Y-%m-%d')
        row.tahun   = tanggal.year
        row.bulan   = tanggal.month
        row.hari    = tanggal.day
        row.minggu  = tanggal.isocalendar()[1]
        row.disable = 'disable' in values and values['disable'] and 1 or 0
        row.is_kota = 'is_kota' in values and values['is_kota'] and 1 or 0

        DBSession.add(row)
        DBSession.flush()
        return row

    def save_request(self, values, row=None):
        if 'id' in self.request.matchdict:
            values['id'] = self.request.matchdict['id']
        row = self.save(values, self.request.user, row)
        self.request.session.flash('Realisasi / STS sudah disimpan.')

    def route_list(self):
        return HTTPFound(location=self.request.route_url('ar-payment-transaksi') )

    def session_failed(self, session_name):

        #r = dict(form=self.session[session_name])
        del self.session[session_name]
        #return r

    @view_config(route_name='ar-payment-transaksi-add', renderer='templates/ar-payment-transaksi/add.pt',
                 permission='add')
    def view_ar_payment_item_add(self):
        req = self.request
        ses = self.session
        form = self.get_form(AddSchema)
        if req.POST:
            if 'simpan' in req.POST:
                controls = req.POST.items()
                try:
                    c = form.validate(controls)
                except ValidationFailure, e:
                    #req.session[SESS_ADD_FAILED] = e.render()
                    #form.set_appstruct(rowd)
                    return dict(form=form)
                    #return HTTPFound(location=req.route_url('ar-payment-transaksi-add'))
                self.save_request(dict(controls))
            return self.route_list()
        elif SESS_ADD_FAILED in req.session:
            return dict(form=form)

            #return self.session_failed(SESS_ADD_FAILED)
        rowd={}
        rowd['unit_id']     = ses['unit_id']
        rowd['unit_nm']     = ses['unit_nm']
        rowd['unit_kd']     = ses['unit_kd']
        form.set_appstruct(rowd)
        return dict(form=form)

    ########
    # Edit #
    ########
    def query_id(self):
        return DBSession.query(ARPaymentTransaksi).filter_by(id=self.request.matchdict['id'])

    def id_not_found(self):
        msg = 'Realisasi / STS ID %s Tidak Ditemukan.' % self.request.matchdict['id']
        request.session.flash(msg, 'error')
        return route_list()

    @view_config(route_name='ar-payment-transaksi-edit', renderer='templates/ar-payment-transaksi/add.pt',
                 permission='edit')
    def view_ar_payment_item_edit(self):
        request = self.request
        row     = self.query_id().first()

        if not row:
            return id_not_found(request)
        if row.posted:
            request.session.flash('Data sudah diposting', 'error')
            return self.route_list()

        form = self.get_form(EditSchema)
        if request.POST:
            if 'simpan' in request.POST:
                controls = request.POST.items()
                print controls
                try:
                    c = form.validate(controls)
                except ValidationFailure, e:
                    return dict(form=form)
                    #request.session[SESS_EDIT_FAILED] = e.render()
                    #return HTTPFound(location=request.route_url('ar-payment-transaksi-edit',
                    #                  id=row.id))
                self.save_request(dict(controls), row)
            return self.route_list()
        elif SESS_EDIT_FAILED in request.session:
            return self.session_failed(SESS_EDIT_FAILED)
        rowd = row.to_dict()
        #rowd={}
        #rowd['id']          = row.id
        #rowd['unit_id']     = row.unit_id
        rowd['unit_nm']     = row.units.nama
        rowd['unit_kd']     = row.units.kode
        #rowd['kegiatan_sub_id'] =row.kegiatan_sub_id
        #rowd['kegiatan_sub_kd'] ="".join([row.kegiatan_subs.kegiatans.kode,'-',str(row.kegiatan_subs.no_urut)])
        #rowd['kegiatan_sub_nm'] =row.kegiatan_subs.nama
        #rowd['rekening_id'] = row.rekening_id
        #rowd['kode']        = row.kode
        #rowd['nama']        = row.nama
        #rowd['ref_kode']    = row.ref_kode
        #rowd['ref_nama']    = row.ref_nama
        #rowd['tanggal']    = row.tanggal
        #rowd['amount']     = row.amount
        #rowd['kecamatan_kd']    = row.kecamatan_kd
        #rowd['kecamatan_nm']    = row.kecamatan_nm
        #rowd['kelurahan_kd']    = row.kelurahan_kd
        #rowd['kelurahan_nm']    = row.kelurahan_nm
        #rowd['is_kota']         = row.is_kota
        #rowd['disabled']      = row.disabled
        #rowd['sumber_id']    = row.sumber_id
        form.set_appstruct(rowd)
        return dict(form=form)

    ##########
    # Delete #
    ##########
    @view_config(route_name='ar-payment-transaksi-delete', renderer='templates/ar-payment-transaksi/delete.pt',
                 permission='delete')
    def view_ar_payment_item_delete(self):
        request = self.request
        q       = self.query_id()
        row     = q.first()

        if not row:
            return self.id_not_found(request)
        if row.posted:
            request.session.flash('Data sudah diposting', 'error')
            return self.route_list()

        form = Form(colander.Schema(), buttons=('hapus','batal'))
        if request.POST:
            if 'hapus' in request.POST:
                msg = 'Realisasi / STS ID %d %s sudah dihapus.' % (row.id, row.nama)
                try:
                  q.delete()
                  DBSession.flush()
                except:
                  msg = 'Realisasi / STS ID %d %s tidak dapat dihapus.' % (row.id, row.nama)
                request.session.flash(msg)
            return self.route_list()
        return dict(row=row,
                     form=form.render())

    ###########
    # Posting #
    ###########
    def save_request2(self, row=None):
        row = ARPaymentTransaksi()
        self.request.session.flash('TBP sudah diposting dan dibuat Jurnalnya.')
        return row

    @view_config(route_name='ar-payment-transaksi-posting', renderer='templates/ar-payment-transaksi/posting.pt',
                 permission='posting')
    def view_edit_posting(self):
        request = self.request
        row     = self.query_id().first()
        id_tbp  = row.id
        nama    = row.ref_nama
        kode    = row.ref_kode
        tanggal = row.tanggal

        if not row:
            return id_not_found(request)
        if not row.amount:
           request.session.flash('Data tidak dapat diposting jurnal, karena bernilai 0.', 'error')
           return route_list()
        if row.posted:
            request.session.flash('Data sudah diposting jurnal.', 'error')
            return self.route_list()

        form = Form(colander.Schema(), buttons=('jurnal','cancel'))

        if request.POST:
            if 'jurnal' in request.POST:
                #Update posted pada TBP
                row.posted=1
                self.save_request2(row)

                #Tambah ke Jurnal LO SKPD
                periode = ARPaymentTransaksi.get_periode(row.id)

                row = Jurnal()
                row.created    = datetime.now()
                row.create_uid = self.request.user.id
                row.updated    = datetime.now()
                row.update_uid = self.request.user.id
                row.tahun_id   = self.session['tahun']
                row.unit_id    = self.session['unit_id']
                row.nama       = "Diterima TBP %s" % nama
                row.notes      = nama
                row.periode    = periode
                row.posted     = 0
                row.disabled   = 0
                row.is_skpd    = 1
                row.jv_type    = 1
                row.source     = "TBP"
                row.source_no  = kode
                row.tgl_source = tanggal
                row.tanggal    = datetime.now()
                row.tgl_transaksi = datetime.now()

                if not row.kode:
                    tahun    = self.session['tahun']
                    unit_kd  = self.session['unit_kd']
                    is_skpd  = row.is_skpd
                    tipe     = Jurnal.get_tipe(row.jv_type)
                    no_urut  = Jurnal.get_norut(row.tahun_id,row.unit_id)+1
                    no       = "0000%d" % no_urut
                    nomor    = no[-5:]
                    row.kode = "%d" % tahun + "-%s" % is_skpd + "-%s" % unit_kd + "-%s" % tipe + "-%s" % nomor

                DBSession.add(row)
                DBSession.flush()

                jui   = row.id
                rows = DBSession.query(KegiatanItem.rekening_id.label('rekening_id1'),
                                       Sap.nama.label('nama1'),
                                       KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'),
                                       ARPaymentTransaksi.amount.label('nilai1'),
                                       RekeningSap.db_lo_sap_id.label('sap1'),
                                       Rekening.id.label('rek'),
                                ).join(Rekening
                                ).outerjoin(KegiatanItem,RekeningSap,KegiatanSub,
                                ).filter(ARPaymentTransaksi.id==id_tbp,
                                       ARPaymentTransaksi.rekening_id==KegiatanItem.rekening_id,
                                       KegiatanItem.kegiatan_sub_id==KegiatanSub.id,
                                       KegiatanItem.rekening_id==RekeningSap.rekening_id,
                                       RekeningSap.rekening_id==Rekening.id,
                                       RekeningSap.db_lo_sap_id==Sap.id
                                ).group_by(KegiatanItem.rekening_id.label('rekening_id1'),
                                       Sap.nama.label('nama1'),
                                       KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'),
                                       ARPaymentTransaksi.amount.label('nilai1'),
                                       RekeningSap.db_lo_sap_id.label('sap1'),
                                       Rekening.id.label('rek'),
                                ).all()

                n=0
                for row in rows:
                    ji = JurnalItem()

                    ji.jurnal_id = "%d" % jui
                    ji.kegiatan_sub_id = row.kegiatan_sub_id1
                    ji.rekening_id  = 0
                    x=DBSession.query(Sap.id).filter(Sap.kode=='1.1.1.02.01').first()
                    ji.sap_id       = x
                    ji.amount       = row.nilai1
                    ji.notes        = ""
                    n = n + 1

                    DBSession.add(ji)
                    DBSession.flush()

                n=0
                for row in rows:
                    ji2 = JurnalItem()

                    ji2.jurnal_id = "%d" % jui
                    ji2.kegiatan_sub_id = row.kegiatan_sub_id1
                    ji2.rekening_id  = row.rek
                    ji2.sap_id       = row.sap1
                    n = row.nilai1
                    ji2.amount       = n * -1
                    ji2.notes        = ""
                    n = n + 1

                    DBSession.add(ji2)
                    DBSession.flush()

                #Tambah ke Jurnal LRA SKPD
                periode2 = ARPaymentTransaksi.get_periode2(id_tbp)

                row = Jurnal()
                row.created    = datetime.now()
                row.create_uid = self.request.user.id
                row.updated    = datetime.now()
                row.update_uid = self.request.user.id
                row.tahun_id   = self.session['tahun']
                row.unit_id    = self.session['unit_id']
                row.nama       = "Diterima TBP %s" % nama
                row.notes      = nama
                row.periode    = periode2
                row.posted     = 0
                row.disabled   = 0
                row.is_skpd    = 1
                row.jv_type    = 1
                row.source     = "TBP"
                row.source_no  = kode
                row.tgl_source = tanggal
                row.tanggal    = datetime.now()
                row.tgl_transaksi = datetime.now()

                if not row.kode:
                    tahun    = self.session['tahun']
                    unit_kd  = self.session['unit_kd']
                    is_skpd  = row.is_skpd
                    tipe     = Jurnal.get_tipe(row.jv_type)
                    no_urut  = Jurnal.get_norut(row.tahun_id,row.unit_id)+1
                    no       = "0000%d" % no_urut
                    nomor    = no[-5:]
                    row.kode = "%d" % tahun + "-%s" % is_skpd + "-%s" % unit_kd + "-%s" % tipe + "-%s" % nomor

                DBSession.add(row)
                DBSession.flush()

                jui   = row.id
                rows = DBSession.query(KegiatanItem.rekening_id.label('rekening_id1'),
                                       Sap.nama.label('nama1'),
                                       KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'),
                                       ARPaymentTransaksi.amount.label('nilai1'),
                                       RekeningSap.db_lra_sap_id.label('sap1'),
                                       RekeningSap.kr_lra_sap_id.label('sap2'),
                                       Rekening.id.label('rek'),
                                ).join(Rekening
                                ).outerjoin(KegiatanItem,RekeningSap,KegiatanSub,
                                ).filter(ARPaymentTransaksi.id==id_tbp,
                                       ARPaymentTransaksi.rekening_id==KegiatanItem.rekening_id,
                                       KegiatanItem.kegiatan_sub_id==KegiatanSub.id,
                                       KegiatanItem.rekening_id==RekeningSap.rekening_id,
                                       RekeningSap.rekening_id==Rekening.id,
                                       RekeningSap.db_lra_sap_id==Sap.id
                                ).group_by(KegiatanItem.rekening_id.label('rekening_id1'),
                                       Sap.nama.label('nama1'),
                                       KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'),
                                       ARPaymentTransaksi.amount.label('nilai1'),
                                       RekeningSap.db_lra_sap_id.label('sap1'),
                                       RekeningSap.kr_lra_sap_id.label('sap2'),
                                       Rekening.id.label('rek'),
                                ).all()

                n=0
                for row in rows:
                    ji3 = JurnalItem()

                    ji3.jurnal_id = "%d" % jui
                    ji3.kegiatan_sub_id = row.kegiatan_sub_id1
                    ji3.rekening_id  = 0
                    ji3.sap_id       = row.sap1
                    ji3.amount       = row.nilai1
                    ji3.notes        = ""
                    n = n + 1

                    DBSession.add(ji3)
                    DBSession.flush()

                n=0
                for row in rows:
                    ji4 = JurnalItem()

                    ji4.jurnal_id = "%d" % jui
                    ji4.kegiatan_sub_id = row.kegiatan_sub_id1
                    ji4.rekening_id  = row.rek
                    ji4.sap_id       = row.sap2
                    n = row.nilai1
                    ji4.amount       = n * -1
                    ji4.notes        = ""
                    n = n + 1

                    DBSession.add(ji4)
                    DBSession.flush()

            return self.route_list()
        return dict(row=row, form=form.render())

    #############
    # UnPosting #
    #############
    def save_request4(self, row=None):
        row = ARPaymentTransaksi()
        self.request.session.flash('TBP sudah di Unposting jurnal.')
        return row

    @view_config(route_name='ar-payment-transaksi-unposting', renderer='templates/ar-payment-transaksi/unposting.pt',
                 permission='unposting')
    def view_edit_unposting(self):
        request = self.request
        row     = self.query_id().first()
        kode    = row.ref_kode

        if not row:
            return id_not_found(request)
        if not row.posted:
            self.request.session.flash('Data tidak dapat di Unposting jurnal, karena belum diposting jurnal.', 'error')
            return self.route_list()
        if row.disabled:
            self.request.session.flash('Data jurnal TBP sudah diposting.', 'error')
            return self.route_list()

        form = Form(colander.Schema(), buttons=('un-jurnal','cancel'))

        if request.POST:
            if 'un-jurnal' in request.POST:

                #Update status posted pada TBP
                row.posted=0
                self.save_request4(row)

                r = DBSession.query(Jurnal.id.label('di')).filter(Jurnal.source_no==row.ref_kode,Jurnal.source=='TBP').all()
                for row in r:
                    #Menghapus Item Jurnal
                    DBSession.query(JurnalItem).filter(JurnalItem.jurnal_id==row.di).delete()
                    DBSession.flush()

                #Menghapus TBP yang sudah menjadi jurnal
                DBSession.query(Jurnal).filter(Jurnal.source_no==kode,Jurnal.source=='TBP').delete()
                DBSession.flush()

            return self.route_list()
        return dict(row=row, form=form.render())

redpajama_set_name: RedPajamaGithub


text:
"""This tool builds or repacks the client binaries."""

import getpass
import glob
import logging
import multiprocessing
import os
import platform
import subprocess
import sys

from absl import app
from absl import flags
from absl.flags import argparse_flags
import distro

from grr_response_client_builder import build_helpers
from grr_response_client_builder import builders
from grr_response_client_builder import repacking
from grr_response_core import config as grr_config
from grr_response_core.config import contexts
from grr_response_core.lib import config_lib
from grr_response_core.lib import utils

# pylint: disable=unused-import
# Required for google_config_validator
from grr_response_core.lib.local import plugins

# pylint: enable=unused-import

FLAGS = flags.FLAGS

class Error(Exception):
  pass

class ErrorDuringRepacking(Error):
  pass

# This is an absl flag, and not an argparse flag, for backwards compatibility.
flags.DEFINE_bool(
    "verbose",
    default=False,
    help="Turn on verbose logging.",
    allow_override=True)

parser = argparse_flags.ArgumentParser(
    description="A tool for building client binaries.")

# Initialize sub parsers and their arguments.
subparsers = parser.add_subparsers(
    title="subcommands", dest="subparser_name", description="valid subcommands")

# generate config
parser_generate_config = subparsers.add_parser(
    "generate_client_config", help="Generate client config.")

parser_generate_config.add_argument(
    "--client_config_output",
    help="Filename to write output.",
    required=True,
    default=None)

# build arguments.
parser_build = subparsers.add_parser(
    "build", help="Build a client from source.")

parser_build.add_argument(
    "--output", default=None, help="The path to write the output template.")

# repack arguments
parser_repack = subparsers.add_parser(
    "repack", help="Build installer from a template.")

parser_repack.add_argument(
    "--debug_build",
    action="store_true",
    default=False,
    help="Build a debug installer.")

parser_repack.add_argument(
    "--sign",
    action="store_true",
    default=False,
    help="Sign installer binaries.")

parser_repack.add_argument(
    "--signed_template",
    action="store_true",
    default=False,
    help="Set to true if template was signed with sign_template. This is only "
    "necessary when repacking a windows template many times.")

parser_repack.add_argument(
    "--template",
    default=None,
    required=True,
    help="The template zip file to repack.")

parser_repack.add_argument(
    "--output_dir",
    default="",
    required=True,
    help="The directory to which we should write the "
    "output installer. Installers will be named "
    "automatically from config options.")

# repack_multiple arguments
parser_multi = subparsers.add_parser(
    "repack_multiple", help="Repack multiple templates with multiple configs.")

parser_multi.add_argument(
    "--sign",
    action="store_true",
    default=False,
    help="Sign installer binaries.")

parser_multi.add_argument(
    "--signed_template",
    action="store_true",
    default=False,
    help="Set to true if template was signed with sign_template. This is only "
    "necessary when repacking a windows template many times.")

parser_multi.add_argument(
    "--templates",
    default=None,
    required=True,
    nargs="+",
    help="The list of templates to repack. Use "
    "'--template /some/dir/*.zip' to repack "
    "all templates in a directory.")

parser_multi.add_argument(
    "--repack_configs",
    default=None,
    required=True,
    nargs="+",
    help="The list of repacking configs to apply. Use "
    "'--repack_configs /some/dir/*.yaml' to repack "
    "with all configs in a directory")

parser_multi.add_argument(
    "--output_dir",
    default=None,
    required=True,
    help="The directory where we output our installers.")

parser_signer = subparsers.add_parser(
    "sign_template",
    help="Sign client libraries in a client template."
    "Use this when you are repacking a windows template many times and "
    "need all binaries inside signed.")

parser_signer.add_argument(
    "--template", default=None, required=True, help="Template to sign.")

parser_signer.add_argument(
    "--output_file",
    default=None,
    required=True,
    help="Where to write the new template with signed libs.")

class TemplateBuilder(object):
  """Build client templates."""

  def GetBuilder(self, context):
    """Get instance of builder class based on flags."""
    try:
      if "Target:Darwin" in context:
        return builders.DarwinClientBuilder(context=context)
      elif "Target:Windows" in context:
        return builders.WindowsClientBuilder(context=context)
      elif "Target:LinuxDeb" in context:
        return builders.DebianClientBuilder(context=context)
      elif "Target:LinuxRpm" in context:
        return builders.CentosClientBuilder(context=context)
      else:
        parser.error("Bad build context: %s" % context)
    except AttributeError:
      raise RuntimeError("Unable to build for platform %s when running "
                         "on current platform." % self.platform)

  def GetArch(self):
    if platform.architecture()[0] == "32bit":
      return "i386"
    return "amd64"

  def GetPackageFormat(self):
    if platform.system() == "Linux":
      distro_id = distro.id()
      if distro_id in ["ubuntu", "debian"]:
        return "Target:LinuxDeb"
      elif distro_id in ["centos", "rhel", "fedora"]:
        return "Target:LinuxRpm"
      else:
        message = "Unknown distro '{}', can't determine package format"
        raise RuntimeError(message.format(distro_id))

  def BuildTemplate(self, context=None, output=None):
    """Find template builder and call it."""
    context = context or []
    context.append("Arch:%s" % self.GetArch())
    # Platform context has common platform settings, Target has template build
    # specific stuff.
    self.platform = platform.system()
    context.append("Platform:%s" % self.platform)
    context.append("Target:%s" % self.platform)
    if "Target:Linux" in context:
      context.append(self.GetPackageFormat())
    if ("Target:Windows" in context and
        grr_config.CONFIG["ClientBuilder.build_msi"]):
      # Include an additional context in the MSI template.
      # The repacker uses this context to chose the .msi extension for the
      # repacked installer.
      context.append("Target:WindowsMsi")

    template_path = None
    # If output is specified, place the built template file there, otherwise
    # use the default location prescribed by the config.
    if output:
      template_path = os.path.join(
          output,
          grr_config.CONFIG.Get(
              "PyInstaller.template_filename", context=context))
    else:
      template_path = grr_config.CONFIG.Get(
          "ClientBuilder.template_path", context=context)

    utils.EnsureDirExists(os.path.dirname(template_path))

    builder_obj = self.GetBuilder(context)
    builder_obj.MakeExecutableTemplate(template_path)

def SpawnProcess(popen_args, passwd=None):
  """Spawns a process."""
  if passwd is not None:
    # We send the password via pipe to avoid creating a process with the
    # password as an argument that will get logged on some systems.
    p = subprocess.Popen(popen_args, stdin=subprocess.PIPE)
    p.communicate(input=passwd)
  else:
    p = subprocess.Popen(popen_args)
    p.wait()
  if p.returncode != 0:
    raise ErrorDuringRepacking(" ".join(popen_args))

class MultiTemplateRepacker(object):
  """Helper class for repacking multiple templates and configs.

  This class calls client_build in a separate process for each repacking job.
  This greatly speeds up repacking lots of templates and also avoids the need to
  manage adding and removing different build contexts for each repack.

  This is only really useful if you have lots of repacking config
  customizations, such as many differently labelled clients.
  """

  def GetOutputDir(self, base_dir, config_filename):
    """Add the repack config filename onto the base output directory.

    This allows us to repack lots of different configs to the same installer
    name and still be able to distinguish them.

    Args:
      base_dir: output directory string
      config_filename: the secondary config filename string

    Returns:
      String to be used as output directory for this repack.
    """
    return os.path.join(base_dir,
                        os.path.basename(config_filename.replace(".yaml", "")))

  def GetWindowsPassphrase(self):
    try:
      return self._windows_passphrase
    except AttributeError:
      print("Enter passphrase for Windows code signing")
      self._windows_passphrase = getpass.getpass()
      return self._windows_passphrase

  def GetRPMPassPhrase(self):
    try:
      return self._rpm_passphrase
    except AttributeError:
      print("Enter passphrase for RPM code signing")
      self._rpm_passphrase = getpass.getpass()
      return self._rpm_passphrase

  def RepackTemplates(self,
                      repack_configs,
                      templates,
                      output_dir,
                      config=None,
                      sign=False,
                      signed_template=False):
    """Call repacker in a subprocess."""
    pool = multiprocessing.Pool(processes=10)
    results = []
    bulk_sign_installers = False
    for repack_config in repack_configs:
      for template in templates:
        repack_args = ["grr_client_build"]
        if config:
          repack_args.extend(["--config", config])

        repack_args.extend([
            "--secondary_configs", repack_config, "repack", "--template",
            template, "--output_dir",
            self.GetOutputDir(output_dir, repack_config)
        ])

        # We only sign exes and rpms at the moment. The others will raise if we
        # try to ask for signing.
        passwd = None

        if sign:
          if template.endswith(".exe.zip") or template.endswith(".msi.zip"):
            # This is for osslsigncode only.
            if platform.system() != "Windows":
              passwd = self.GetWindowsPassphrase()
              repack_args.append("--sign")
            else:
              if template.endswith(".msi.zip"):
                repack_args.append("--sign")
              else:
                bulk_sign_installers = True
            if signed_template:
              repack_args.append("--signed_template")
          elif template.endswith(".rpm.zip"):
            bulk_sign_installers = True

        print("Calling %s" % " ".join(repack_args))
        results.append(
            pool.apply_async(SpawnProcess, (repack_args,), dict(passwd=passwd)))

        # Also build debug if it's windows.
        if template.endswith(".exe.zip") or template.endswith(".msi.zip"):
          debug_args = []
          debug_args.extend(repack_args)
          debug_args.append("--debug_build")
          print("Calling %s" % " ".join(debug_args))
          results.append(
              pool.apply_async(SpawnProcess, (debug_args,),
                               dict(passwd=passwd)))

    try:
      pool.close()
      # Workaround to handle keyboard kills
      # http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool
      # get will raise if the child raises.
      for result_obj in results:
        result_obj.get(9999)
      pool.join()
    except KeyboardInterrupt:
      print("parent received control-c")
      pool.terminate()
    except ErrorDuringRepacking:
      pool.terminate()
      raise

    if bulk_sign_installers:
      to_sign = {}
      for root, _, files in os.walk(output_dir):
        for f in files:
          if f.endswith(".exe"):
            to_sign.setdefault("windows", []).append(os.path.join(root, f))
          elif f.endswith(".rpm"):
            to_sign.setdefault("rpm", []).append(os.path.join(root, f))
      if to_sign.get("windows"):
        signer = repacking.TemplateRepacker().GetSigner([
            "ClientBuilder Context",
            "Platform:%s" % platform.system(), "Target:Windows"
        ])
        signer.SignFiles(to_sign.get("windows"))
      if to_sign.get("rpm"):
        signer = repacking.TemplateRepacker().GetSigner([
            "ClientBuilder Context",
            "Platform:%s" % platform.system(), "Target:Linux", "Target:LinuxRpm"
        ])
        signer.AddSignatureToRPMs(to_sign.get("rpm"))

def GetClientConfig(filename):
  """Write client config to filename."""
  config_lib.SetPlatformArchContext()
  config_lib.ParseConfigCommandLine()
  context = list(grr_config.CONFIG.context)
  context.append("Client Context")
  # Disable timestamping so we can get a reproducible and cacheable config file.
  config_data = build_helpers.GetClientConfig(
      context, validate=True, deploy_timestamp=False)
  with open(filename, "w") as fd:
    fd.write(config_data)
    build_helpers.WriteBuildYaml(fd, build_timestamp=False, context=context)

def main(args):
  """Launch the appropriate builder."""

  grr_config.CONFIG.AddContext(contexts.CLIENT_BUILD_CONTEXT)

  if args.subparser_name == "generate_client_config":
    # We don't need a full init to just build a config.
    GetClientConfig(args.client_config_output)
    return

  # TODO(user): Find out if adding the client-builder context is still
  # necessary.
  context = FLAGS.context
  context.append(contexts.CLIENT_BUILD_CONTEXT)

  config_lib.SetPlatformArchContext()
  config_lib.ParseConfigCommandLine()

  # Use basic console output logging so we can see what is happening.
  logger = logging.getLogger()
  handler = logging.StreamHandler()
  handler.setLevel(logging.DEBUG if FLAGS.verbose else logging.INFO)
  logger.handlers = [handler]

  if args.subparser_name == "build":
    if grr_config.CONFIG["Client.fleetspeak_enabled"]:
      if grr_config.CONFIG.ContextApplied("Platform:Darwin"):
        if not grr_config.CONFIG.Get("ClientBuilder.install_dir"):
          raise RuntimeError("ClientBuilder.install_dir must be set.")
        if not grr_config.CONFIG.Get("ClientBuilder.fleetspeak_plist_path"):
          raise RuntimeError("ClientBuilder.fleetspeak_plist_path must be set.")
    TemplateBuilder().BuildTemplate(context=context, output=args.output)
  elif args.subparser_name == "repack":
    if args.debug_build:
      context.append("DebugClientBuild Context")
    result_path = repacking.TemplateRepacker().RepackTemplate(
        args.template,
        args.output_dir,
        context=context,
        sign=args.sign,
        signed_template=args.signed_template)

    if not result_path:
      raise ErrorDuringRepacking(" ".join(sys.argv[:]))
  elif args.subparser_name == "repack_multiple":

    # Resolve globs manually on Windows.
    templates = []
    for template in args.templates:
      if "*" in template:
        templates.extend(glob.glob(template))
      else:
        # This could go through glob but then we'd swallow errors for
        # non existing files.
        templates.append(template)

    repack_configs = []
    for repack_config in args.repack_configs:
      if "*" in repack_config:
        repack_configs.extend(glob.glob(repack_config))
      else:
        # This could go through glob but then we'd swallow errors for
        # non existing files.
        repack_configs.append(repack_config)

    MultiTemplateRepacker().RepackTemplates(
        repack_configs,
        templates,
        args.output_dir,
        config=FLAGS.config,
        sign=args.sign,
        signed_template=args.signed_template)
  elif args.subparser_name == "sign_template":
    repacking.TemplateRepacker().SignTemplate(
        args.template, args.output_file, context=context)
    if not os.path.exists(args.output_file):
      raise RuntimeError("Signing failed: output not written")

def Run():
  app.run(main, flags_parser=lambda argv: parser.parse_args(argv[1:]))

if __name__ == "__main__":
  Run()


text:
namespace blink {

class LocalDOMWindow;

class MODULES_EXPORT ManifestChangeNotifier
    : public GarbageCollected<ManifestChangeNotifier> {
 public:
  explicit ManifestChangeNotifier(LocalDOMWindow& window);
  virtual ~ManifestChangeNotifier();

  virtual void Trace(Visitor*);

  virtual void DidChangeManifest();

 private:
  void ReportManifestChange();
  void EnsureManifestChangeObserver();

  Member<LocalDOMWindow> window_;
  HeapMojoAssociatedRemote<mojom::blink::ManifestUrlChangeObserver>
      manifest_change_observer_;
  bool report_task_scheduled_ = false;

  DISALLOW_COPY_AND_ASSIGN(ManifestChangeNotifier);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_MANIFEST_MANIFEST_CHANGE_NOTIFIER_H_


text:
package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"strconv"

	"golang.org/x/net/websocket"
)

var (
	source   string
	port     int
	channels []chan string
)

func arguments() {
	flag.StringVar(&source, "s", "", "the source websocket e.g. 10.0.0.5:8000")
	flag.IntVar(&port, "p", 8000, "port to accept websocket connections")
	flag.Parse()

	if envSource := os.Getenv("SOURCE"); envSource != "" {
		source = envSource
	}

	if envPort := os.Getenv("PORT"); envPort != "" {
		p, _ := strconv.Atoi(envPort)
		port = p
	}
}

func stream(ws *websocket.Conn) {
	fmt.Println("New connection from", ws.Request().RemoteAddr)
	c := make(chan string)
	channels = append(channels, c)
	for ascii := range c {
		websocket.Message.Send(ws, ascii)
	}
	ws.Close()
}

func receive() {

	var message string
	url := fmt.Sprintf("ws://%s/", source)
	ws, err := websocket.Dial(url, "", "http://localhost/")

	if err != nil {
		fmt.Println("Could not connect")
		os.Exit(1)
	}

	for {
		if nil != websocket.Message.Receive(ws, &message) {
			fmt.Println("Connection lost to ", source)
			break
		}
		for _, ch := range channels {
			ch <- message
		}
	}
}

func main() {
	arguments()

	fmt.Println("Settings")
	fmt.Println("  Source:", source)
	fmt.Println("  Port:", port)

	go receive()

	// create a websocket server
	http.Handle("/", websocket.Handler(stream))
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}


text:
using System;
using System.Linq;

namespace Microsoft.Azure.Management.DataFactories.Core.Registration.Models
{
    /// <summary>
    /// Parameters specifying how to return a ComputeType definition for a Get
    /// operation.
    /// </summary>
    public partial class ComputeTypeGetParameters
    {
        private string _computeTypeName;

        /// <summary>
        /// Required. A ComputeType name.
        /// </summary>
        public string ComputeTypeName
        {
            get { return this._computeTypeName; }
            set { this._computeTypeName = value; }
        }

        private string _registrationScope;

        /// <summary>
        /// Required. The scope for which to get a ComputeType definition.
        /// </summary>
        public string RegistrationScope
        {
            get { return this._registrationScope; }
            set { this._registrationScope = value; }
        }

        /// <summary>
        /// Initializes a new instance of the ComputeTypeGetParameters class.
        /// </summary>
        public ComputeTypeGetParameters()
        {
        }

        /// <summary>
        /// Initializes a new instance of the ComputeTypeGetParameters class
        /// with required arguments.
        /// </summary>
        public ComputeTypeGetParameters(string registrationScope, string computeTypeName)
            : this()
        {
            if (registrationScope == null)
            {
                throw new ArgumentNullException("registrationScope");
            }
            if (computeTypeName == null)
            {
                throw new ArgumentNullException("computeTypeName");
            }
            this.RegistrationScope = registrationScope;
            this.ComputeTypeName = computeTypeName;
        }
    }
}


text:
"""Switch between depending on pyglib.app or an OSS replacement."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=unused-import
# pylint: disable=g-import-not-at-top
# pylint: disable=wildcard-import
import tensorflow.python.platform
from . import control_imports
if control_imports.USE_OSS and control_imports.OSS_APP:
  from tensorflow.python.platform.default._app import *
else:
  from tensorflow.python.platform.google._app import *

# Import 'flags' into this module
from tensorflow.python.platform import flags


text:
<?php

namespace Zotlabs\Update;

class _1031 {
function run() {
	$r = q("ALTER TABLE `account` ADD `account_external` CHAR( 255 ) NOT NULL DEFAULT '' AFTER `account_email` ,
ADD INDEX ( `account_external` )");
	if($r)
		return UPDATE_SUCCESS;
	return UPDATE_FAILED;
}

}


text:
typedef unsigned int mode_t;
typedef unsigned long ino_t;
typedef unsigned long long dev_t;
typedef unsigned int nlink_t;
typedef unsigned int uid_t;
typedef unsigned int gid_t;
typedef long off_t;
typedef int blksize_t;
typedef int blkcnt_t;

typedef long time_t;
struct timespec {
	time_t	tv_sec;
	long	tv_nsec;
};

struct stat {
	dev_t st_dev;
	unsigned int pad1;
	ino_t st_ino;
	mode_t st_mode;
	nlink_t st_nlink;
	uid_t st_uid;
	gid_t st_gid;
	dev_t st_rdev;
	unsigned int pad2;
	off_t st_size;
	blksize_t st_blksize;
	blkcnt_t st_blocks;
	timespec st_atime;
	timespec st_mtime;
	timespec st_ctime;
	unsigned pad4;
	unsigned pad5;
};


text: gunicorn -c gun_config.py server:app


text:
<?php

namespace AcademyHQ\API\Repository\ConnectedRMS;

use AcademyHQ\API\ValueObjects as VO;
use AcademyHQ\API\HTTP\Request\Request as Request;
use Guzzle\Http\Client as GuzzleClient;
use AcademyHQ\API\Common\Credentials;

class MemberApiRepository {

	private $base_url = 'https://api.academyhq.com/api/v2/crms';

	public function __construct(Credentials $credentials)
	{
		$this->credentials = $credentials;
	}

	public function get_members(
		VO\StringVO $search=null,
		VO\Integer $current_page
	){
		$request = new Request(
			new GuzzleClient,
			$this->credentials,
			VO\HTTP\Url::fromNative($this->base_url.'/members/get'),
			new VO\HTTP\Method('POST')
		);

		$request_parameters = array(
			'search' => $search ? $search->__toString() : '',
			'current_page' => $current_page->__toInteger()
		);

		$response = $request->send($request_parameters);

		$data = $response->get_data();

		return $data;
	}

}


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

    <string-array name="rss_settings_array_auto_lock_times">
        <item>1 minute</item>
        <item>5 minutes</item>
        <item>10 minutes</item>
        <item>15 minutes</item>
        <item>30 minutes</item>
        <item>45 minutes</item>
    </string-array>

    <string-array name="rss_settings_array_auto_lock_times_values">
        <item>1</item>
        <item>5</item>
        <item>10</item>
        <item>15</item>
        <item>30</item>
        <item>45</item>
    </string-array>

</resources>


text:
using Newtonsoft.Json;
using System.Collections.Generic;

namespace Gfycat.API
{
    internal class FollowersResponse
    {
        [JsonProperty("followers")]
        internal IEnumerable<string> Followers { get; set; }
    }
}


text:
package com.amdelamar.action.api;

import java.util.Map;

import com.amdelamar.config.Application;
import com.amdelamar.config.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.ext.web.RoutingContext;

/**
 * Forgot action class
 *
 * @author amdelamar
 * @date 12/19/2016
 */
public class ForgotAction implements Handler<RoutingContext> {

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

    private Map<String, Object> sessionAttributes = null;
    private String email; // need email to send reminders or resets
    private String code;
    private String type; // 'username' or 'password' or 'twofactor'

    private boolean remind; // true if they forgot username
    private boolean reset; // true if they forgot password
    private boolean recover; // true if they forgot two factor

    protected int lockout = 30; // minutes
    protected int maxAttempts = 3;
    private int attempts = 0;
    private long lastAttempt = 0;

    // JSON response
    private String forgot;
    private String error;
    private String message;
    private Map<String, String> data;

    /**
     * Forgot user/password action. Resets a password via email.
     */
    @Override
    public void handle(RoutingContext context) {

        // Don't handle if response ended
        if (context.response().ended() || context.response().closed()) {
            return;
        }

        JsonObject json = new JsonObject();
        try {
            defaults();
            // check if locked out
            // check inputs
            if (!isLockedOut(context) && validParameters()) {

                // if email is good, and remind, then send reminder email.
                // TODO

                // if email is good, and reset, then send email link to reset
                // password.
                // Generate a unique token that can only be used once.
                // TODO

                if (remind) {
                    message = "You have been sent a reminder. Please check your inbox for your Username.";
                } else if (reset) {
                    message = "You have been sent a reset token. Please check your inbox to reset your password.";
                } else if (recover) {
                    message = "You have been sent a recovery token. Please check your inbox to login.";
                }
                json.put("forgot", "ok");
                json.put("message", message);

                JsonObject data = new JsonObject();
                data.put("email", email);
                data.put("time", Utils.getDateIso8601());
                json.put("data", data);

                context.session()
                        .remove("attempts");
                context.session()
                        .remove("lastAttempt");
            }

        } catch (Exception e) {
            logger.warn("Forgot: " + json.encode());
            json.put("error", true);
            json.put("message", e.getMessage());
        }

        // return response
        logger.info(message);
        context.response()
                .putHeader("Cache-Control", "no-store, no-cache")
                .putHeader("content-type", "application/json; charset=UTF-8")
                .end(json.encode());
    }

    /**
     * Get the default parameters for lockout, if available. Otherwise use defaults.
     */
    protected void defaults() {
        try {
            maxAttempts = Application.getInt("apiMaxAttempts");
            lockout = Application.getInt("apiLockoutInMin");
        } catch (Exception e) {
            // quitely ignore
            maxAttempts = 3;
            lockout = 30;
        }
    }

    /**
     * Check email parameter.
     *
     * @return true if ok
     * @throws Exception if invalid
     */
    protected boolean validParameters() throws Exception {
        if (code != null && code.isEmpty()) {
            throw new IllegalArgumentException("Invalid or missing code.");
        } else if (code != null && code.length() > 6) {
            throw new IllegalArgumentException("Code cannot be greater than 6 digits.");
        } else if (email == null || email.isEmpty()) {
            throw new IllegalArgumentException("Invalid or missing email.");
        } else if (!Utils.isValidEmail(email)) {
            throw new IllegalArgumentException("Invalid email address. Double-check and try again.");
        } else if (!remind && !reset && !recover) {
            throw new IllegalArgumentException(
                    "Missing expected boolean option. Please add remind, reset, or recover.");
        } else {
            return true;
        }
    }

    /**
     * Check if the user has attempted too many times, and lock them out if they have.
     *
     * @return true if locked out
     * @throws IllegalArgumentException if locked out
     */
    protected boolean isLockedOut(RoutingContext context) throws IllegalArgumentException {
        // count login attempts
        // and remember when their last attempt was
        if (sessionAttributes.get("attempts") == null) {
            attempts = 1;
        } else {
            attempts = (int) sessionAttributes.get("attempts");
            attempts++;
        }
        if (sessionAttributes.get("lastAttempt") == null) {
            lastAttempt = System.currentTimeMillis();
        } else {
            lastAttempt = (long) sessionAttributes.get("lastAttempt");
        }
        sessionAttributes.put("attempts", attempts);
        sessionAttributes.put("lastAttempt", lastAttempt);

        // lockout for 30 min, if they failed 3 times
        if (attempts >= maxAttempts) {

            if (System.currentTimeMillis() >= (lastAttempt + (lockout * 60 * 1000))) {
                // its been 30mins or more, so unlock
                sessionAttributes.remove("attempts");
                sessionAttributes.remove("lastAttempt");
                logger.error("Unknown user has waited " + lockout + " min, proceed. (" + context.request()
                        .remoteAddress() + ")");
                return false;
            } else {
                // they have already been locked out
                logger.error("Unknown user has been locked out for " + lockout + " min. (" + context.request()
                        .remoteAddress() + ") ");
                throw new IllegalArgumentException(
                        "You have been locked out for the next " + lockout + " minutes, for too many attempts.");
            }
        }
        return false;
    }

    public void setSession(Map<String, Object> sessionAttributes) {
        this.sessionAttributes = sessionAttributes;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = Utils.removeBadChars(code);
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        String type2 = type;
        if (type2 == null) {
            type2 = "username";
        }
        this.type = Utils.removeBadChars(type2);
    }

    public int getAttempts() {
        return attempts;
    }

    public boolean isRemind() {
        return remind;
    }

    public void setRemind(boolean remind) {
        this.remind = remind;
    }

    public boolean isReset() {
        return reset;
    }

    public void setReset(boolean reset) {
        this.reset = reset;
    }

    public boolean isRecover() {
        return recover;
    }

    public void setRecover(boolean recover) {
        this.recover = recover;
    }

    public String getForgot() {
        return forgot;
    }

    public void setForgot(String forgot) {
        this.forgot = forgot;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, String> getData() {
        return data;
    }

    public void setData(Map<String, String> data) {
        this.data = data;
    }

}


text:
package vg.civcraft.mc.namelayer;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

import com.google.common.collect.Maps;

import vg.civcraft.mc.namelayer.database.GroupManagerDao;
import vg.civcraft.mc.namelayer.events.GroupCreateEvent;
import vg.civcraft.mc.namelayer.events.GroupDeleteEvent;
import vg.civcraft.mc.namelayer.events.GroupMergeEvent;
import vg.civcraft.mc.namelayer.events.GroupTransferEvent;
import vg.civcraft.mc.namelayer.group.Group;
import vg.civcraft.mc.namelayer.misc.Mercury;
import vg.civcraft.mc.namelayer.permission.GroupPermission;
import vg.civcraft.mc.namelayer.permission.PermissionHandler;
import vg.civcraft.mc.namelayer.permission.PermissionType;

public class GroupManager{

	private static GroupManagerDao groupManagerDao;
	private PermissionHandler permhandle;

	private static Map<String, Group> groupsByName = new ConcurrentHashMap<String, Group>();
	private static Map<Integer, Group> groupsById = new ConcurrentHashMap<Integer, Group>();

	public GroupManager(){
		groupManagerDao = NameLayerPlugin.getGroupManagerDao();
		permhandle = new PermissionHandler();
	}

	/**
	 * Saves the group into caching and saves it into the db. Also fires the GroupCreateEvent.
	 * @param The group to create to db.
	 */
	public int createGroup(Group group){
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group create failed, caller passed in null", new Exception());
			return -1;
		}
		GroupCreateEvent event = new GroupCreateEvent(
				group.getName(), group.getOwner(),
				group.getPassword());
		Bukkit.getPluginManager().callEvent(event);
		if (event.isCancelled()){
			NameLayerPlugin.log(Level.INFO, "Group create was cancelled for group: " + group.getName());
			return -1;
		}
		int id = groupManagerDao.createGroup(
				event.getGroupName(), event.getOwner(),
				event.getPassword());
		if (id > -1) {
			initiateDefaultPerms(event.getGroupName()); // give default perms to a newly create group
			GroupManager.getGroup(id); // force a recache from DB.
			/*group.setGroupIds(groupManagerDao.getAllIDs(event.getGroupName()));
			group.addMember(event.getOwner(), PlayerType.OWNER);
			groupsByName.put(event.getGroupName(), group);
			for (int q : group.getGroupIds()) {
				groupsById.put(q, group);
			}*/
		}
		return id;
	}

	public boolean deleteGroup(String groupName){
		if (groupName == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group delete failed, caller passed in null", new Exception());
			return false;
		}
		groupName = groupName.toLowerCase();
		Group group = getGroup(groupName);
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group delete failed, failed to find group " + groupName);
			return false;
		}

		// Call once w/ finished false to allow cancellation.
		GroupDeleteEvent event = new GroupDeleteEvent(group, false);
		Bukkit.getPluginManager().callEvent(event);
		if (event.isCancelled()) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group delete was cancelled for "+ groupName);
			return false;
		}

		// Unlinks subgroups.
		group.prepareForDeletion();
		deleteGroupPerms(group);
		groupManagerDao.deleteGroup(groupName);
		groupsByName.remove(groupName);
		for (int id : group.getGroupIds()) {
			groupsById.remove(id);
		}

		// Call after actual delete to alert listeners that we're done.
		event = new GroupDeleteEvent(group, true);
		Bukkit.getPluginManager().callEvent(event);

		group.setDisciplined(true);
		group.setValid(false);

		if (NameLayerPlugin.isMercuryEnabled()){
			String message = "delete " + groupName;
			Mercury.invalidateGroup(message);
		}
		return true;
	}

	public void transferGroup(Group g, UUID uuid){
		if (g == null || uuid == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group transfer failed, caller passed in null", new Exception());
			return;
		}

		GroupTransferEvent event = new GroupTransferEvent(g, uuid);
		Bukkit.getPluginManager().callEvent(event);
		if (event.isCancelled()){
			NameLayerPlugin.log(Level.INFO, "Group transfer event was cancelled for group: " + g.getName());
			return;
		}
		g.addMember(uuid, PlayerType.OWNER);
		g.setOwner(uuid);
		if (NameLayerPlugin.isMercuryEnabled()){
			String message = "transfer " + g.getName();
			Mercury.invalidateGroup(message);
		}
	}

	public void mergeGroup(final Group group, final Group toMerge){
		if (group == null || toMerge == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group merge failed, caller passed in null", new Exception());
			return;
		} else if (group == toMerge || group.getName().equalsIgnoreCase(toMerge.getName())) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group merge failed, caller passed in null", new Exception());
			return;
		}
		GroupMergeEvent event = new GroupMergeEvent(group, toMerge, false);
		Bukkit.getPluginManager().callEvent(event);
		if (event.isCancelled()){
			NameLayerPlugin.log(Level.INFO, "Group merge event was cancelled for groups: " +
					group.getName() + " and " + toMerge.getName());
			return;
		}

		groupManagerDao.mergeGroup(group.getName(), toMerge.getName());
		// At this point, at the DB level all non-overlap members are in target group, name is reset to target,
		// unique group header record is removed, and faction_id all point to new name.
		/*deleteGroup(toMerge.getName());
		// b/c cache isn't clear yet, this works.
		// Delete the actual subgroup links from old group
		// Uncaches permissions
		// Attempts to "delete" group (move to special) but can't b/c name is already removed.
		//   Consequently the subgroups, permissions, and blacklist will be unaltered.
		// Removes toMerge from cache.
		// "Disciplines" the memory-copy and sets to invalid.
		 */
		// deleteGroup was wasteful. Pulled the only things it did of value out and put them here:
		if (toMerge.getSuperGroup() != null) {
			Group sup = toMerge.getSuperGroup();
			Group.unlink(sup, toMerge); // need to unlink any supergroup from merge.
			invalidateCache(sup.getName());
		}
		// Merge brings subgroups with, but unlinks the toMerge group out from under any supergroup it had.
		//toMerge.prepareForDeletion();
		for (Group subMerge : toMerge.getSubgroups()) {
			Group.link(group, subMerge, false);
			invalidateCache(subMerge.getName());
		}
		deleteGroupPerms(toMerge);
		toMerge.setDisciplined(true);
		invalidateCache(toMerge.getName()); // Removes merge group from cache & invalidates object
		invalidateCache(group.getName()); // Means next access will requery the group, good.

		event = new GroupMergeEvent(group, toMerge, true);
		Bukkit.getPluginManager().callEvent(event);
		//toMerge.setDisciplined(true); // duplicate action, toMerge is set to discipline by deleteGroup()
		// Fail safe for plugins that don't check if the group is valid or not.
		if (NameLayerPlugin.isMercuryEnabled()){
			String message = "merge " + group.getName() + " " + toMerge.getName();
			Mercury.invalidateGroup(message);
		}
	}

	public static List<Group> getSubGroups(String name) {
		if (name == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Group getSubGroups event failed, caller passed in null", new Exception());
			return new ArrayList<Group>();
		}

		List<Group> groups = groupManagerDao.getSubGroups(name);
		for (Group group : groups) {
			groupsByName.put(group.getName().toLowerCase(), group);
			for (int j : group.getGroupIds()){
				groupsById.put(j, group);
			}
		}
		return groups;
	}

	/*
	 * Making this static so I can use it in other places without needing the GroupManager Object.
	 * Saves me code so I can always grab a group if it is already loaded while not needing to check db.
	 */
	public static Group getGroup(String name){
		if (name == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getGroup failed, caller passed in null", new Exception());
			return null;
		}

		String lower = name.toLowerCase();
		if (groupsByName.containsKey(lower)) {
			return groupsByName.get(lower);
		} else {
			Group group = groupManagerDao.getGroup(name);
			if (group != null) {
				groupsByName.put(lower, group);
				for (int j : group.getGroupIds()){
					groupsById.put(j, group);
				}
			} else {
				NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getGroup by Name failed, unable to find the group " + name);
			}
			return group;
		}
	}

	public static Group getGroup(int groupId){
		if (groupsById.containsKey(groupId)) {
			return groupsById.get(groupId);
		} else {
			Group group = groupManagerDao.getGroup(groupId);
			if (group != null) {
				groupsByName.put(group.getName().toLowerCase(), group);
				for (int j : group.getGroupIds()){
					groupsById.put(j, group);
				}
			} else {
				NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getGroup by ID failed, unable to find the group " + groupId);
			}
			return group;
		}
	}

	public static boolean hasGroup(String groupName) {
		if (groupName == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "HasGroup Name failed, name was null ", new Exception());
			return false;
		}

		if (!groupsByName.containsKey(groupName.toLowerCase())) {
			return (getGroup(groupName.toLowerCase()) != null);
		} else {
			return true;
		}
	}

	/**
	 * Returns the admin group for groups if the group was found to be null.
	 * Good for when you have to have a group that can't be null.
	 * @param name - The group name for the group
	 * @return Either the group or the special admin group.
	 */
	public static Group getSpecialCircumstanceGroup(String name){
		if (name == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getSpecialCircumstance failed, caller passed in null", new Exception());
			return null;
		}
		String lower = name.toLowerCase();
		if (groupsByName.containsKey(lower)) {
			return groupsByName.get(lower);
		} else {
			Group group = groupManagerDao.getGroup(name);
			if (group != null) {
				groupsByName.put(lower, group);
				for (int j : group.getGroupIds()){
					groupsById.put(j, group);
				}
			} else {
				group = groupManagerDao.getGroup(NameLayerPlugin.getSpecialAdminGroup());
			}
			return group;
		}
	}

	/**
	 * DO NOT WORK WITH THE PERMISSION OBJECT ITSELF TO DETERMINE ACCESS. Use the methods provided in this class instead, as they
	 * respect all the permission inheritation stuff
	 */
	public GroupPermission getPermissionforGroup(Group group){
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getPermissionForGroup failed, caller passed in null", new Exception());
			return null;
		}
		return permhandle.getGroupPermission(group);
	}

	public boolean hasAccess(String groupname, UUID player, PermissionType perm) {
		if (groupname == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "hasAccess failed (access denied), could not find group " + groupname);
			return false;
		}
		return hasAccess(getGroup(groupname), player, perm);
	}

	public boolean hasAccess(Group group, UUID player, PermissionType perm) {
		Player p = Bukkit.getPlayer(player);
		if (p != null && (p.isOp() || p.hasPermission("namelayer.admin"))) {
			return true;
		}
		if (group == null || player == null || perm == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "hasAccess failed, caller passed in null", new Exception());
			return false;
		}
		if (!group.isValid()) {
			group = getGroup(group.getName());
			if (group == null) {
				//what happened? who knows?
				return false;
			}
		}
		GroupPermission perms = getPermissionforGroup(group);
		for(PlayerType rank : getRecursivePlayerTypes(group, player)) {
			if (perms.hasPermission(rank, perm)) {
				//player has right rank in the group itself or at least one super group
				return true;
			}
		}
		return false;
	}

	private List<PlayerType> getRecursivePlayerTypes(Group group, UUID player) {
		List<PlayerType> perms = new LinkedList<PlayerType>();
		PlayerType type = group.getPlayerType(player);
		if (type != null) {
			perms.add(type);
		}
		if (group.hasSuperGroup()) {
			perms.addAll(getRecursivePlayerTypes(group.getSuperGroup(), player));
		}
		return perms;
	}

	// == PERMISSION HANDLING ============================================================= //

	private void deleteGroupPerms(Group group){
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "deleteGroupPerms failed, caller passed in null", new Exception());
			return;
		}
		permhandle.deletePerms(group);
	}

	public List<String> getAllGroupNames(UUID uuid){
		if (uuid == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getAllGroupNames failed, caller passed in null", new Exception());
			return new ArrayList<String>();
		}
		return groupManagerDao.getGroupNames(uuid);
	}

	private void initiateDefaultPerms(String group){
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "initiateDefaultPerms failed, caller passed in null", new Exception());
			return;
		}
		Map <PlayerType, List <PermissionType>> defaultPermMapping = new HashMap<GroupManager.PlayerType, List<PermissionType>>();
		for(PermissionType perm : PermissionType.getAllPermissions()) {
			for(PlayerType type : perm.getDefaultPermLevels()) {
				List <PermissionType> perms = defaultPermMapping.get(type);
				if (perms == null) {
					perms = new LinkedList<PermissionType>();
					defaultPermMapping.put(type, perms);
				}
				perms.add(perm);
			}
		}
		for (Entry <PlayerType, List <PermissionType>> entry: defaultPermMapping.entrySet()){
			groupManagerDao.addPermission(group, entry.getKey().name(), entry.getValue());
		}
	}

	public String getDefaultGroup(UUID uuid){
		if (uuid == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getDefaultGroup was cancelled, caller passed in null", new Exception());
			return null;
		}
		return NameLayerPlugin.getDefaultGroupHandler().getDefaultGroup(uuid);
	}

	/**
	 * Invalidates a group from cache.
	 * @param group
	 */
	public void invalidateCache(String group){
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "invalidateCache failed, caller passed in null", new Exception());
			return;
		}

		Group g = groupsByName.get(group.toLowerCase());
		if (g != null) {
			g.setValid(false);
			List<Integer>k = g.getGroupIds();
			groupsByName.remove(group.toLowerCase());
			NameLayerPlugin.getBlackList().removeFromCache(g.getName());

			boolean fail = true;
			// You have a freaking hashmap, use it.
			for (int j : k) {
				if (groupsById.remove(j) != null) {
					fail = false;
				}
			}

			// FALLBACK is hardloop
			if (fail) { // can't find ID or cache is wrong.
				for (Group x: groupsById.values()) {
					if (x.getName().equals(g.getName())) {
						groupsById.remove(x.getGroupId());
					}
				}
			}
		} else {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "Invalidate cache by name failed, unable to find the group " + group);
		}
	}

	public int countGroups(UUID uuid){
		if (uuid == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "countGroups failed, caller passed in null", new Exception());
			return 0;
		}
		return groupManagerDao.countGroups(uuid);
	}

	public Timestamp getTimestamp(String group){
		if (group == null) {
			NameLayerPlugin.getInstance().getLogger().log(Level.INFO, "getTimeStamp failed, caller passed in null", new Exception());
			return null;
		}

		return groupManagerDao.getTimestamp(group);
	}

	/**
	 * In ascending order
	 * Add an enum here if you wish to add more than the four default tiers of
	 * roles.
	 */
	public enum PlayerType{
		MEMBERS,
		MODS,
		ADMINS,
		OWNER,
		NOT_BLACKLISTED;//anyone, who is not blacklisted

		private final static Map<String, PlayerType> BY_NAME = Maps.newHashMap();

		static {
			for (PlayerType rank : values()) {
				BY_NAME.put(rank.name(), rank);
			}
		}

		public static PlayerType getPlayerType(String type){
			return BY_NAME.get(type.toUpperCase());
		}

		public static String getStringOfTypes() {
			StringBuilder ranks = new StringBuilder();
			for (String rank: BY_NAME.keySet()) {
				ranks.append(rank);
				ranks.append(" ");
			}
			return ranks.toString();
		}

		public static void displayPlayerTypes(Player p) {
			p.sendMessage(ChatColor.RED
					+ "That PlayerType does not exists.\n"
					+ "The current types are: " + getStringOfTypes());
		}

		public static void displayPlayerTypesnllpt(Player p) {
			p.sendMessage(ChatColor.GREEN
					+ "The current types are: " + getStringOfTypes());
			//dont yell at player for nllpt
		}

		public static PlayerType getByID(int id) {
			switch(id) {
			case 0:
				return PlayerType.NOT_BLACKLISTED;
			case 1:
				return PlayerType.MEMBERS;
			case 2:
				return PlayerType.MODS;
			case 3:
				return PlayerType.ADMINS;
			case 4:
				return PlayerType.OWNER;
			default:
				return null;
			}
		}

		public static int getID(PlayerType type) {
			if (type == null) {
				return -1;
			}
			switch (type) {
				case NOT_BLACKLISTED:
					return 0;
				case MEMBERS:
					return 1;
				case MODS:
					return 2;
				case ADMINS:
					return 3;
				case OWNER:
					return 4;
				default:
					return -1;
			}
		}

		public static String getNiceRankName(PlayerType pType) {
			if (pType == null) {
				return "RANK_ERROR";
			}
			switch (pType) {
			case MEMBERS:
				return "Member";
			case MODS:
				return "Mod";
			case ADMINS:
				return "Admin";
			case OWNER:
				return "Owner";
			case NOT_BLACKLISTED:
				return "Anyone who is not blacklisted";
			}
			return "RANK_ERROR";
		}
	}
}


text:
var logger = require('npmlog');

class Plugin {
    constructor(settings) {
        this.settings = settings;
        this.init();
    }

    init() { }

    canHandle() {
        return false;
    }

    process(url) {
        logger.verbose(this.constructor.name, `Processing ${url}`);
        return this.run(url);
    }

    run() {
        return Promise.reject(new Error('Not implemented'));
    }
}

Plugin.isUrlTransformer = false; // When true, automatically sets priority as 2: Super high
Plugin.priority = 0; // Values: -1: Low, 0: Normal, 1: High

module.exports = Plugin;


text:
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>

#include "asyncxmlstream.h"

using namespace std;

/**
* Конструктор
*/
AsyncXMLStream::AsyncXMLStream(int afd): AsyncStream(afd)
{
}

/**
* Деструктор
*/
AsyncXMLStream::~AsyncXMLStream()
{
}

/**
* Обработчик прочитанных данных
*/
void AsyncXMLStream::onRead(const char *data, size_t len)
{
	parseXML(data, len, false);
}

/**
* Обработчик ошибок парсера
*/
void AsyncXMLStream::onParseError(const char *message)
{
	onError(message);
}

/**
* Пир (peer) закрыл поток.
*
* Мы уже ничего не можем отправить в ответ,
* можем только корректно закрыть соединение с нашей стороны.
*/
void AsyncXMLStream::onPeerDown()
{
	fprintf(stderr, "AsyncXMLStream[%d]: peer down\n", getFd());

	// и сообщаем парсеру об EOF
	parseXML(0, 0, true);
}


text:
package com.huawei.esdk.fusioncompute.local.impl.utils;

public class LogConfig
{

    // 敏感词替换后的String
    static String replaceWord = "******";

    // 当前业务
    public static final String product = LogUtil.ProductType_FC_R5;

    // 敏感词接口url
    private static final String[] sensitiveWordUrl = {"/service/sites/<ID>/vms/action/import",//导入模板 POST
        "/service/sites/<ID>/vms/<ID>/action/export",//导出模板 POST
        "/service/sites/<ID>/vmcustomizations", //虚拟机自定义规范 POST
        "/service/sites/<ID>/vms/<ID>", //虚拟机修改 PUT
        "/service/sites/<ID>/vms/<ID>/action/clone",//虚拟机克隆 POST
        "/service/sites/<ID>/vms",//创建虚拟机 POST
        "/service/sites/<ID>/hosts" //创建主机 POST
    };

    // 敏感词
    private static final String[] sensitiveWords = {"vncPassword", "vncOldPassword", "password", "domainPassword",
        "bmcPassword"};

    // 当前业务涉及敏感词的处理
    public static boolean checkUrl(String url)
    {

        for (String str : sensitiveWordUrl)
        {

            // 任何一条全部匹配就是返回结果
            boolean blnContain = true;

            String[] strArr = str.split("<ID>");

            for (String strPart : strArr)
            {

                if (!url.contains(strPart))
                {

                    blnContain = false;
                }
            }

            if (blnContain)
            {
                return blnContain;
            }
        }

        return false;
    }

    // 当前业务涉及敏感词的处理
    public static String replaceWord(String str)
    {
        str = (null == str ? "" : str);
        // 前提:敏感词不包含数字  结构体都是 "敏感词":"Value"
        StringBuffer strNew = new StringBuffer(str);
        // "vncPassword":""  "password":""
        String sensitiveStr = str;
        //是否替换敏感字符
        boolean flag = false;
        for (String sensitiveWord : sensitiveWords)
        {
            // now sensitivestr is "vncPassword":"
            sensitiveWord = "\"" + sensitiveWord + "\":\"";
            int i = 0;
            while (null != sensitiveStr && sensitiveStr.contains(sensitiveWord))
            {
                //替换敏感字符中间变量
                StringBuffer tempBuffer = new StringBuffer();
                flag = true;
                // "vncPassword":"截取到这里
                tempBuffer.append(sensitiveStr.substring(0, sensitiveStr.indexOf(sensitiveWord)))
                    .append(sensitiveWord)
                    .append(replaceWord)
                    .append("\"");
                i++;
                // strBuffer = "vncPassword":"*******
                sensitiveStr = sensitiveStr.substring(sensitiveStr.indexOf(sensitiveWord));
                // strBuffer = *******"********
                sensitiveStr = sensitiveStr.substring(sensitiveWord.length());
                // strBuffer = ************
                if (sensitiveStr.indexOf("\"") != -1)
                {
                    sensitiveStr = sensitiveStr.substring(sensitiveStr.indexOf("\"") + 1);
                }
                //第一次替换时,直接赋值;多次替换,做字符串拼接
                if (1 == i)
                {
                    strNew = tempBuffer;
                }
                else
                {
                    strNew = strNew.append(tempBuffer);
                }
            }

            if (flag)
            {
                sensitiveStr = strNew.append(sensitiveStr).toString();
                flag = false;
            }
        }

        return strNew.toString();
    }
}


text:
module Blog.Widgets.StreamOfConsciousness.TwitterNanny ( start_twitter_nanny ) where

import qualified Control.Monad as CM
import Blog.Widgets.StreamOfConsciousness.Controller ( Worker ( .. )
                                                     , SoCController )

import qualified System.Log.Logger as L

import Network.HTTP
import Network.HTTP.Headers
import Network.URI ( parseURI )
import Data.Maybe ( fromJust )

import Text.JSON

import qualified Codec.Binary.Base64.String as B64

import Blog.Widgets.JsonUtilities

import Blog.BackEnd.HttpPoller

nanny_period :: Int
nanny_period = 60 * 10^6 -- supposedly cheap.

log_handle :: String
log_handle = "TwitterNanny"

start_twitter_nanny :: SoCController -> [(Worker,Int)] -> String -> String -> IO Worker
start_twitter_nanny socc kids user password = do { let req = build_request user password
                                                 ; p <- start_poller log_handle req (handle_throttle kids) nanny_period
                                                 ; return $ Worker socc p }

build_request :: String -> String -> Request String
build_request user password = Request uri GET heads ""
    where
      uri = fromJust $ parseURI $ "http://twitter.com/account/rate_limit_status.json"
      heads = [ Header HdrAuthorization $ (++) "Basic " $ B64.encode $ user ++ ":" ++ password ]

handle_throttle :: [(Worker,Int)] -> String -> IO ()
handle_throttle ws body = case parse_utf8_json body of
                            Right v@(JSObject _) ->
                                compute_new_delays ws v
                            Right _ ->
                                L.errorM log_handle $ "Unexpected non-object JSON response that starts with: "
                                     ++ (take 100 body) ++ " [...]"
                            Left err_message ->
                                L.errorM log_handle err_message

compute_new_delays :: [(Worker,Int)] -> JSValue -> IO ()
compute_new_delays _ v = do { let throttle = unn $ v </> "remaining_hits"
                             ; L.infoM log_handle $ "Twitter throttle is " ++ (show throttle) ++ " requests per hour."
                             }


text:
using System;
using System.IO;

namespace Id3Lib.Frames
{
    [Frame("UFID")]
    internal class FrameUniqueIdentifier : FrameBase, IFrameDescription
    {
        #region Ïîëÿ

        private string _description;

        private byte[] _identifer;

        #endregion

        #region Ñâîéñòâà

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

        public byte[] Identifier
        {
            get { return _identifer; }
            set
            {
                if (value.Length > 64)
                {
                    throw new ArgumentOutOfRangeException("value", "The identifier can't be more than 64 bytes");
                }
                _identifer = value;
            }
        }

        #endregion

        #region Êîíñòðóêòîð

        public FrameUniqueIdentifier(string frameId)
            : base(frameId)
        {
        }

        #endregion

        #region Ìåòîäû

        public override void Parse(byte[] frame)
        {
            int index = 0;
            _description = TextBuilder.ReadASCII(frame, ref index);
            _identifer = Memory.Extract(frame, index, frame.Length - index);
        }

        public override byte[] Make()
        {
            MemoryStream buffer = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(buffer);
            writer.Write(TextBuilder.WriteASCII(_description));
            writer.Write(_identifer);
            return buffer.ToArray();
        }

        public override string ToString()
        {
            return _description;
        }

        #endregion
    }
}


text:
using System;
using System.Reflection;
using ThinkingHome.Migrator.Framework.Interfaces;

namespace ThinkingHome.Migrator.Providers
{
    public class ConditionByProvider : IConditionByProvider
    {
        private readonly ITransformationProvider currentProvider;

        public ITransformationProvider CurrentProvider
        {
            get { return currentProvider; }
        }

        public bool isExecuted;

        public ConditionByProvider(ITransformationProvider current)
        {
            if (current == null) throw new ArgumentNullException(nameof(current));

            currentProvider = current;
            isExecuted = false;
        }

        private static void ValidateProviderType(Type providerType)
        {
            if (providerType == null) throw new ArgumentNullException(nameof(providerType));

            if (!typeof(ITransformationProvider).GetTypeInfo().IsAssignableFrom(providerType))
            {
                throw new InvalidCastException("Provider class must implement the ITransformationProvider interface");
            }
        }

        public IConditionByProvider For<TProvider>(Action<ITransformationProvider> action)
        {
            return For(typeof(TProvider), action);
        }

        public IConditionByProvider For(Type providerType, Action<ITransformationProvider> action)
        {
            ValidateProviderType(providerType);

            bool needExecute = providerType.GetTypeInfo().IsInstanceOfType(currentProvider);

            if (needExecute)
            {
                action?.Invoke(currentProvider);
            }

            isExecuted |= needExecute;

            return this;
        }

        public void Else(Action<ITransformationProvider> action)
        {
            if (!isExecuted && action != null)
            {
                action(currentProvider);
                isExecuted = true;
            }
        }
    }
}