text:
use crate::base::ExtCtxt;

use rustc_ast::attr;
use rustc_ast::ptr::P;
use rustc_ast::{self as ast, AttrVec, BlockCheckMode, Expr, LocalKind, PatKind, UnOp};
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Ident, Symbol};

use rustc_span::Span;

impl<'a> ExtCtxt<'a> {
    pub fn path(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
        self.path_all(span, false, strs, vec![])
    }
    pub fn path_ident(&self, span: Span, id: Ident) -> ast::Path {
        self.path(span, vec![id])
    }
    pub fn path_global(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
        self.path_all(span, true, strs, vec![])
    }
    pub fn path_all(
        &self,
        span: Span,
        global: bool,
        mut idents: Vec<Ident>,
        args: Vec<ast::GenericArg>,
    ) -> ast::Path {
        assert!(!idents.is_empty());
        let add_root = global && !idents[0].is_path_segment_keyword();
        let mut segments = Vec::with_capacity(idents.len() + add_root as usize);
        if add_root {
            segments.push(ast::PathSegment::path_root(span));
        }
        let last_ident = idents.pop().unwrap();
        segments.extend(
            idents.into_iter().map(|ident| ast::PathSegment::from_ident(ident.with_span_pos(span))),
        );
        let args = if !args.is_empty() {
            let args = args.into_iter().map(ast::AngleBracketedArg::Arg).collect();
            ast::AngleBracketedArgs { args, span }.into()
        } else {
            None
        };
        segments.push(ast::PathSegment {
            ident: last_ident.with_span_pos(span),
            id: ast::DUMMY_NODE_ID,
            args,
        });
        ast::Path { span, segments, tokens: None }
    }

    pub fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy {
        ast::MutTy { ty, mutbl }
    }

    pub fn ty(&self, span: Span, kind: ast::TyKind) -> P<ast::Ty> {
        P(ast::Ty { id: ast::DUMMY_NODE_ID, span, kind, tokens: None })
    }

    pub fn ty_path(&self, path: ast::Path) -> P<ast::Ty> {
        self.ty(path.span, ast::TyKind::Path(None, path))
    }

    // Might need to take bounds as an argument in the future, if you ever want
    // to generate a bounded existential trait type.
    pub fn ty_ident(&self, span: Span, ident: Ident) -> P<ast::Ty> {
        self.ty_path(self.path_ident(span, ident))
    }

    pub fn anon_const(&self, span: Span, kind: ast::ExprKind) -> ast::AnonConst {
        ast::AnonConst {
            id: ast::DUMMY_NODE_ID,
            value: P(ast::Expr {
                id: ast::DUMMY_NODE_ID,
                kind,
                span,
                attrs: AttrVec::new(),
                tokens: None,
            }),
        }
    }

    pub fn const_ident(&self, span: Span, ident: Ident) -> ast::AnonConst {
        self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident)))
    }

    pub fn ty_rptr(
        &self,
        span: Span,
        ty: P<ast::Ty>,
        lifetime: Option<ast::Lifetime>,
        mutbl: ast::Mutability,
    ) -> P<ast::Ty> {
        self.ty(span, ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl)))
    }

    pub fn ty_ptr(&self, span: Span, ty: P<ast::Ty>, mutbl: ast::Mutability) -> P<ast::Ty> {
        self.ty(span, ast::TyKind::Ptr(self.ty_mt(ty, mutbl)))
    }

    pub fn typaram(
        &self,
        span: Span,
        ident: Ident,
        attrs: Vec<ast::Attribute>,
        bounds: ast::GenericBounds,
        default: Option<P<ast::Ty>>,
    ) -> ast::GenericParam {
        ast::GenericParam {
            ident: ident.with_span_pos(span),
            id: ast::DUMMY_NODE_ID,
            attrs: attrs.into(),
            bounds,
            kind: ast::GenericParamKind::Type { default },
            is_placeholder: false,
        }
    }

    pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
        ast::TraitRef { path, ref_id: ast::DUMMY_NODE_ID }
    }

    pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {
        ast::PolyTraitRef {
            bound_generic_params: Vec::new(),
            trait_ref: self.trait_ref(path),
            span,
        }
    }

    pub fn trait_bound(&self, path: ast::Path) -> ast::GenericBound {
        ast::GenericBound::Trait(
            self.poly_trait_ref(path.span, path),
            ast::TraitBoundModifier::None,
        )
    }

    pub fn lifetime(&self, span: Span, ident: Ident) -> ast::Lifetime {
        ast::Lifetime { id: ast::DUMMY_NODE_ID, ident: ident.with_span_pos(span) }
    }

    pub fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt {
        ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Expr(expr) }
    }

    pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: Ident, ex: P<ast::Expr>) -> ast::Stmt {
        let pat = if mutbl {
            let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mut);
            self.pat_ident_binding_mode(sp, ident, binding_mode)
        } else {
            self.pat_ident(sp, ident)
        };
        let local = P(ast::Local {
            pat,
            ty: None,
            id: ast::DUMMY_NODE_ID,
            kind: LocalKind::Init(ex),
            span: sp,
            attrs: AttrVec::new(),
            tokens: None,
        });
        ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span: sp }
    }

    // Generates `let _: Type;`, which is usually used for type assertions.
    pub fn stmt_let_type_only(&self, span: Span, ty: P<ast::Ty>) -> ast::Stmt {
        let local = P(ast::Local {
            pat: self.pat_wild(span),
            ty: Some(ty),
            id: ast::DUMMY_NODE_ID,
            kind: LocalKind::Decl,
            span,
            attrs: AttrVec::new(),
            tokens: None,
        });
        ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span }
    }

    pub fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt {
        ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Item(item), span: sp }
    }

    pub fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> {
        self.block(
            expr.span,
            vec![ast::Stmt {
                id: ast::DUMMY_NODE_ID,
                span: expr.span,
                kind: ast::StmtKind::Expr(expr),
            }],
        )
    }
    pub fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block> {
        P(ast::Block {
            stmts,
            id: ast::DUMMY_NODE_ID,
            rules: BlockCheckMode::Default,
            span,
            tokens: None,
            could_be_bare_literal: false,
        })
    }

    pub fn expr(&self, span: Span, kind: ast::ExprKind) -> P<ast::Expr> {
        P(ast::Expr { id: ast::DUMMY_NODE_ID, kind, span, attrs: AttrVec::new(), tokens: None })
    }

    pub fn expr_path(&self, path: ast::Path) -> P<ast::Expr> {
        self.expr(path.span, ast::ExprKind::Path(None, path))
    }

    pub fn expr_ident(&self, span: Span, id: Ident) -> P<ast::Expr> {
        self.expr_path(self.path_ident(span, id))
    }
    pub fn expr_self(&self, span: Span) -> P<ast::Expr> {
        self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower))
    }

    pub fn expr_binary(
        &self,
        sp: Span,
        op: ast::BinOpKind,
        lhs: P<ast::Expr>,
        rhs: P<ast::Expr>,
    ) -> P<ast::Expr> {
        self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs))
    }

    pub fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
        self.expr(sp, ast::ExprKind::Unary(UnOp::Deref, e))
    }

    pub fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
        self.expr(sp, ast::ExprKind::AddrOf(ast::BorrowKind::Ref, ast::Mutability::Not, e))
    }

    pub fn expr_call(
        &self,
        span: Span,
        expr: P<ast::Expr>,
        args: Vec<P<ast::Expr>>,
    ) -> P<ast::Expr> {
        self.expr(span, ast::ExprKind::Call(expr, args))
    }
    pub fn expr_call_ident(&self, span: Span, id: Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr> {
        self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args))
    }
    pub fn expr_call_global(
        &self,
        sp: Span,
        fn_path: Vec<Ident>,
        args: Vec<P<ast::Expr>>,
    ) -> P<ast::Expr> {
        let pathexpr = self.expr_path(self.path_global(sp, fn_path));
        self.expr_call(sp, pathexpr, args)
    }
    pub fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr> {
        self.expr(b.span, ast::ExprKind::Block(b, None))
    }
    pub fn field_imm(&self, span: Span, ident: Ident, e: P<ast::Expr>) -> ast::ExprField {
        ast::ExprField {
            ident: ident.with_span_pos(span),
            expr: e,
            span,
            is_shorthand: false,
            attrs: AttrVec::new(),
            id: ast::DUMMY_NODE_ID,
            is_placeholder: false,
        }
    }
    pub fn expr_struct(
        &self,
        span: Span,
        path: ast::Path,
        fields: Vec<ast::ExprField>,
    ) -> P<ast::Expr> {
        self.expr(
            span,
            ast::ExprKind::Struct(P(ast::StructExpr {
                qself: None,
                path,
                fields,
                rest: ast::StructRest::None,
            })),
        )
    }
    pub fn expr_struct_ident(
        &self,
        span: Span,
        id: Ident,
        fields: Vec<ast::ExprField>,
    ) -> P<ast::Expr> {
        self.expr_struct(span, self.path_ident(span, id), fields)
    }

    pub fn expr_lit(&self, span: Span, lit_kind: ast::LitKind) -> P<ast::Expr> {
        let lit = ast::Lit::from_lit_kind(lit_kind, span);
        self.expr(span, ast::ExprKind::Lit(lit))
    }
    pub fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> {
        self.expr_lit(
            span,
            ast::LitKind::Int(i as u128, ast::LitIntType::Unsigned(ast::UintTy::Usize)),
        )
    }
    pub fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> {
        self.expr_lit(sp, ast::LitKind::Int(u as u128, ast::LitIntType::Unsigned(ast::UintTy::U32)))
    }
    pub fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> {
        self.expr_lit(sp, ast::LitKind::Bool(value))
    }

    pub fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
        self.expr(sp, ast::ExprKind::Array(exprs))
    }
    pub fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
        self.expr_addr_of(sp, self.expr_vec(sp, exprs))
    }
    pub fn expr_str(&self, sp: Span, s: Symbol) -> P<ast::Expr> {
        self.expr_lit(sp, ast::LitKind::Str(s, ast::StrStyle::Cooked))
    }

    pub fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr> {
        self.expr(sp, ast::ExprKind::Cast(expr, ty))
    }

    pub fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
        let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
        self.expr_call_global(sp, some, vec![expr])
    }

    pub fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
        self.expr(sp, ast::ExprKind::Tup(exprs))
    }

    pub fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> {
        self.expr_call_global(
            span,
            [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(),
            vec![self.expr_str(span, msg)],
        )
    }

    pub fn expr_unreachable(&self, span: Span) -> P<ast::Expr> {
        self.expr_fail(span, Symbol::intern("internal error: entered unreachable code"))
    }

    pub fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
        let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
        self.expr_call_global(sp, ok, vec![expr])
    }

    pub fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> {
        let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
        let ok_path = self.path_global(sp, ok);
        let err = self.std_path(&[sym::result, sym::Result, sym::Err]);
        let err_path = self.path_global(sp, err);

        let binding_variable = Ident::new(sym::__try_var, sp);
        let binding_pat = self.pat_ident(sp, binding_variable);
        let binding_expr = self.expr_ident(sp, binding_variable);

        // `Ok(__try_var)` pattern
        let ok_pat = self.pat_tuple_struct(sp, ok_path, vec![binding_pat.clone()]);

        // `Err(__try_var)` (pattern and expression respectively)
        let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]);
        let err_inner_expr =
            self.expr_call(sp, self.expr_path(err_path), vec![binding_expr.clone()]);
        // `return Err(__try_var)`
        let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr)));

        // `Ok(__try_var) => __try_var`
        let ok_arm = self.arm(sp, ok_pat, binding_expr);
        // `Err(__try_var) => return Err(__try_var)`
        let err_arm = self.arm(sp, err_pat, err_expr);

        // `match head { Ok() => ..., Err() => ... }`
        self.expr_match(sp, head, vec![ok_arm, err_arm])
    }

    pub fn pat(&self, span: Span, kind: PatKind) -> P<ast::Pat> {
        P(ast::Pat { id: ast::DUMMY_NODE_ID, kind, span, tokens: None })
    }
    pub fn pat_wild(&self, span: Span) -> P<ast::Pat> {
        self.pat(span, PatKind::Wild)
    }
    pub fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat> {
        self.pat(span, PatKind::Lit(expr))
    }
    pub fn pat_ident(&self, span: Span, ident: Ident) -> P<ast::Pat> {
        let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Not);
        self.pat_ident_binding_mode(span, ident, binding_mode)
    }

    pub fn pat_ident_binding_mode(
        &self,
        span: Span,
        ident: Ident,
        bm: ast::BindingMode,
    ) -> P<ast::Pat> {
        let pat = PatKind::Ident(bm, ident.with_span_pos(span), None);
        self.pat(span, pat)
    }
    pub fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat> {
        self.pat(span, PatKind::Path(None, path))
    }
    pub fn pat_tuple_struct(
        &self,
        span: Span,
        path: ast::Path,
        subpats: Vec<P<ast::Pat>>,
    ) -> P<ast::Pat> {
        self.pat(span, PatKind::TupleStruct(None, path, subpats))
    }
    pub fn pat_struct(
        &self,
        span: Span,
        path: ast::Path,
        field_pats: Vec<ast::PatField>,
    ) -> P<ast::Pat> {
        self.pat(span, PatKind::Struct(None, path, field_pats, false))
    }
    pub fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> {
        self.pat(span, PatKind::Tuple(pats))
    }

    pub fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
        let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
        let path = self.path_global(span, some);
        self.pat_tuple_struct(span, path, vec![pat])
    }

    pub fn arm(&self, span: Span, pat: P<ast::Pat>, expr: P<ast::Expr>) -> ast::Arm {
        ast::Arm {
            attrs: AttrVec::new(),
            pat,
            guard: None,
            body: expr,
            span,
            id: ast::DUMMY_NODE_ID,
            is_placeholder: false,
        }
    }

    pub fn arm_unreachable(&self, span: Span) -> ast::Arm {
        self.arm(span, self.pat_wild(span), self.expr_unreachable(span))
    }

    pub fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> {
        self.expr(span, ast::ExprKind::Match(arg, arms))
    }

    pub fn expr_if(
        &self,
        span: Span,
        cond: P<ast::Expr>,
        then: P<ast::Expr>,
        els: Option<P<ast::Expr>>,
    ) -> P<ast::Expr> {
        let els = els.map(|x| self.expr_block(self.block_expr(x)));
        self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els))
    }

    pub fn lambda(&self, span: Span, ids: Vec<Ident>, body: P<ast::Expr>) -> P<ast::Expr> {
        let fn_decl = self.fn_decl(
            ids.iter().map(|id| self.param(span, *id, self.ty(span, ast::TyKind::Infer))).collect(),
            ast::FnRetTy::Default(span),
        );

        // FIXME -- We are using `span` as the span of the `|...|`
        // part of the lambda, but it probably (maybe?) corresponds to
        // the entire lambda body. Probably we should extend the API
        // here, but that's not entirely clear.
        self.expr(
            span,
            ast::ExprKind::Closure(
                ast::CaptureBy::Ref,
                ast::Async::No,
                ast::Movability::Movable,
                fn_decl,
                body,
                span,
            ),
        )
    }

    pub fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr> {
        self.lambda(span, Vec::new(), body)
    }

    pub fn lambda1(&self, span: Span, body: P<ast::Expr>, ident: Ident) -> P<ast::Expr> {
        self.lambda(span, vec![ident], body)
    }

    pub fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, ident: Ident) -> P<ast::Expr> {
        self.lambda1(span, self.expr_block(self.block(span, stmts)), ident)
    }

    pub fn param(&self, span: Span, ident: Ident, ty: P<ast::Ty>) -> ast::Param {
        let arg_pat = self.pat_ident(span, ident);
        ast::Param {
            attrs: AttrVec::default(),
            id: ast::DUMMY_NODE_ID,
            pat: arg_pat,
            span,
            ty,
            is_placeholder: false,
        }
    }

    // FIXME: unused `self`
    pub fn fn_decl(&self, inputs: Vec<ast::Param>, output: ast::FnRetTy) -> P<ast::FnDecl> {
        P(ast::FnDecl { inputs, output })
    }

    pub fn item(
        &self,
        span: Span,
        name: Ident,
        attrs: Vec<ast::Attribute>,
        kind: ast::ItemKind,
    ) -> P<ast::Item> {
        // FIXME: Would be nice if our generated code didn't violate
        // Rust coding conventions
        P(ast::Item {
            ident: name,
            attrs,
            id: ast::DUMMY_NODE_ID,
            kind,
            vis: ast::Visibility {
                span: span.shrink_to_lo(),
                kind: ast::VisibilityKind::Inherited,
                tokens: None,
            },
            span,
            tokens: None,
        })
    }

    pub fn item_static(
        &self,
        span: Span,
        name: Ident,
        ty: P<ast::Ty>,
        mutbl: ast::Mutability,
        expr: P<ast::Expr>,
    ) -> P<ast::Item> {
        self.item(span, name, Vec::new(), ast::ItemKind::Static(ty, mutbl, Some(expr)))
    }

    pub fn item_const(
        &self,
        span: Span,
        name: Ident,
        ty: P<ast::Ty>,
        expr: P<ast::Expr>,
    ) -> P<ast::Item> {
        let def = ast::Defaultness::Final;
        self.item(span, name, Vec::new(), ast::ItemKind::Const(def, ty, Some(expr)))
    }

    pub fn attribute(&self, mi: ast::MetaItem) -> ast::Attribute {
        attr::mk_attr_outer(mi)
    }

    pub fn meta_word(&self, sp: Span, w: Symbol) -> ast::MetaItem {
        attr::mk_word_item(Ident::new(w, sp))
    }
}


text:
include T('guide/layout/html')

def stylesheets
  super + %w(css/highlight.github.css)
end

def javascripts
  super + %w(js/underscore.js js/doctools.js js/searchtools.js js/highlight.pack.js)
end

redpajama_set_name: RedPajamaGithub


text:
#include <syscfg/syscfg.h>
#include "cosa_webconfig_api.h"
#include "webconfig_framework.h"
#include "base64.h"
#include "safec_lib_common.h"

t_cache pf_cache[PORTMAP_CACHE_SIZE];
t_cache pf_cache_bkup[PORTMAP_CACHE_SIZE];

t_cache dmz_cache[DMZ_CACHE_SIZE];
t_cache dmz_cache_bkup[DMZ_CACHE_SIZE];

int pf_cache_size = 0;
int pf_cache_size_bkup = 0;

char pf_param_name[128] = {0};
int gpfEnable = 0;

int  get_base64_decodedbuffer(char *pString, char **buffer, int *size)
{
    struct timespec start,end,*startPtr,*endPtr;
    int decodeMsgSize = 0;
    char *decodeMsg = NULL;
    if (buffer == NULL || size == NULL || pString == NULL)
        return -1;

    startPtr = &start;
    endPtr = &end;

    getCurrentTime(startPtr);
    decodeMsgSize = b64_get_decoded_buffer_size(strlen(pString));

    decodeMsg = (char *) malloc(sizeof(char) * decodeMsgSize);

    if (!decodeMsg)
        return -1;

    *size = b64_decode( (const uint8_t*)pString, strlen(pString), (uint8_t *)decodeMsg );
    CcspTraceWarning(("base64 decoded data contains %d bytes\n",*size));

    getCurrentTime(endPtr);
    CcspTraceWarning(("Base64 decode Elapsed time : %ld ms\n", timeValDiff(startPtr, endPtr)));

    *buffer = decodeMsg;
    return 0;
}

msgpack_unpack_return get_msgpack_unpack_status(char *decodedbuf, int size)
{

    msgpack_zone mempool;
    msgpack_object deserialized;
    msgpack_unpack_return unpack_ret;

    if (decodedbuf == NULL || !size)
        return MSGPACK_UNPACK_NOMEM_ERROR;

    msgpack_zone_init(&mempool, 2048);
    unpack_ret = msgpack_unpack(decodedbuf, size, NULL, &mempool, &deserialized);

    switch(unpack_ret)
    {
        case MSGPACK_UNPACK_SUCCESS:
            CcspTraceWarning(("MSGPACK_UNPACK_SUCCESS :%d\n",unpack_ret));
            break;
        case MSGPACK_UNPACK_EXTRA_BYTES:
            CcspTraceWarning(("MSGPACK_UNPACK_EXTRA_BYTES :%d\n",unpack_ret));
            break;
        case MSGPACK_UNPACK_CONTINUE:
            CcspTraceWarning(("MSGPACK_UNPACK_CONTINUE :%d\n",unpack_ret));
            break;
        case MSGPACK_UNPACK_PARSE_ERROR:
            CcspTraceWarning(("MSGPACK_UNPACK_PARSE_ERROR :%d\n",unpack_ret));
            break;
        case MSGPACK_UNPACK_NOMEM_ERROR:
            CcspTraceWarning(("MSGPACK_UNPACK_NOMEM_ERROR :%d\n",unpack_ret));
            break;
        default:
            CcspTraceWarning(("Message Pack decode failed with error: %d\n", unpack_ret));
    }

    msgpack_zone_destroy(&mempool);
    //End of msgpack decoding

    return unpack_ret;
}
int CheckIfIpIsValid( char *ipAddress )
{

    CcspTraceInfo(("%s:IpAddressReceivedIs:%s\n",__FUNCTION__,ipAddress));

    struct sockaddr_in sa;
    struct sockaddr_in6 sa6;

    if ( (inet_pton(AF_INET, ipAddress, &(sa.sin_addr)) == 1 ) || (inet_pton(AF_INET6, ipAddress, &(sa6.sin6_addr)) == 1 ))
    {
        return VALID_IP;
    }

    return INVALID_IP;
}

int CheckIfPortsAreValid( char *port, char *port_end_range )
{

    CcspTraceInfo(("%s:ExternalPortEndRangeReceivedIs:%s\n",__FUNCTION__,port));
    CcspTraceInfo(("%s:ExternalPortEndRangeReceivedIs:%s\n",__FUNCTION__,port_end_range));

    int iPort = atoi(port);

    int iPort_end_range = atoi(port_end_range);

    while (*port)
    {
        if (isdigit(*port++) == 0)
        {
            return INVALID_PORT ;
        }
    }

    while (*port_end_range)
    {
        if (isdigit(*port_end_range++) == 0)
        {
            return INVALID_PORT ;
        }
    }

    if ( iPort <= 0 || iPort > 65535 || iPort_end_range <=0 || iPort_end_range > 65535  || iPort > iPort_end_range)
    {
        return INVALID_PORT ;
    }

    return 0;
}
/* API to get the subdoc version */

uint32_t getBlobVersion(char* subdoc)
{

	char subdoc_ver[64] = {0}, buf[72] = {0};
    	snprintf(buf,sizeof(buf),"%s_version",subdoc);
    	if ( syscfg_get( NULL, buf, subdoc_ver, sizeof(subdoc_ver)) == 0 )
    	{
        	int version = atoi(subdoc_ver);
      		//  uint32_t version = strtoul(subdoc_ver, NULL, 10) ;

        	return (uint32_t)version;
    	}
    	return 0;
}

/* API to update the subdoc version */
int setBlobVersion(char* subdoc,uint32_t version)
{

	char subdoc_ver[32] = {0}, buf[72] = {0};
  	snprintf(subdoc_ver,sizeof(subdoc_ver),"%u",version);
  	snprintf(buf,sizeof(buf),"%s_version",subdoc);

    if (strcmp(subdoc,"hotspot") == 0 )
    {
        char cmd[256] = {0};
        memset(cmd,0,sizeof(cmd));
        snprintf(cmd,sizeof(cmd),"mv /tmp/.%s%s %s",subdoc,subdoc_ver,HOTSPOT_BLOB_FILE);
        CcspTraceInfo(("%s : cmd to move filename is %s\n",__FUNCTION__,cmd));

        system(cmd);

    }
 	if(syscfg_set_commit(NULL,buf,subdoc_ver) != 0)
 	{
        	CcspTraceError(("syscfg_set failed\n"));
        	return -1;
 	}

	return 0;

}

/* API to register all the supported subdocs , versionGet and versionSet are callback functions to get and set the subdoc versions in db */

void webConfigFrameworkInit()
{
#if defined (FEATURE_RDKB_DHCP_MANAGER)
	char *sub_docs[SUBDOC_COUNT+1]= {"portforwarding","wan","hotspot",(char *) 0 };
#else
	char *sub_docs[SUBDOC_COUNT+1]= {"portforwarding","wan","macbinding","lan","hotspot",(char *) 0 };
#endif
    	blobRegInfo *blobData;

    	blobData = (blobRegInfo*) malloc(SUBDOC_COUNT * sizeof(blobRegInfo));

    	int i;
    	memset(blobData, 0, SUBDOC_COUNT * sizeof(blobRegInfo));

    	blobRegInfo *blobDataPointer = blobData;

    	for (i=0 ; i < SUBDOC_COUNT ; i++ )
    	{
        	strncpy( blobDataPointer->subdoc_name, sub_docs[i], sizeof(blobDataPointer->subdoc_name)-1);

        	blobDataPointer++;
    	}

   	    blobDataPointer = blobData ;

    	getVersion versionGet = getBlobVersion;

    	setVersion versionSet = setBlobVersion;

    	register_sub_docs(blobData,SUBDOC_COUNT,versionGet,versionSet);
	initMultiCompMaster();

        //Multi Comp
        wbInitializeHotspot();
}

/* API to clear the buffer */
void clear_pf_cache(t_cache *tmp_pf_cache)
{
	int i = 0;
    	for(i = 0; i < PORTMAP_CACHE_SIZE; i++)
    	{
        	memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
        	memset(tmp_pf_cache[i].val,0,VAL_BLOCK_SIZE);

    	}

}

/* API to print cache */
void print_pf_cache(t_cache *tmp_pf_cache)
{
	int i = 0;
    	for(i = 0;i <pf_cache_size ; i++)
    	{
        	printf("pf_cache[%d].cmd - %s\n",i,tmp_pf_cache[i].cmd);
        	printf("pf_cache[%d].val - %s\n",i,tmp_pf_cache[i].val);
    	}

}
#if 1
/*int syscfg_set(void *p, char *cmd, char)
{

}*/

/* API to unset the entries from DB */
int clear_pf_cache_DB(t_cache *tmp_pf_cache)
{
	int i = 0;
    	for(i = 0; i < pf_cache_size; i++)
    	{

        	if (syscfg_unset(NULL, tmp_pf_cache[i].cmd) != 0)
        	{
               		CcspTraceError(("syscfg_set failed for %s %s\n",tmp_pf_cache[i].cmd,tmp_pf_cache[i].val));
                    return SYSCFG_FAILURE;

               		//break;
        	}
        	memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
        	memset(tmp_pf_cache[i].val,0,VAL_BLOCK_SIZE);
        	if (syscfg_commit() != 0)
        	{
            		CcspTraceError(("syscfg_commit failed apply_cache_ToDB\n"));
                    return SYSCFG_FAILURE;

        	}

    	}
    	system("sysevent set firewall-restart");

    return 0;

}

/* API to back up the cache */
void backup_pf_cache(t_cache *tmp_pf_cache,t_cache *tmp_pf_cache_bkup,int cache_size)
{
    UNREFERENCED_PARAMETER(cache_size);
	int i = 0;
    errno_t rc = -1;
    	for(i = 0; i < pf_cache_size; i++)
    	{

			memset(tmp_pf_cache_bkup[i].cmd,0,BLOCK_SIZE);
       		memset(tmp_pf_cache_bkup[i].val,0,VAL_BLOCK_SIZE);

			rc = strcpy_s(tmp_pf_cache_bkup[i].cmd, BLOCK_SIZE,tmp_pf_cache[i].cmd);
			if(rc != EOK)
			{
				ERR_CHK(rc);
			}

			rc = strcpy_s(tmp_pf_cache_bkup[i].val, VAL_BLOCK_SIZE,tmp_pf_cache[i].val);
			if(rc != EOK)
			{
				ERR_CHK(rc);
			}
   	 }
}

/* API to apply port forwarding requests to DB */
int apply_pf_cache_ToDB(t_cache *tmp_pf_cache, int cache_size,int pmapEnable)
{
	    int i = 0;
        if ( gpfEnable !=  pmapEnable )
        {
                if (syscfg_set(NULL,pf_param_name, (pmapEnable == 1) ? "1" : "0" ) != 0)
                {
                    CcspTraceError(("syscfg_set failed to set %s parameter\n",pf_param_name));
                    return SYSCFG_FAILURE;
                }
        }

    	for(i = 0;i <cache_size ; i++)
    	{
        	//printf("pf_cache[%d].cmd - %s\n",i,tmp_pf_cache[i].cmd);
        	//printf("pf_cache[%d].val - %s\n",i,tmp_pf_cache[i].val);

        	if (syscfg_set(NULL, tmp_pf_cache[i].cmd, tmp_pf_cache[i].val) != 0)
        	{
               		CcspTraceError(("syscfg_set failed for %s %s\n",tmp_pf_cache[i].cmd,tmp_pf_cache[i].val));
               		return SYSCFG_FAILURE;
              		// break;
        	}
    	}
    	if (syscfg_commit() != 0)
    	{
        	CcspTraceError(("syscfg_commit failed apply_cache_ToDB\n"));
       		return SYSCFG_FAILURE;

    	}

        #ifdef WEBCFG_TEST_SIM
            int fd = -1;
            // to simulate NACK
            fd = access(NACK_SIMULATE_FILE, F_OK);
            if(fd == 0)
            {
                    unlink(NACK_SIMULATE_FILE);
                    return SYSCFG_FAILURE;

            }
            fd = -1;

            // to simulate timeout and maxtimeout cases
            FILE *fp;
            int interval = 15 ;
            fp = fopen (TIMEOUT_SIMULATE_FILE, "r");
            if( fp )
            {
                fscanf(fp, "%d", &interval);
                if ( interval <= 0 )
                    interval = 15;

                sleep(interval);
                fclose(fp);
                fp=NULL;
                unlink(TIMEOUT_SIMULATE_FILE);

            }
        #endif

    	system("sysevent set firewall-restart");

    return 0;
}
#endif
#if 0
void fill_portmap_entry(int count)
{
    int i = 0;
    rpm = (portmappingdoc_t *)malloc(sizeof(portmappingdoc_t));
    rpm->entries = (portdoc_t *)malloc(sizeof(portdoc_t)*count);
    rpm->entries_count = count;
    for(i = 0; i < count; i++ )
    {
        rpm->entries[i].internal_client = malloc(sizeof(char)*16);
        memset(rpm->entries[i].internal_client,0,16);
        strcpy(rpm->entries[i].internal_client,"192.168.0.21");

        rpm->entries[i].enable = malloc(sizeof(char)*16);
        memset(rpm->entries[i].enable,0,16);
        strcpy(rpm->entries[i].enable,"1");

        rpm->entries[i].external_port_end_range = malloc(sizeof(char)*16);
        memset(rpm->entries[i].external_port_end_range,0,16);
        if(i%2 == 1)
        strcpy(rpm->entries[i].external_port_end_range,"5670");
        else
            strcpy(rpm->entries[i].external_port_end_range,"5666");

        rpm->entries[i].protocol = malloc(sizeof(char)*16);
        memset(rpm->entries[i].protocol,0,16);
        strcpy(rpm->entries[i].protocol,"both");

        rpm->entries[i].description = malloc(sizeof(char)*16);
        memset(rpm->entries[i].description,0,16);
        strcpy(rpm->entries[i].description,"test");

        rpm->entries[i].external_port = malloc(sizeof(char)*16);
        memset(rpm->entries[i].external_port,0,16);
        strcpy(rpm->entries[i].external_port,"5666");
    }
}

void print_portmap_entry()
{
	int i = 0;
    	printf("entries %d\n",rpm->entries_count);

    	for(i = 0; i < rpm->entries_count; i++ )
    	{
        	printf("rpm->entries[%d].internal_client= %s\n",i,rpm->entries[i].internal_client);
        	printf("rpm->entries[%d].enable= %s\n",i,rpm->entries[i].enable);
        	printf("rpm->entries[%d].external_port_end_range= %s\n",i,rpm->entries[i].external_port_end_range);
        	printf("rpm->entries[%d].protocol= %s\n",i,rpm->entries[i].protocol);
        	printf("rpm->entries[%d].description= %s\n",i,rpm->entries[i].description);
        	printf("rpm->entries[%d].external_port= %s\n",i,rpm->entries[i].external_port);

    	}
}

#endif

/* Read blob entries into a cache */
int set_portmap_conf(portmappingdoc_t *rpm)
{
        unsigned long i = 0;
        int count = 0; int j = 0;
    	int spf_count = 0;
    	int pfr_count = 0;
    	char alias_pre[8];
        errno_t  rc   = -1;
    	printf("Port map entries %d\n",rpm->entries_count);
    	//printf("SinglePortForwardCount = %d\n", rpm->entries_count);
    	//count = rpm->entries_count + 1;
    	for(i = 1,j =0; i < rpm->entries_count+1; i++, j++ )
    	{
        	memset(alias_pre,0,8);

            if ( INVALID_IP == CheckIfIpIsValid(rpm->entries[j].internal_client) )
            {
                return INVALID_IP;
            }

            if ( (rpm->entries[j].external_port[0] == '\0' ) || ( rpm->entries[j].external_port_end_range[0] == '\0' ) )
            {
                CcspTraceError(("port value is null, validation failed\n"));
                return INVALID_PORT ;

            }

            else if ( INVALID_PORT == CheckIfPortsAreValid(rpm->entries[j].external_port, rpm->entries[j].external_port_end_range ) )
            {
                return INVALID_PORT ;
            }

       		if(strcmp(rpm->entries[j].external_port,rpm->entries[j].external_port_end_range) == 0)
        	{
            		spf_count++;
            		snprintf(pf_cache[count].cmd,BLOCK_SIZE,ALIAS_SPF"%d",spf_count);
            		rc = strcpy_s(alias_pre, sizeof(alias_pre),ALIAS_PRE_SPF);
			if(rc != EOK)
			{
				ERR_CHK(rc);
				return -1;
			}
			snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s%lu",alias_pre,i);
			rc = sprintf_s(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_EXT_PORT,alias_pre,i);
			if(rc < EOK) ERR_CHK(rc);
            		snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s",rpm->entries[j].external_port);

        	}
        	else
        	{
           		pfr_count++;
           		snprintf(pf_cache[count].cmd,BLOCK_SIZE,ALIAS_PFR"%d",pfr_count);
			rc = strcpy_s(alias_pre, sizeof(alias_pre),ALIAS_PRE_PFR);
			if(rc != EOK)
			{
				ERR_CHK(rc);
				return -1;
			}
            		snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s%lu",alias_pre,i);
            		rc = sprintf_s(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_EXT_PORT_RANGE,alias_pre,i);
			if(rc < EOK) ERR_CHK(rc);
            		snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s %s",rpm->entries[j].external_port,rpm->entries[j].external_port_end_range);
            		snprintf(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_PFR_PUBLIC_IP,alias_pre,i);
            		snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s","0.0.0.0");
            		rc = sprintf_s(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_PFR_INT_RANGE,alias_pre,i);
			if(rc < EOK) ERR_CHK(rc);
            		snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s","0");
        	}

        	snprintf(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_IP,alias_pre,i);

      		snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s",rpm->entries[j].internal_client);
        	snprintf(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_NAME,alias_pre,i);
        	snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s",rpm->entries[j].description);
        	snprintf(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_ENABLE,alias_pre,i);
        	snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%s",rpm->entries[j].enable);
        	snprintf(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_PROTO,alias_pre,i);

            if ( ( strcasecmp(rpm->entries[j].protocol,"TCP/UDP") == 0 )|| ( strcasecmp(rpm->entries[j].protocol,"UDP/TCP") == 0 ) || ( strcasecmp(rpm->entries[j].protocol,"BOTH") == 0 )  )
            {
                    snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"both");

            }
            else if ( strcasecmp(rpm->entries[j].protocol,"TCP") == 0 )
            {
                snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"tcp");

            }
            else if ( strcasecmp(rpm->entries[j].protocol,"UDP") == 0 )
            {
                snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"udp");

            }
            else
            {
                return INVALID_PROTOCOL ;
            }
        	rc = sprintf_s(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_INT_PORT,alias_pre,i);
        	if(rc < EOK) ERR_CHK(rc);
        	snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"0");
        	snprintf(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_IPV6,alias_pre,i);
        	snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"x");
        	rc = sprintf_s(pf_cache[count].cmd,BLOCK_SIZE,"%s%lu"ALIAS_POS_PREV_STATE,alias_pre,i);
        	if(rc < EOK) ERR_CHK(rc);
        	snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"1");

    	}
        printf("SinglePortForwardCount = %d\n", spf_count);
        printf("PortRangeForwardCount = %d\n", pfr_count);
        snprintf(pf_cache[count].cmd,BLOCK_SIZE,"SinglePortForwardCount");
        snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%d",spf_count);
        snprintf(pf_cache[count].cmd,BLOCK_SIZE,"PortRangeForwardCount");
        snprintf(pf_cache[count++].val,VAL_BLOCK_SIZE,"%d",pfr_count);
        pf_cache_size =  count;

    return 0;
}

/* Initialize cache , this API will be called once in boot up */
void init_pf_cache(t_cache *tmp_pf_cache)
{
	int i = 0;
    	int spf_count = 0;
    	int pfr_count = 0;
    	char alias_pre[8];
    	errno_t rc = -1;
        char buf[8] = {0} ;
        snprintf(pf_param_name,sizeof(pf_param_name),"%s::%s",COSA_NAT_SYSCFG_NAMESPACE,PORT_FORWARD_ENABLED_KEY);

        if( 0 == syscfg_get( NULL, pf_param_name , buf, sizeof( buf ) ) &&  ( '\0' != buf[0] ) )
        {
                gpfEnable = atoi(buf);
        }

    	memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
    	memset(tmp_pf_cache[i].val,0,VAL_BLOCK_SIZE);
    	snprintf(tmp_pf_cache[i].cmd,BLOCK_SIZE,"SinglePortForwardCount");
        /* CID : 144101 Array compared against 0*/
        if(!syscfg_get( NULL, tmp_pf_cache[i].cmd, tmp_pf_cache[i].val, VAL_BLOCK_SIZE))
           spf_count = atoi(tmp_pf_cache[i++].val);
        //i++;
        snprintf(tmp_pf_cache[i].cmd,BLOCK_SIZE,"PortRangeForwardCount");
        /*CID: 144101 Array compared against 0*/
        if (!syscfg_get( NULL, tmp_pf_cache[i].cmd, tmp_pf_cache[i].val, VAL_BLOCK_SIZE))
            pfr_count = atoi(tmp_pf_cache[i++].val);

       // i++;
//  for(i; i < PORTMAP_CACHE_SIZE; i++)
	{
		//memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
		//memset(tmp_pf_cache[i].val,0,BLOCK_SIZE);
		//snprintf(tmp_pf_cache[i].cmd,BLOCK_SIZE,"SinglePortForwardCount");
		//spf_count++;
		int j = 0;
		for(j = 1; j< spf_count+1; j++)
		{
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			memset(tmp_pf_cache[i].val,0,VAL_BLOCK_SIZE);
			snprintf(tmp_pf_cache[i].cmd,BLOCK_SIZE,ALIAS_SPF"%d",j);
			syscfg_get( NULL, tmp_pf_cache[i].cmd, tmp_pf_cache[i].val, VAL_BLOCK_SIZE);
			/* CID : 144101 Array compared against 0*/
			memset(alias_pre,0,8);
			strcpy(alias_pre,tmp_pf_cache[i].val);
			printf("alias_pre = %s  %s\n",alias_pre,tmp_pf_cache[i].val);
			i++;
			//strcpy(alias_pre,ALIAS_PRE_SPF);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_EXT_PORT,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_IP,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_NAME,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_ENABLE,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_PROTO,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_INT_PORT,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_IPV6,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			rc = sprintf_s(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_PREV_STATE,alias_pre);
			if(rc < EOK) ERR_CHK(rc);
		}

    //  i++;

		for(j = 1; j< pfr_count+1; j++)
		{
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i].cmd,BLOCK_SIZE,ALIAS_PFR"%d",j);
			syscfg_get( NULL, tmp_pf_cache[i].cmd, tmp_pf_cache[i].val, VAL_BLOCK_SIZE);
			/* CID : 144101 Array compared against 0*/
			//  strcpy(alias_pre,tmp_pf_cache[i].val);
			memset(alias_pre,0,8);
			strcpy(alias_pre,tmp_pf_cache[i].val);
			printf("alias_pre = %s\n",alias_pre);

			i++;

			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			//  snprintf(tmp_pf_cache[i++].val,BLOCK_SIZE,"%s",alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_EXT_PORT_RANGE,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_PFR_PUBLIC_IP,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			rc = sprintf_s(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_PFR_INT_RANGE,alias_pre);
			if(rc < EOK) ERR_CHK(rc);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_IP,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_NAME,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_ENABLE,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_PROTO,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_INT_PORT,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			snprintf(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_IPV6,alias_pre);
			memset(tmp_pf_cache[i].cmd,0,BLOCK_SIZE);
			rc = sprintf_s(tmp_pf_cache[i++].cmd,BLOCK_SIZE,"%s"ALIAS_POS_PREV_STATE,alias_pre);
			if(rc < EOK) ERR_CHK(rc);
		}

	}
	pf_cache_size = i;
}

/* CallBack API to execute Portforwarding Blob request */
pErr Process_PF_WebConfigRequest(void *Data)
{

    	pErr execRetVal = NULL;
        int lpfEnable = 0;
    	execRetVal = (pErr) malloc (sizeof(Err));
    	if (execRetVal == NULL )
    	{
        	CcspTraceError(("%s : malloc failed\n",__FUNCTION__));
        	return execRetVal;
    	}

    	memset(execRetVal,0,sizeof(Err));

    	execRetVal->ErrorCode = BLOB_EXEC_SUCCESS;

    	portmappingdoc_t *rpm = (portmappingdoc_t *) Data ;

        CcspTraceWarning(("rpm->entries_count is %d\n", rpm->entries_count));
    	CcspTraceWarning(("Portmap configurartion recieved\n"));

    	backup_pf_cache(pf_cache,pf_cache_bkup,pf_cache_size);
    	pf_cache_size_bkup = pf_cache_size;

        if ( SYSCFG_FAILURE == clear_pf_cache_DB(pf_cache) )
        {
                CcspTraceError(("%s: Failed to clear_pf_cache_DB\n",__FUNCTION__));
             //   portmappingdoc_destroy( rpm );

                execRetVal->ErrorCode = SYSCFG_FAILURE;

                strncpy(execRetVal->ErrorMsg,"sysconfig failure while clearing old entries",sizeof(execRetVal->ErrorMsg)-1);

                return execRetVal;

        }

        int ret  = set_portmap_conf(rpm) ;
    	if ( 0 != ret )
        {
            if ( INVALID_IP == ret )
            {
                CcspTraceError(("%s : Invalid IP\n",__FUNCTION__));
                execRetVal->ErrorCode = INVALID_IP;

                strncpy(execRetVal->ErrorMsg,"Invalid IP",sizeof(execRetVal->ErrorMsg)-1);

            }
            else if ( INVALID_PORT == ret )
            {
                CcspTraceError(("%s : Invalid Port\n",__FUNCTION__));
                execRetVal->ErrorCode = INVALID_PORT;

                strncpy(execRetVal->ErrorMsg,"Invalid Port",sizeof(execRetVal->ErrorMsg)-1);

            }

            else if ( INVALID_PROTOCOL == ret )
            {
                CcspTraceError(("%s : Invalid Protocol\n",__FUNCTION__));
                execRetVal->ErrorCode = INVALID_PROTOCOL;

                strncpy(execRetVal->ErrorMsg,"Invalid Protocol",sizeof(execRetVal->ErrorMsg)-1);

            }

            //portmappingdoc_destroy( rpm );

            return execRetVal;
        }
        if ( rpm->entries_count > 0 )
                lpfEnable = 1 ;

    	if ( SYSCFG_FAILURE == apply_pf_cache_ToDB(pf_cache,pf_cache_size, lpfEnable ) )
    	{
            	CcspTraceError(("Failed to apply Portmap configurartion\n"));
            	//portmappingdoc_destroy( rpm );

            	execRetVal->ErrorCode = SYSCFG_FAILURE;

            	strncpy(execRetVal->ErrorMsg,"sysconfig failure while applying",sizeof(execRetVal->ErrorMsg)-1);

            	return execRetVal;

    	}

     	CcspTraceWarning(("Portmap configurartion applied\n"));
        gpfEnable = lpfEnable;
    	int i;
    	for(i = 0; i < (int)rpm->entries_count ; i++)
    	{
            CcspTraceWarning(("rpm->entries[%d].InternalClient %s\n", i, rpm->entries[i].internal_client));
            CcspTraceWarning(("rpm->entries[%d].ExternalPortEndRange %s\n" , i, rpm->entries[i].external_port_end_range));
            CcspTraceWarning(("rpm->entries[%d].Enable %s\n", i, rpm->entries[i].enable?"true":"false"));
            CcspTraceWarning(("rpm->entries[%d].Protocol %s\n", i, rpm->entries[i].protocol));
            CcspTraceWarning(("rpm->entries[%d].Description %s\n", i, rpm->entries[i].description));
            CcspTraceWarning(("rpm->entries[%d].external_port %s\n", i, rpm->entries[i].external_port));
    	}

      //  portmappingdoc_destroy( rpm );

    	return execRetVal;

}

/* Callback function to rollback when port forwarding blob execution fails */
int rollback_PortForwarding()
{
    // return 0 to notify framework when rollback is success
    CcspTraceInfo((" Entering %s \n",__FUNCTION__));

    int ret = 0;
    ret = apply_pf_cache_ToDB(pf_cache_bkup,pf_cache_size_bkup,  gpfEnable ) ;

    backup_pf_cache(pf_cache_bkup,pf_cache,pf_cache_size_bkup);

    pf_cache_size = pf_cache_size_bkup;

    return ret ;
}

void freeResources_PortForwarding(void *arg)
{

    CcspTraceInfo((" Entering %s \n",__FUNCTION__));
    execData *blob_exec_data  = (execData*) arg;
    /* CID: 158629 Dereference before null check*/
    if(!blob_exec_data)
        return;

    portmappingdoc_t *rpm = (portmappingdoc_t *) blob_exec_data->user_data ;

    if ( rpm != NULL )
    {
        portmappingdoc_destroy( rpm );
        rpm = NULL;
    }

    if ( blob_exec_data != NULL )
    {
        free(blob_exec_data);
        blob_exec_data = NULL ;
    }
}


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

TimelineModel.TimelineProfileTree = {};

/**
 * @unrestricted
 */
TimelineModel.TimelineProfileTree.Node = class {
  /**
   * @param {string} id
   * @param {?SDK.TracingModel.Event} event
   */
  constructor(id, event) {
    /** @type {number} */
    this.totalTime = 0;
    /** @type {number} */
    this.selfTime = 0;
    /** @type {string} */
    this.id = id;
    /** @type {?SDK.TracingModel.Event} */
    this.event = event;
    /** @type {?TimelineModel.TimelineProfileTree.Node} */
    this.parent;

    /** @type {string} */
    this._groupId = '';
    this._isGroupNode = false;
  }

  /**
   * @return {boolean}
   */
  isGroupNode() {
    return this._isGroupNode;
  }

  /**
   * @return {boolean}
   */
  hasChildren() {
    throw 'Not implemented';
  }

  /**
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  children() {
    throw 'Not implemented';
  }

  /**
   * @param {function(!SDK.TracingModel.Event):boolean} matchFunction
   * @param {!Array<!TimelineModel.TimelineProfileTree.Node>=} results
   * @return {!Array<!TimelineModel.TimelineProfileTree.Node>}
   */
  searchTree(matchFunction, results) {
    results = results || [];
    if (this.event && matchFunction(this.event))
      results.push(this);
    for (const child of this.children().values())
      child.searchTree(matchFunction, results);
    return results;
  }
};

TimelineModel.TimelineProfileTree.TopDownNode = class extends TimelineModel.TimelineProfileTree.Node {
  /**
   * @param {string} id
   * @param {?SDK.TracingModel.Event} event
   * @param {?TimelineModel.TimelineProfileTree.TopDownNode} parent
   */
  constructor(id, event, parent) {
    super(id, event);
    /** @type {?TimelineModel.TimelineProfileTree.TopDownRootNode} */
    this._root = parent && parent._root;
    this._hasChildren = false;
    this._children = null;
    this.parent = parent;
  }

  /**
   * @override
   * @return {boolean}
   */
  hasChildren() {
    return this._hasChildren;
  }

  /**
   * @override
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  children() {
    return this._children || this._buildChildren();
  }

  /**
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  _buildChildren() {
    /** @type {!Array<!TimelineModel.TimelineProfileTree.TopDownNode>} */
    const path = [];
    for (let node = this; node.parent && !node._isGroupNode; node = node.parent)
      path.push(/** @type {!TimelineModel.TimelineProfileTree.TopDownNode} */ (node));
    path.reverse();
    /** @type {!Map<string, !TimelineModel.TimelineProfileTree.Node>} */
    const children = new Map();
    const self = this;
    const root = this._root;
    const startTime = root._startTime;
    const endTime = root._endTime;
    const instantEventCallback = root._doNotAggregate ? onInstantEvent : undefined;
    const eventIdCallback = root._doNotAggregate ? undefined : TimelineModel.TimelineProfileTree._eventId;
    const eventGroupIdCallback = root._eventGroupIdCallback;
    let depth = 0;
    let matchedDepth = 0;
    let currentDirectChild = null;
    TimelineModel.TimelineModel.forEachEvent(
        root._events, onStartEvent, onEndEvent, instantEventCallback, startTime, endTime, root._filter);

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onStartEvent(e) {
      ++depth;
      if (depth > path.length + 2)
        return;
      if (!matchPath(e))
        return;
      const duration = Math.min(endTime, e.endTime) - Math.max(startTime, e.startTime);
      if (duration < 0)
        console.error('Negative event duration');
      processEvent(e, duration);
    }

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onInstantEvent(e) {
      ++depth;
      if (matchedDepth === path.length && depth <= path.length + 2)
        processEvent(e, 0);
      --depth;
    }

    /**
     * @param {!SDK.TracingModel.Event} e
     * @param {number} duration
     */
    function processEvent(e, duration) {
      if (depth === path.length + 2) {
        currentDirectChild._hasChildren = true;
        currentDirectChild.selfTime -= duration;
        return;
      }
      let id;
      let groupId = '';
      if (!eventIdCallback) {
        id = Symbol('uniqueId');
      } else {
        id = eventIdCallback(e);
        groupId = eventGroupIdCallback ? eventGroupIdCallback(e) : '';
        if (groupId)
          id += '/' + groupId;
      }
      let node = children.get(id);
      if (!node) {
        node = new TimelineModel.TimelineProfileTree.TopDownNode(id, e, self);
        node._groupId = groupId;
        children.set(id, node);
      }
      node.selfTime += duration;
      node.totalTime += duration;
      currentDirectChild = node;
    }

    /**
     * @param {!SDK.TracingModel.Event} e
     * @return {boolean}
     */
    function matchPath(e) {
      if (matchedDepth === path.length)
        return true;
      if (matchedDepth !== depth - 1)
        return false;
      if (!e.endTime)
        return false;
      if (!eventIdCallback) {
        if (e === path[matchedDepth].event)
          ++matchedDepth;
        return false;
      }
      let id = eventIdCallback(e);
      const groupId = eventGroupIdCallback ? eventGroupIdCallback(e) : '';
      if (groupId)
        id += '/' + groupId;
      if (id === path[matchedDepth].id)
        ++matchedDepth;
      return false;
    }

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onEndEvent(e) {
      --depth;
      if (matchedDepth > depth)
        matchedDepth = depth;
    }

    this._children = children;
    return children;
  }
};

TimelineModel.TimelineProfileTree.TopDownRootNode = class extends TimelineModel.TimelineProfileTree.TopDownNode {
  /**
   * @param {!Array<!SDK.TracingModel.Event>} events
   * @param {!Array<!TimelineModel.TimelineModelFilter>} filters
   * @param {number} startTime
   * @param {number} endTime
   * @param {boolean=} doNotAggregate
   * @param {?function(!SDK.TracingModel.Event):string=} eventGroupIdCallback
   */
  constructor(events, filters, startTime, endTime, doNotAggregate, eventGroupIdCallback) {
    super('', null, null);
    this._root = this;
    this._events = events;
    this._filter = e => filters.every(f => f.accept(e));
    this._startTime = startTime;
    this._endTime = endTime;
    this._eventGroupIdCallback = eventGroupIdCallback;
    this._doNotAggregate = doNotAggregate;
    this.totalTime = endTime - startTime;
    this.selfTime = this.totalTime;
  }

  /**
   * @override
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  children() {
    return this._children || this._grouppedTopNodes();
  }

  /**
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  _grouppedTopNodes() {
    const flatNodes = super.children();
    for (const node of flatNodes.values())
      this.selfTime -= node.totalTime;
    if (!this._eventGroupIdCallback)
      return flatNodes;
    const groupNodes = new Map();
    for (const node of flatNodes.values()) {
      const groupId = this._eventGroupIdCallback(/** @type {!SDK.TracingModel.Event} */ (node.event));
      let groupNode = groupNodes.get(groupId);
      if (!groupNode) {
        groupNode = new TimelineModel.TimelineProfileTree.GroupNode(
            groupId, this, /** @type {!SDK.TracingModel.Event} */ (node.event));
        groupNodes.set(groupId, groupNode);
      }
      groupNode.addChild(node, node.selfTime, node.totalTime);
    }
    this._children = groupNodes;
    return groupNodes;
  }
};

TimelineModel.TimelineProfileTree.BottomUpRootNode = class extends TimelineModel.TimelineProfileTree.Node {
  /**
   * @param {!Array<!SDK.TracingModel.Event>} events
   * @param {!Array<!TimelineModel.TimelineModelFilter>} filters
   * @param {number} startTime
   * @param {number} endTime
   * @param {?function(!SDK.TracingModel.Event):string} eventGroupIdCallback
   */
  constructor(events, filters, startTime, endTime, eventGroupIdCallback) {
    super('', null);
    /** @type {?Map<string, !TimelineModel.TimelineProfileTree.Node>} */
    this._children = null;
    this._events = events;
    this._filter = e => filters.every(f => f.accept(e));
    this._startTime = startTime;
    this._endTime = endTime;
    this._eventGroupIdCallback = eventGroupIdCallback;
    this.totalTime = endTime - startTime;
  }

  /**
   * @override
   * @return {boolean}
   */
  hasChildren() {
    return true;
  }

  /**
   * @override
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  children() {
    return this._children || this._grouppedTopNodes();
  }

  /**
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  _ungrouppedTopNodes() {
    const root = this;
    const startTime = this._startTime;
    const endTime = this._endTime;
    /** @type {!Map<string, !TimelineModel.TimelineProfileTree.Node>} */
    const nodeById = new Map();
    /** @type {!Array<number>} */
    const selfTimeStack = [endTime - startTime];
    /** @type {!Array<boolean>} */
    const firstNodeStack = [];
    /** @type {!Map<string, number>} */
    const totalTimeById = new Map();
    TimelineModel.TimelineModel.forEachEvent(
        this._events, onStartEvent, onEndEvent, undefined, startTime, endTime, this._filter);

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onStartEvent(e) {
      const duration = Math.min(e.endTime, endTime) - Math.max(e.startTime, startTime);
      selfTimeStack[selfTimeStack.length - 1] -= duration;
      selfTimeStack.push(duration);
      const id = TimelineModel.TimelineProfileTree._eventId(e);
      const noNodeOnStack = !totalTimeById.has(id);
      if (noNodeOnStack)
        totalTimeById.set(id, duration);
      firstNodeStack.push(noNodeOnStack);
    }

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onEndEvent(e) {
      const id = TimelineModel.TimelineProfileTree._eventId(e);
      let node = nodeById.get(id);
      if (!node) {
        node = new TimelineModel.TimelineProfileTree.BottomUpNode(root, id, e, true, root);
        nodeById.set(id, node);
      }
      node.selfTime += selfTimeStack.pop();
      if (firstNodeStack.pop()) {
        node.totalTime += totalTimeById.get(id);
        totalTimeById.delete(id);
      }
    }

    this.selfTime = selfTimeStack.pop();
    for (const pair of nodeById) {
      if (pair[1].selfTime <= 0)
        nodeById.delete(/** @type {string} */ (pair[0]));
    }
    return nodeById;
  }

  /**
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  _grouppedTopNodes() {
    const flatNodes = this._ungrouppedTopNodes();
    if (!this._eventGroupIdCallback) {
      this._children = flatNodes;
      return flatNodes;
    }
    const groupNodes = new Map();
    for (const node of flatNodes.values()) {
      const groupId = this._eventGroupIdCallback(/** @type {!SDK.TracingModel.Event} */ (node.event));
      let groupNode = groupNodes.get(groupId);
      if (!groupNode) {
        groupNode = new TimelineModel.TimelineProfileTree.GroupNode(
            groupId, this, /** @type {!SDK.TracingModel.Event} */ (node.event));
        groupNodes.set(groupId, groupNode);
      }
      groupNode.addChild(node, node.selfTime, node.selfTime);
    }
    this._children = groupNodes;
    return groupNodes;
  }
};

TimelineModel.TimelineProfileTree.GroupNode = class extends TimelineModel.TimelineProfileTree.Node {
  /**
   * @param {string} id
   * @param {!TimelineModel.TimelineProfileTree.BottomUpRootNode|!TimelineModel.TimelineProfileTree.TopDownRootNode} parent
   * @param {!SDK.TracingModel.Event} event
   */
  constructor(id, parent, event) {
    super(id, event);
    this._children = new Map();
    this.parent = parent;
    this._isGroupNode = true;
  }

  /**
   * @param {!TimelineModel.TimelineProfileTree.BottomUpNode} child
   * @param {number} selfTime
   * @param {number} totalTime
   */
  addChild(child, selfTime, totalTime) {
    this._children.set(child.id, child);
    this.selfTime += selfTime;
    this.totalTime += totalTime;
    child.parent = this;
  }

  /**
   * @override
   * @return {boolean}
   */
  hasChildren() {
    return true;
  }

  /**
   * @override
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  children() {
    return this._children;
  }
};

TimelineModel.TimelineProfileTree.BottomUpNode = class extends TimelineModel.TimelineProfileTree.Node {
  /**
   * @param {!TimelineModel.TimelineProfileTree.BottomUpRootNode} root
   * @param {string} id
   * @param {!SDK.TracingModel.Event} event
   * @param {boolean} hasChildren
   * @param {!TimelineModel.TimelineProfileTree.Node} parent
   */
  constructor(root, id, event, hasChildren, parent) {
    super(id, event);
    this.parent = parent;
    this._root = root;
    this._depth = (parent._depth || 0) + 1;
    this._cachedChildren = null;
    this._hasChildren = hasChildren;
  }

  /**
   * @override
   * @return {boolean}
   */
  hasChildren() {
    return this._hasChildren;
  }

  /**
   * @override
   * @return {!Map<string, !TimelineModel.TimelineProfileTree.Node>}
   */
  children() {
    if (this._cachedChildren)
      return this._cachedChildren;
    /** @type {!Array<number>} */
    const selfTimeStack = [0];
    /** @type {!Array<string>} */
    const eventIdStack = [];
    /** @type {!Array<!SDK.TracingModel.Event>} */
    const eventStack = [];
    /** @type {!Map<string, !TimelineModel.TimelineProfileTree.Node>} */
    const nodeById = new Map();
    const startTime = this._root._startTime;
    const endTime = this._root._endTime;
    let lastTimeMarker = startTime;
    const self = this;
    TimelineModel.TimelineModel.forEachEvent(
        this._root._events, onStartEvent, onEndEvent, undefined, startTime, endTime, this._root._filter);

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onStartEvent(e) {
      const duration = Math.min(e.endTime, endTime) - Math.max(e.startTime, startTime);
      if (duration < 0)
        console.assert(false, 'Negative duration of an event');
      selfTimeStack[selfTimeStack.length - 1] -= duration;
      selfTimeStack.push(duration);
      const id = TimelineModel.TimelineProfileTree._eventId(e);
      eventIdStack.push(id);
      eventStack.push(e);
    }

    /**
     * @param {!SDK.TracingModel.Event} e
     */
    function onEndEvent(e) {
      const selfTime = selfTimeStack.pop();
      const id = eventIdStack.pop();
      eventStack.pop();
      let node;
      for (node = self; node._depth > 1; node = node.parent) {
        if (node.id !== eventIdStack[eventIdStack.length + 1 - node._depth])
          return;
      }
      if (node.id !== id || eventIdStack.length < self._depth)
        return;
      const childId = eventIdStack[eventIdStack.length - self._depth];
      node = nodeById.get(childId);
      if (!node) {
        const event = eventStack[eventStack.length - self._depth];
        const hasChildren = eventStack.length > self._depth;
        node = new TimelineModel.TimelineProfileTree.BottomUpNode(self._root, childId, event, hasChildren, self);
        nodeById.set(childId, node);
      }
      const totalTime = Math.min(e.endTime, endTime) - Math.max(e.startTime, lastTimeMarker);
      node.selfTime += selfTime;
      node.totalTime += totalTime;
      lastTimeMarker = Math.min(e.endTime, endTime);
    }

    this._cachedChildren = nodeById;
    return nodeById;
  }

  /**
   * @override
   * @param {function(!SDK.TracingModel.Event):boolean} matchFunction
   * @param {!Array<!TimelineModel.TimelineProfileTree.Node>=} results
   * @return {!Array<!TimelineModel.TimelineProfileTree.Node>}
   */
  searchTree(matchFunction, results) {
    results = results || [];
    if (this.event && matchFunction(this.event))
      results.push(this);
    return results;
  }
};

/**
 * @param {!SDK.TracingModel.Event} event
 * @return {?string}
 */
TimelineModel.TimelineProfileTree.eventURL = function(event) {
  const data = event.args['data'] || event.args['beginData'];
  if (data && data['url'])
    return data['url'];
  let frame = TimelineModel.TimelineProfileTree.eventStackFrame(event);
  while (frame) {
    const url = frame['url'];
    if (url)
      return url;
    frame = frame.parent;
  }
  return null;
};

/**
 * @param {!SDK.TracingModel.Event} event
 * @return {?Protocol.Runtime.CallFrame}
 */
TimelineModel.TimelineProfileTree.eventStackFrame = function(event) {
  if (event.name === TimelineModel.TimelineModel.RecordType.JSFrame)
    return /** @type {?Protocol.Runtime.CallFrame} */ (event.args['data'] || null);
  return TimelineModel.TimelineData.forEvent(event).topFrame();
};

/**
 * @param {!SDK.TracingModel.Event} event
 * @return {string}
 */
TimelineModel.TimelineProfileTree._eventId = function(event) {
  if (event.name === TimelineModel.TimelineModel.RecordType.TimeStamp)
    return `${event.name}:${event.args.data.message}`;
  if (event.name !== TimelineModel.TimelineModel.RecordType.JSFrame)
    return event.name;
  const frame = event.args['data'];
  const location = frame['scriptId'] || frame['url'] || '';
  const functionName = frame['functionName'];
  const name = TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame) ?
      TimelineModel.TimelineJSProfileProcessor.nativeGroup(functionName) || functionName :
      `${functionName}:${frame['lineNumber']}:${frame['columnNumber']}`;
  return `f:${name}@${location}`;
};


text:
package dshell.internal.lib;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

import dshell.lang.GenericPair;

/**
 * contain global variable.
 * @author skgchxngsxyz-osx
 *
 */
public class GlobalVariableTable {
	private final static int MAX_INDEX = Integer.MAX_VALUE;
	private final static int defaultTableSize = 16;

	/**
	 * global variable table for long value.
	 */
	public static long[]    longVarTable;

	/**
	 * global variable table for double value.
	 */
	public static double[]  doubleVarTable;

	/**
	 * global variable table for boolean value.
	 */
	public static boolean[] booleanVarTable;

	/**
	 * global variable table for object value.
	 */
	public static Object[]  objectVarTable;

	private static int longVarIndexCount    = 0;
	private static int doubleVarIndexCount  = 0;
	private static int booleanVarIndexCount = 0;
	private static int objectVarIndexCount  = 0;

	private static Map<String, GenericPair<Integer, Class<?>>> indexMap = new HashMap<>();

	private static Deque<Integer> unusedLongIndexStack    = new ArrayDeque<>();
	private static Deque<Integer> unusedDoubleIndexStack  = new ArrayDeque<>();
	private static Deque<Integer> unusedBooleanIndexStack = new ArrayDeque<>();
	private static Deque<Integer> unusedObjectIndexStack  = new ArrayDeque<>();

	static {
		longVarTable = new long[defaultTableSize];
		doubleVarTable = new double[defaultTableSize];
		booleanVarTable = new boolean[defaultTableSize];
		objectVarTable = new Object[defaultTableSize];
	}

	// create new global variable entry
	public static int newLongVarEntry(String varName) {
		checkDuplicatedEntry(varName);
		if(!unusedLongIndexStack.isEmpty()) {
			return unusedLongIndexStack.pop();
		}

		final int size = longVarTable.length;
		if(longVarIndexCount == size) {
			checkIndexRange(size);
			longVarTable = Arrays.copyOf(longVarTable, size * 2);
		}
		final int varIndex = longVarIndexCount++;
		indexMap.put(varName, new GenericPair<Integer, Class<?>>(varIndex, long.class));
		return varIndex;
	}

	public static int newDoubleVarEntry(String varName) {
		checkDuplicatedEntry(varName);
		if(!unusedDoubleIndexStack.isEmpty()) {
			return unusedDoubleIndexStack.pop();
		}

		final int size = doubleVarTable.length;
		if(doubleVarIndexCount == size) {
			checkIndexRange(size);
			doubleVarTable = Arrays.copyOf(doubleVarTable, size * 2);
		}
		final int varIndex = doubleVarIndexCount++;
		indexMap.put(varName, new GenericPair<Integer, Class<?>>(varIndex, double.class));
		return varIndex;
	}

	public static int newBooleanVarEntry(String varName) {
		checkDuplicatedEntry(varName);
		if(!unusedBooleanIndexStack.isEmpty()) {
			return unusedBooleanIndexStack.pop();
		}

		final int size = booleanVarTable.length;
		if(booleanVarIndexCount == size) {
			checkIndexRange(size);
			booleanVarTable = Arrays.copyOf(booleanVarTable, size * 2);
		}
		final int varIndex = booleanVarIndexCount++;
		indexMap.put(varName, new GenericPair<Integer, Class<?>>(varIndex, boolean.class));
		return varIndex;
	}

	public static int newObjectVarEntry(String varName) {
		checkDuplicatedEntry(varName);
		if(!unusedObjectIndexStack.isEmpty()) {
			return unusedObjectIndexStack.pop();
		}

		final int size = objectVarTable.length;
		if(objectVarIndexCount == size) {
			checkIndexRange(size);
			objectVarTable = Arrays.copyOf(objectVarTable, size * 2);
		}
		final int varIndex = objectVarIndexCount++;
		indexMap.put(varName, new GenericPair<Integer, Class<?>>(varIndex, Object.class));
		return varIndex;
	}

	private static void checkDuplicatedEntry(String varName) {
		GenericPair<Integer, Class<?>> pair = indexMap.get(varName);
		if(pair != null) {
			// find duplicated entry and push to unused index stack
			int index = pair.getLeft();
			Class<?> clazz = pair.getRight();
			if(clazz == long.class) {
				unusedLongIndexStack.push(index);
			} else if(clazz == double.class) {
				unusedDoubleIndexStack.push(index);
			} else if(clazz == boolean.class) {
				unusedBooleanIndexStack.push(index);
			} else if(clazz == Object.class) {
				unusedObjectIndexStack.push(index);
			} else {
				Utils.fatal(1, "illegal class: " + clazz);
			}
		}
	}

	/**
	 * force terminate if index out of max integer
	 * @param size
	 */
	private static void checkIndexRange(int size) {
		if(size >= MAX_INDEX) {
			Utils.fatal(1, "too many global variable");
		}
	}

	private static GenericPair<Integer, Class<?>> getIndexPair(String varName) {
		GenericPair<Integer, Class<?>> indexPair = indexMap.get(varName);
		if(indexPair == null) {
			Utils.fatal(1, "undefined global variable: " + varName);
		}
		return indexPair;
	}
	/**
	 * get var index
	 * @param varName
	 * @return
	 * - force terminate if has no var entry
	 */
	public static int getVarIndex(String varName) {
		return getIndexPair(varName).getLeft();
	}

	private static void checkVarClass(GenericPair<Integer, Class<?>> indexPair, Class<?> targetClass) {
		if(!indexPair.getRight().equals(targetClass)) {
			Utils.fatal(1, "require " + targetClass + ", but is " + indexPair.getRight());
		}
	}

	// get global variable
	public static long getLongVar(String varName) {
		GenericPair<Integer, Class<?>> indexPair = getIndexPair(varName);
		checkVarClass(indexPair, long.class);
		return longVarTable[indexPair.getLeft()];
	}

	public static double getDoubleVar(String varName) {
		GenericPair<Integer, Class<?>> indexPair = getIndexPair(varName);
		checkVarClass(indexPair, double.class);
		return doubleVarTable[indexPair.getLeft()];
	}

	public static boolean getBooleanVar(String varName) {
		GenericPair<Integer, Class<?>> indexPair = getIndexPair(varName);
		checkVarClass(indexPair, boolean.class);
		return booleanVarTable[indexPair.getLeft()];
	}

	@SuppressWarnings("unchecked")
	public static <T> T getObjectVar(String varName, Class<T> clazz) {
		GenericPair<Integer, Class<?>> indexPair = getIndexPair(varName);
		checkVarClass(indexPair, Object.class);
		return (T) objectVarTable[indexPair.getLeft()];
	}

	// add new global variable
	public static void addNewLongVar(String varName, long value) {
		longVarTable[newLongVarEntry(varName)] = value;
	}

	public static void addNewDoubleVar(String varName, double value) {
		doubleVarTable[newDoubleVarEntry(varName)] = value;
	}

	public static void addNewBooleanVar(String varName, boolean value) {
		booleanVarTable[newBooleanVarEntry(varName)] = value;
	}

	public static void addNewObjectVar(String varName, Object value) {
		objectVarTable[newObjectVarEntry(varName)] = value;
	}

	public static boolean checkVarExistence(String varName) {
		return indexMap.containsKey(varName);
	}
}


text:
You may want to add additional parameters to each beacon.  For example, you may
want to tag the beacon with a Page Group or you may want to do A/B testing and
tag the beacon specifying which bucket this beacon is for.  You can achieve all
of this using {@link BOOMR.addVar BOOMR.addVar()}.

Before you use this method, remember that each plugin adds its own parameters
and you should avoid overwriting these with your own values.  See
{@link BOOMR Boomerang} and each {@link BOOMR.plugins plugin} for documentation
on what data it adds to the beacon.

## Adding Data to the Beacon

{@link BOOMR.addVar} can be used to add any arbitrary data you want to the beacon.

Example usage:

```javascript
BOOMR.addVar("ab_test", "a");
```

If you need to set multiple parameters, you can supply an object instead:

```javascript
BOOMR.addVar({
  "ab_test": "a"
  "customer_id": 123
});
```

The beacon will include all variables that you add in the URL.  Both keys and
values will be URI encoded.  Your beacon endpoint will need to understand
the data.

```
http://yoursite.com/beacon/?t_done=500&ab_test=1&customer_id=123&...
```

## Removing Data from the Beacon

You can also remove a parameter that you've added (or that a plugin has added)
from the beacon.  To do this, call {@link BOOMR.removeVar}:

```javascript
// remove a single parameter
BOOMR.removeVar("ab_test");

// remove multiple parameters
BOOMR.removeVar("ab_test", "customer_id", "something_else");
```


text:
This module contains the following resources/facilities which are useful for testing:

- A facility class that creates the directory structure for a simple server and copies the required
  resources from the classpath in order to provide a minimalistic environment. For more details, check:

      org.carlspring.strongbox.storage.StorageManager.createServerLayout(String basedir)

You should add this project as a test scoped dependency to any Strongbox module which needs to have
a proper directory skeleton with the required resources. This would avoid you having to duplicate resources,
while also simplifying your tests' readability.


text:
TEST_(SuccessIsTrue) {
  DynamicJsonBuffer _jsonBuffer;
  JsonArray& array = _jsonBuffer.createArray();

  EXPECT_TRUE(array.success());
}

TEST_(InitialSizeIsZero) {
  DynamicJsonBuffer _jsonBuffer;
  JsonArray& array = _jsonBuffer.createArray();

  EXPECT_EQ(0U, array.size());
}

TEST_(CreateNestedArray) {
  DynamicJsonBuffer _jsonBuffer;
  JsonArray& array = _jsonBuffer.createArray();

  JsonArray& arr = array.createNestedArray();
  EXPECT_EQ(&arr, &array[0].as<JsonArray&>());
}

TEST_(CreateNestedObject) {
  DynamicJsonBuffer _jsonBuffer;
  JsonArray& array = _jsonBuffer.createArray();

  JsonObject& obj = array.createNestedObject();
  EXPECT_EQ(&obj, &array[0].as<JsonObject&>());
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>RbaiAdmin</title>
  <base href="/admin/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

<link href="styles.98becd514f4fc64c2be8.bundle.css" rel="stylesheet">

  <app-root>Loading...</app-root>


text:
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="mysql_normaltbl_oneGroup_oneAtom" class="com.taobao.tddl.client.sequence.impl.GroupSequence" init-method="init">
		<property name="sequenceDao" ref="sequenceDao" />
		<property name="name" value="mysql_normaltbl_oneGroup_oneAtom" />
	</bean>

	<bean id="mysql_normaltbl_oneGroup_mutilAtom" class="com.taobao.tddl.client.sequence.impl.GroupSequence" init-method="init">
		<property name="sequenceDao" ref="sequenceDao" />
		<property name="name" value="mysql_normaltbl_oneGroup_mutilAtom" />
	</bean>

	<bean id="mysql_normaltbl_mutilGroup" class="com.taobao.tddl.client.sequence.impl.GroupSequence" init-method="init">
		<property name="sequenceDao" ref="sequenceDao" />
		<property name="name" value="mysql_normaltbl_mutilGroup" />
	</bean>

	<bean id="ob_normaltbl_oneGroup_oneAtom" class="com.taobao.tddl.client.sequence.impl.GroupSequence" init-method="init">
		<property name="sequenceDao" ref="sequenceDao" />
		<property name="name" value="ob_normaltbl_oneGroup_oneAtom" />
	</bean>

	<bean id="sequenceDao" class="com.taobao.tddl.client.sequence.impl.GroupSequenceDao"
		init-method="init">
		<!--appName ,±ØÌî -->
		<property name="appName" value="andor_mysql_qatest" />
		<!--Êý¾ÝÔ´µÄ¸öÊý -->
		<property name="dscount" value="1" />
		<!--dbGroupKeys±ØÌî -->
		<property name="dbGroupKeys">
			<list>
				<value>andor_mysql_group_0</value>
			</list>
		</property>
		<!--ÄÚ²½³¤ -->
		<property name="innerStep" value="100" />
		<!--ÊÇ·ñ¿ªÆô×ÔÊÊÓ¦£¬Ä¬ÈÏÊÇfalse -->
		<property name="adjust" value="true" />
		<property name="retryTimes" value="100" />

		<property name="gmtModifiedColumnName" value="gmt_modified" />
		<property name="nameColumnName" value="name" />
		<property name="tableName" value="sequence" />
		<property name="valueColumnName" value="value" />
	</bean>
</beans>


text:
title: OrderedThreadPool – Bug Fix !!!
author: vivekragunathan
layout: post
date: 2012-04-13T19:50:01+00:00
url: /2012/04/14/otp-bug-fix/
categories:
  - .NET
  - 'C#'
  - Uncategorized

---
Hugh pointed out a [bug](http://www.blogger.com/comment.g?blogID=11793007&postID=8394495887151499024) in the [OrderedThreadPool](/2009/03/18/ordered-thread-pool).

I think there is a small window for error in the OrderedThreadPool class. Basically, if an item of work is queued, then a worker thread runs, takes the item off the queue and is about to call `wcb(state)` – but at that instant is (say) context switched. Then another item gets queued and another worker thread runs and dequeues the item and then again is about to call `wcb(state)`. There is scope here for the two operations to run concurrently or even out of order…

Here is the fixed version of the same.

```csharp
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace System.Threading
{
 public class OrderedThreadPool
 {
  private Queue workItemQ = new Queue();
  private bool loopWorkRunning = false;

  public void QueueUserWorkItem(WaitCallback wcbDelegate, object state)
  {
   lock (workItemQ)
   {
    workItemQ.Enqueue(new ThreadPoolTaskInfo(wcbDelegate, state));

    if (workItemQ.Count == 1 && !loopWorkRunning)
    {
     loopWorkRunning = true;
     ThreadPool.QueueUserWorkItem(LoopWork);
    }
   }
  }

  private void LoopWork(object notUsed)
  {
   WaitCallback wcb = null;
   object state = null;

   lock (workItemQ)
   {
    if (workItemQ.Count == 0)
    {
     loopWorkRunning = false;
     return;
    }

    ThreadPoolTaskInfo tptInfo = workItemQ.Dequeue();
    state = tptInfo.State;
    wcb = tptInfo.CallbackDelegate;
    Debug.Assert(wcb != null);
   }

   try
   {
    wcb(state);
   }
   finally
   {
    ThreadPool.QueueUserWorkItem(LoopWork, notUsed);
   }
  }

  public struct ThreadPoolTaskInfo
  {
   public readonly WaitCallback CallbackDelegate;
   public readonly object State;

   public ThreadPoolTaskInfo(WaitCallback wc, object state)
   {
    Debug.Assert(wc != null);
    CallbackDelegate = wc;
    State = state;
   }
  }
 }
}
```


text:
<?php

namespace Core\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * FormasPagamento
 *
 * @ORM\Table(name="formas_pagamento")
 * @ORM\Entity
 */
class FormasPagamento
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id_forma_pagamento", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idFormaPagamento;

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

    /**
     * Get idFormaPagamento
     *
     * @return integer
     */
    public function getIdFormaPagamento()
    {
        return $this->idFormaPagamento;
    }

    /**
     * Set forma
     *
     * @param string $forma
     * @return FormasPagamento
     */
    public function setForma($forma)
    {
        $this->forma = $forma;

        return $this;
    }

    /**
     * Get forma
     *
     * @return string
     */
    public function getForma()
    {
        return $this->forma;
    }
}


text:
<?php

namespace Guzzle\Iterator;

/**
 * Pulls out chunks from an inner iterator and yields the chunks as arrays
 */
class ChunkedIterator extends \IteratorIterator
{
    /**
     * @var int Size of each chunk
     */
    protected $chunkSize;

    /**
     * @var array Current chunk
     */
    protected $chunk;

    /**
     * @param \Traversable $iterator  Traversable iterator
     * @param int          $chunkSize Size to make each chunk
     */
    public function __construct(\Traversable $iterator, $chunkSize)
    {
        parent::__construct($iterator);
        $this->chunkSize = $chunkSize;
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        $this->next();
    }

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        $this->chunk = array();
        $inner = $this->getInnerIterator();
        for ($i = 0; $i < $this->chunkSize && $inner->valid(); $i++) {
            $this->chunk[] = $inner->current();
            $inner->next();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        return $this->chunk;
    }

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        return !empty($this->chunk);
    }
}


text:
[![Build Status](https://travis-ci.org/hoegaarden/pgpass.png?branch=master)](https://travis-ci.org/hoegaarden/pgpass)

## Install

```sh
npm install --save hoegaarden/pgpass
```

## Usage
```js
var pgPass = require('pgpass');

var connInfo = {
  'host' : 'pgserver' ,
  'user' : 'the_user_name' ,
};

// ---- async ----
pgPass(connInfo, function(pass){
  conn_info.password = pass;
  // connect to postgresql server
});
```

## Description

This module tries to read the `~/.pgpass` file (or the equivalent for windows systems). If the environment variable `PGPASSFILE` is set, this file is used instead. If everything goes right, the password from said file is to the callback; if the password cannot be read `undefined` is passed to the callback.

Cases where `undefined` is returned:

- the environment variable `PGPASSWORD` is set
- the file cannot be read (wrong permissions, no such file, ...)
- for non windows systems: the file is write-/readable by the group or by other users
- there is no matching line for the given connection info

The goal of this package is to get included in the `node-postgresql` module to get the same behaviour for the javascript client as for the native client.

## Tests

There are tests in `./test/`; including linting and coverage testing. Running `npm test` runs:

- `jshint`
- `mocha` tests
- `jscoverage` and `mocha -R html-cov`

You can see the coverage report in `coverage.html`.

## Development, Patches, Bugs, ...

If you find Bugs or have improvments, please feel free to open a issue on github. If you provide a pull request, I'm more than happy to merge them, just make sure to add tests for your changes.

## Links

- https://github.com/hoegaarden/node-pgpass
- http://www.postgresql.org/docs/current/static/libpq-pgpass.html
- https://wiki.postgresql.org/wiki/Pgpass
- https://github.com/postgres/postgres/blob/master/src/interfaces/libpq/fe-connect.c


text:
#ifndef __key_format_ltfs_h
#define __key_format_ltfs_h

#define DK_LENGTH 32
#define DKI_LENGTH 12
#define DKI_ASCII_LENGTH 3
#define	SEPARATOR_LENGTH 1 /* length of ':' and '/' */

struct key {
	unsigned char dk[DK_LENGTH];   /**< Data Key */
	unsigned char dki[DKI_LENGTH]; /**< Data Key Identifier */
};

struct key_format_ltfs {
	int num_of_keys;                  /**< Number of DK and DKi pairs */
	struct key *dk_list;              /**< DK and DKi pairs' list */
};

void *key_format_ltfs_init(struct ltfs_volume *vol);
int key_format_ltfs_destroy(void * const kmi_handle);
int key_format_ltfs_get_key(unsigned char **keyalias, unsigned char **key, void * const kmi_handle,
	unsigned char * const dk_list, unsigned char * const dki_for_format);

#endif /* __key_format_ltfs_h */


text:
title: Authentication
description: How authentication works in your B2C IAM implementation.
toc: true
topics:
    - b2c
    - ciam
    - authentication
    - universal-login
contentType: concept
useCase:
    - authentication
---
# Authentication

<%= include('../../_includes/_authentication/_introduction.md', { platform: 'b2c' }) %>

## Universal Login

<%= include('../../_includes/_authentication/_universal-login.md', { platform: 'b2c' }) %>

## Username and password authentication

<%= include('../../_includes/_authentication/_username-and-password-authentication.md', { platform: 'b2c' }) %>

## Application integration

<%= include('../../_includes/_authentication/_application-integration.md', { platform: 'b2c' }) %>

## Anomaly detection

<%= include('../../_includes/_authentication/_anomaly-detection.md', { platform: 'b2c' }) %>

## SSO with legacy systems

<%= include('../../_includes/_authentication/_sso-legacy.md', { platform: 'b2c' }) %>

## Social authentication

<%= include('../../_includes/_authentication/_social-authentication.md', { platform: 'b2c' }) %>

## Multi-factor authentication (MFA)

<%= include('../../_includes/_authentication/_mfa.md', { platform: 'b2c' }) %>

## Project Planning Guide

<%= include('../../_includes/_planning.md', { platform: 'b2c' }) %>

## Keep reading

* [Architecture](/architecture-scenarios/implementation/b2c/b2c-architecture)
* [Provisioning](/architecture-scenarios/implementation/b2c/b2c-provisioning)
* [Branding](/architecture-scenarios/implementation/b2c/b2c-branding)
* [Deployment Automation](/architecture-scenarios/implementation/b2c/b2c-deployment)
* [Quality Assurance](/architecture-scenarios/implementation/b2c/b2c-qa)
* [Profile Management](/architecture-scenarios/implementation/b2c/b2c-profile-mgmt)
* [Authorization](/architecture-scenarios/implementation/b2c/b2c-authorization)
* [Logout](/architecture-scenarios/implementation/b2c/b2c-logout)
* [Operations](/architecture-scenarios/implementation/b2c/b2c-operations)


text:
require "optparse"
module MetricFu
  module Cli
    # see https://github.com/florianpilz/CLI-Option-Parser-Examples
    # https://raw.github.com/florianpilz/micro-optparse/master/lib/micro-optparse/parser.rb
    module MicroOptParse
      class Parser
        attr_accessor :banner, :version
        def initialize
          @options = []
          @used_short = []
          @default_values = nil
          yield self if block_given?
        end

        def process!(arguments = ARGV)
          parser = build_option_parser
          process_options(parser, arguments)
        end

        def option(name, desc, settings = {})
          @options << [name, desc, settings]
        end

        private

        def build_option_parser
          @result = (@default_values || {}).clone # reset or new

          @optionparser ||= OptionParser.new do |p| # prepare only once
            configure_options(p)
          end
        end

        def process_options(parser, arguments)
          begin
            parser.parse!(arguments)
          rescue OptionParser::ParseError => e
            puts e.message
            MetricFu::Cli.immediate_shutdown!
          end

          @result
        end

        def configure_options(p)
          add_general_options(@options, p)

          add_format_option(p)
          add_output_option(p)

          p.banner = @banner unless @banner.nil?
          p.on_tail("-h", "--help", "Show this message") { puts p; success! }
          short = @used_short.include?("v") ? "-V" : "-v"
          p.on_tail(short, "--version", "Print version") { puts @version; success! } unless @version.nil?
          p.on_tail("--debug-info", "Print debug info") { debug_info; success! }
          @default_values = @result.clone # save default values to reset @result in subsequent calls
        end

        def add_general_options(options, p)
          options.each do |o|
            add_general_option(p, o)
          end
        end

        def add_general_option(p, o)
          @used_short << short = o[2][:short] || short_from(o[0])
          @result[o[0]] = o[2][:default] || false # set default
          klass = o[2][:default].class == Fixnum ? Integer : o[2][:default].class

          if [TrueClass, FalseClass, NilClass].include?(klass) # boolean switch
            p.on("-" << short, "--[no-]" << o[0].to_s.gsub("_", "-"), o[1]) { |x| @result[o[0]] = x }
          else # argument with parameter
            p.on("-" << short, "--" << o[0].to_s.gsub("_", "-") << " " << o[2][:default].to_s, klass, o[1]) { |x| @result[o[0]] = x }
          end
        end

        def add_output_option(p)
          p.on("--out FILE|DIR",
               "Specify the file or directory to use for output",
               "This option applies to the previously",
               "specified --format, or the default format",
               "if no format is specified. Paths are relative to",
               "#{MetricFu.run_path.join(MetricFu::Io::FileSystem.directory('base_directory'))}",
               "Check the specific formatter\'s docs to see",
               "whether to pass a file or a dir.") do |o|
            @result[:format] ||= MetricFu::Formatter::DEFAULT
            @result[:format].last << o
          end
        end

        def add_format_option(p)
          p.on("--format FORMAT",
               "Specify the formatter to use for output.",
               "This option can be specified multiple times.",
               "Specify a built-in formatter from the list below,",
               "or the fully-qualified class name of your own custom formatter.",
               *format_descriptions) do |f|
            @result[:format] ||= []
            @result[:format] << [f]
          end
        end

        def short_from(name)
          name.to_s.chars.each do |c|
            next if @used_short.include?(c) || c == "_"
            return c # returns from short_from method
          end
        end

        def debug_info
          extend(MetricFu::Environment)
          require "pp"
          pp debug_info
        end

        # Build a nicely formatted list of built-in
        # formatter keys and their descriptions
        # @see MetricFu::Formatter::BUILTIN_FORMATS
        # @example
        #    format_descriptions #=> ["  yaml :  Generates the raw output as yaml"]
        # @return [Array<String>] in the form of
        #    "   <key>  : <description>."
        def format_descriptions
          formats = MetricFu::Formatter::BUILTIN_FORMATS
          max = formats.keys.map(&:length).max
          formats.keys.sort.map do |key|
            "  #{key}#{' ' * (max - key.length)} : #{formats[key][1]}"
          end
        end

        def success!
          MetricFu::Cli.complete!
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<openerp>
    <data>
    	<!--Paper Format-->
    	<record id="paperformat_LetterPortrait" model="report.paperformat">
		    <field name="name">US Letter Portrait</field>
		    <field name="default" eval="True"/>
		    <field name="format">Letter</field>
		    <field name="page_height">0</field>
		    <field name="page_width">0</field>
		    <field name="orientation">Portrait</field>
		    <field name="margin_top">20</field>
		    <field name="margin_bottom">20</field>
		    <field name="margin_left">7</field>
		    <field name="margin_right">7</field>
		    <field name="header_line" eval="False"/>
		    <field name="header_spacing">7</field>
		    <field name="dpi">80</field>
		</record>
    	<record id="paperformat_LetterLandscape" model="report.paperformat">
		    <field name="name">US Letter Landscape</field>
		    <field name="default" eval="True"/>
		    <field name="format">Letter</field>
		    <field name="page_height">0</field>
		    <field name="page_width">0</field>
		    <field name="orientation">Landscape</field>
		    <field name="margin_top">15</field>
		    <field name="margin_bottom">15</field>
		    <field name="margin_left">2</field>
		    <field name="margin_right">2</field>
		    <field name="header_line" eval="False"/>
		    <field name="header_spacing">7</field>
		    <field name="dpi">100</field>
		</record>
		<!--Report PDF-->
        <report
            id="action_report_delivery_order_pdf"
            model="stock.picking"
            string="Delivery Order Report"
            report_type="qweb-pdf"
            name="delivery_order_report.report_delivery_order_pdf"
            file="delivery_order_report.report_delivery_order_pdf"
            menu="False"/>
		<!--Paper Format to delivery order report-->
		<record id="action_report_delivery_order_pdf" model="ir.actions.report.xml">
			<field name="paperformat_id" ref="delivery_order_report.paperformat_LetterLandscape"/>
    	</record>
	</data>
</openerp>


text:
package com.github.amitkma.boilerplate.presentation.data;

public class Resource<T> {

    public final ResourceState status;
    public final T data;
    public final String message;

    public Resource(ResourceState status, T data, String message) {
        this.status = status;
        this.data = data;
        this.message = message;
    }

    Resource<T> error(String message, T data) {
        return new Resource<>(ResourceState.ERROR, null, message);
    }

    Resource<T> success(T data) {
        return new Resource<>(ResourceState.SUCCESS, data, null);
    }

    Resource<T> loading() {
        return new Resource<>(ResourceState.LOADING, null, null);
    }
}


text:
@interface UIWindow (WtMask)
@property (nonatomic, readonly) UIView *wtWindowMask;
@property (nonatomic, assign) CGFloat wtMaskAlpha;                    // 0..<1
@property (nonatomic, assign) CGFloat wtMaxMaskAlpha;                 // Default 0.5
@property (nonatomic, assign) NSTimeInterval wtMaskAnimationDuration; // Default 0.25
- (void)wtPrepareMask;
- (void)wtShowMask;
- (void)wtHideMask;
@end


text:
#ifndef TOOLS_H_
#define TOOLS_H_
#include <vector>
#include "Eigen/Dense"

using Eigen::MatrixXd;
using Eigen::VectorXd;
using namespace std;

class Tools {
public:
  /**
  * Constructor.
  */
  Tools();

  /**
  * Destructor.
  */
  virtual ~Tools();

  /**
  * A helper method to calculate RMSE.
  */
  VectorXd CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth);

  /**
  * A helper method to calculate Jacobians.
  */
  MatrixXd CalculateJacobian(const VectorXd& x_state);

};

#endif /* TOOLS_H_ */


text:
package ar.com.larreta.commons.exceptions;

import java.io.PrintWriter;
import java.io.StringWriter;

public class AppException extends Exception {

	public static String getStackTrace(Throwable e) {
		StringWriter sWriter = new StringWriter();
		PrintWriter pilaMensajes = new PrintWriter(sWriter);
		e.printStackTrace(pilaMensajes);
		String stackTrace = sWriter.toString();
		return stackTrace;
	}

	public String getExceptionStackTrace(){
		return AppException.getStackTrace(this);
	}

}


text:
;------------------------------------------------------------------------------
; @file
; Transition from 16 bit real mode into 32 bit flat protected mode
;
; Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
;------------------------------------------------------------------------------

%define SEC_DEFAULT_CR0  0x40000023
%define SEC_DEFAULT_CR4  0x640

BITS    16

;
; Modified:  EAX, EBX
;
TransitionFromReal16To32BitFlat:

    debugShowPostCode POSTCODE_16BIT_MODE

    cli

    mov     bx, 0xf000
    mov     ds, bx

    mov     bx, ADDR16_OF(gdtr)

o32 lgdt    [cs:bx]

    mov     eax, SEC_DEFAULT_CR0
    mov     cr0, eax

%ifdef __YASM__ ; VBox
    jmp     dword LINEAR_CODE_SEL:ADDR_OF(jumpTo32BitAndLandHere)
%else
    jmp     LINEAR_CODE_SEL:dword ADDR_OF(jumpTo32BitAndLandHere)
%endif
BITS    32
jumpTo32BitAndLandHere:

    mov     eax, SEC_DEFAULT_CR4
    mov     cr4, eax

    debugShowPostCode POSTCODE_32BIT_MODE

    mov     ax, LINEAR_SEL
    mov     ds, ax
    mov     es, ax
    mov     fs, ax
    mov     gs, ax
    mov     ss, ax

    OneTimeCallRet TransitionFromReal16To32BitFlat

ALIGN   2

gdtr:
    dw      GDT_END - GDT_BASE - 1   ; GDT limit
    dd      ADDR_OF(GDT_BASE)

ALIGN   16

;
; Macros for GDT entries
;

%define  PRESENT_FLAG(p) (p << 7)
%define  DPL(dpl) (dpl << 5)
%define  SYSTEM_FLAG(s) (s << 4)
%define  DESC_TYPE(t) (t)

; Type: data, expand-up, writable, accessed
%define  DATA32_TYPE 3

; Type: execute, readable, expand-up, accessed
%define  CODE32_TYPE 0xb

; Type: execute, readable, expand-up, accessed
%define  CODE64_TYPE 0xb

%define  GRANULARITY_FLAG(g) (g << 7)
%define  DEFAULT_SIZE32(d) (d << 6)
%define  CODE64_FLAG(l) (l << 5)
%define  UPPER_LIMIT(l) (l)

;
; The Global Descriptor Table (GDT)
;

GDT_BASE:
; null descriptor
NULL_SEL            equ $-GDT_BASE
    DW      0            ; limit 15:0
    DW      0            ; base 15:0
    DB      0            ; base 23:16
    DB      0            ; sys flag, dpl, type
    DB      0            ; limit 19:16, flags
    DB      0            ; base 31:24

; linear data segment descriptor
LINEAR_SEL          equ $-GDT_BASE
    DW      0xffff       ; limit 15:0
    DW      0            ; base 15:0
    DB      0            ; base 23:16
    DB      PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(DATA32_TYPE)
    DB      GRANULARITY_FLAG(1)|DEFAULT_SIZE32(1)|CODE64_FLAG(0)|UPPER_LIMIT(0xf)
    DB      0            ; base 31:24

; linear code segment descriptor
LINEAR_CODE_SEL     equ $-GDT_BASE
    DW      0xffff       ; limit 15:0
    DW      0            ; base 15:0
    DB      0            ; base 23:16
    DB      PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE32_TYPE)
    DB      GRANULARITY_FLAG(1)|DEFAULT_SIZE32(1)|CODE64_FLAG(0)|UPPER_LIMIT(0xf)
    DB      0            ; base 31:24

%ifdef ARCH_X64
; linear code (64-bit) segment descriptor
LINEAR_CODE64_SEL   equ $-GDT_BASE
    DW      0xffff       ; limit 15:0
    DW      0            ; base 15:0
    DB      0            ; base 23:16
    DB      PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE64_TYPE)
    DB      GRANULARITY_FLAG(1)|DEFAULT_SIZE32(0)|CODE64_FLAG(1)|UPPER_LIMIT(0xf)
    DB      0            ; base 31:24
%endif

GDT_END:


text:
import libtcodpy as libtcod
from model.action import ActionTag
from model.attribute import Attribute, AttributeTag
from model.entity import Entity
from ui.game.frame_world import WorldRenderType
from behavior import Behavior

#note: an explicit from [] import * because if I don't, using entity_utilities functions in lambdas throws a fit
from model.entity_utilities import *

# TODO: pull this code out into a more generic one for programs
class ProgramMemoryRemoveBehavior(Behavior):
	def remove_memory(self, parent_id, position):
		parent = self.manager.get_entity_by_id(parent_id)
		memory_at_position = filter(lambda ent: is_owned_memory(parent_id, ent), self.manager.get_world_data_for_position(position)['entities'])
		if len(memory_at_position) > 0:
			#will remove multiple copies of memory, best to be safe and do so to trim down on excess floating memory
			#may shoot me in the foot later if i actually have memory duplication bugs somewhere along the line
			for entity in memory_at_position:

				parent.get_attribute(AttributeTag.OwnedMemory).data['segments'].remove(entity)
				self.manager.remove_entity_by_id(entity.id)

	def handle_action(self, action):
		if action.type == ActionTag.ProgramMemoryRemove:
			#going to leave it broken out like this for the moment, if time goes by and I don't need aditional validation logic then ill fold it back into this
			self.remove_memory(action.data['parent_id'], action.data['position'])
		return []

class ProgramMemoryAddBehavior(Behavior):
	def handle_action(self, action):
		if action.type == ActionTag.ProgramMemoryAdd:
			position = action.data['position']
			parent_id = action.data['parent_id']

			world_data_for_position = self.manager.get_world_data_for_position(position)
			if not entities_occupy_position(parent_id, world_data_for_position):
				#todo - consider making this an explicit action instead of just chucking it into the manager? for now, this is fine
				memory_segment = Entity([
						Attribute(AttributeTag.ProgramMemory, {'parent_id': parent_id}),
						Attribute(AttributeTag.Visible),
						Attribute(AttributeTag.WorldPosition, {'value': position}),
						Attribute(AttributeTag.DrawInfo, {'draw_type': WorldRenderType.Memory, 'draw_type': WorldRenderType.Memory, 'z_level': 2})
					])
				self.manager.add_entity(memory_segment)

				parent = self.manager.get_entity_by_id(parent_id)
				parent.get_attribute(AttributeTag.OwnedMemory).data['segments'].append(memory_segment)

		return []