text:
require EasyRailsAuthentication::Engine.config.root + 'app' + 'models' + 'user'

class User
  include ResidentOrUser
  has_one :resident, class_name: "SummerResidents::Resident", dependent: :destroy
  [:husband_and_kids, :wife_and_kids, :first_name, :last_name].each { |col|
   delegate col, to: :resident
  }
end


text:
package com.comandante.creeper.world;

import com.comandante.creeper.server.Color;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;

import java.util.Iterator;
import java.util.Map;

public class MapsManager {

    private final RoomManager roomManager;
    private final Map<Integer, MapMatrix> floorMatrixMaps;

    public MapsManager(RoomManager roomManager) {
        this.roomManager = roomManager;
        this.floorMatrixMaps = Maps.newHashMap();
    }

    public void generateAllMaps(int maxRows, int maxColumns) {
        Iterator<Map.Entry<Integer, Room>> rooms = roomManager.getRooms();
        while (rooms.hasNext()) {
            Map.Entry<Integer, Room> next = rooms.next();
            Integer roomId = next.getValue().getRoomId();
            String s = drawMap(roomId, new Coords(maxRows, maxColumns));
            next.getValue().setMapData(Optional.of(s));
        }
    }

    public String drawMap(Integer roomId, Coords max) {
        MapMatrix floorMatrix = floorMatrixMaps.get(roomManager.getRoom(roomId).getFloorId());
        MapMatrix mapMatrix = floorMatrix.extractMatrix(roomId, max);
        return mapMatrix.renderMap(roomId, roomManager);
    }

    public static Function<Integer, String> render(final Integer currentroomId, final RoomManager roomManager) {
        return new Function<Integer, String>() {
            @Override
            public String apply(Integer roomId) {
                if (roomId > 0) {
                    if (roomId.equals(currentroomId)) {
                        return "[" + Color.BOLD_ON + Color.RED + "*" + Color.RESET + "]";
                    } else if (roomId.equals(1)) {
                        return "[" + Color.BOLD_ON + Color.BLUE + "L" + Color.RESET + "]";
                    } else if (roomManager.getRoom(roomId).getUpId().isPresent()) {
                        return "[" + Color.GREEN + "^" + Color.RESET + "]";
                    } else if (roomManager.getRoom(roomId).getDownId().isPresent()) {
                        return "[" + Color.GREEN + "v" + Color.RESET + "]";
                    }
                    else {
                        return "[ ]";
                    }
                } else {
                    return " - ";
                }
            }
        };
    }

    public void addFloorMatrix(Integer id, MapMatrix floorMatrix) {
        floorMatrixMaps.put(id, floorMatrix);
    }

    public Map<Integer, MapMatrix> getFloorMatrixMaps() {
        return floorMatrixMaps;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#ifndef TTIO_PLI_INCLUDED
#define TTIO_PLI_INCLUDED

#include <memory>

#include "tlevel_io.h"

class GroupTag;
class ParsedPli;
class ImageTag;
class TImageWriterPli;
class TImageReaderPli;

//===========================================================================
/*
class TWriterInfoPli final : public TWriterInfo {

public:
 ~TWriterInfoPli() {}
  static TWriterInfo *create(const std::string &ext) { return new
TWriterInfoPli(); }
  TWriterInfo *clone() const {
  return new TWriterInfoPli(*this); }

private:
  TWriterInfoPli() {}
  TWriterInfoPli(const TWriterInfoPli&) {}
};
*/
//===========================================================================

/*!
  TLevelWriterPli:
 */
class TLevelWriterPli final : public TLevelWriter {
  //! object to manage a pli
  std::unique_ptr<ParsedPli> m_pli;

  //! number of frame in pli
  UINT m_frameNumber;

  //  vettore da utilizzare per il calcolo della palette
  std::vector<TPixel> m_colorArray;

public:
  TLevelWriterPli(const TFilePath &path, TPropertyGroup *winfo);
  ~TLevelWriterPli();
  TImageWriterP getFrameWriter(TFrameId fid) override;

  friend class TImageWriterPli;

public:
  static TLevelWriter *create(const TFilePath &f, TPropertyGroup *winfo) {
    return new TLevelWriterPli(f, winfo);
  }

private:
  // not implemented
  TLevelWriterPli(const TLevelWriterPli &);
  TLevelWriterPli &operator=(const TLevelWriterPli &);
};

//===========================================================================

typedef std::pair<ImageTag *, bool> pliFrameInfo;

/*!
  TLevelReaderPli:
 */
class TLevelReaderPli final : public TLevelReader {
public:
  TLevelReaderPli(const TFilePath &path);
  ~TLevelReaderPli();

  /*!
Return info about current pli
*/
  TLevelP loadInfo() override;
  void doReadPalette(bool doReadIt) override;

  /*!
Return an image with Reader information
*/
  TImageReaderP getFrameReader(TFrameId fid) override;

  QString getCreator() override;
  friend class TImageReaderPli;

private:
  bool m_init;
  //! struct which contanins reference to frame
  std::map<TFrameId, pliFrameInfo> m_mapOfImage;

  //! Reference to pli palette
  TPixel *m_palette;
  bool m_readPalette;
  //!
  TUINT32 m_paletteCount;

  //! flag to check if file exists
  bool m_doesExist;

  //! object to manage a pli
  ParsedPli *m_pli;
  TLevelP m_level;

public:
  static TLevelReader *create(const TFilePath &f) {
    return new TLevelReaderPli(f);
  }

private:
  // not implemented
  TLevelReaderPli(const TLevelReaderPli &);
  TLevelReaderPli &operator=(const TLevelReaderPli &);
};

//===========================================================================
/*
Classe locale per la lettura di un frame del livello.
*/
class TImageReaderPli final : public TImageReader {
public:
  TFrameId m_frameId;  //<! Current frame id

private:
  // not implemented
  TImageReaderPli(const TImageReaderPli &);
  TImageReaderPli &operator=(const TImageReaderPli &src);

public:
  TImageReaderPli(const TFilePath &f, const TFrameId &frameId,
                  TLevelReaderPli *);
  ~TImageReaderPli() {}

  TImageP load() override;
  TImageP doLoad();

  TDimension getSize() const;

  TRect getBBox() const;

private:
  //! Size of image
  int m_lx, m_ly;

  //! Reference to level reader
  TLevelReaderPli *m_lrp;
};

// Functions

TPalette *readPalette(GroupTag *paletteTag, int majorVersion, int minorVersion);

#endif  // TTIO_PLI_INCLUDED


text:
angular.module('workbenchUser', ['ngRoute', 'ngStorage'])
	.value('version', '0.2.0')
	.config(['$routeProvider', function($routeProvider) {
		$routeProvider
			.when('/user/:tab', {
				templateUrl: 'partials/profile.html',
				controller: 'wbProfileCtrl' });
	}])
	.controller('wbProfileCtrl', function($scope, $routeParams, tmOrganization,
			tmOrganizationUsers) {
		$scope.organizations = tmOrganization.list();
		$scope.activetab = $routeParams.tab;

		$scope.updateUser = function(passa, passb) {
			if (passa && passa === passb) {
				$scope.user.password = passa;
			} else if ((passa || passb)) {
				// if either field is non null, it might be previously
				// synced to user object resulting in a updated
				// password when the user may not have intended so.
				return;
			}

			return $scope.user.$update();
		};
	});


text:
*Clone a memory block.*

## C Signature
```
Nucleus_Status
Nucleus_cloneMemory
    (
        void **p,
        const void *q,
        Nucleus_Size n
     );
```

## Parameters
- `p` a pointer to a `void *` variable
- `q` a pointer to the memory block to be cloned
- `n` the size, in Bytes, of the memory block pointed to by `q`. Note that `0` is a valid size.

## Description
This function clones a memory block.

A memory block with the same size and the same contents as the specified memory block `(q,n)` is
allocated, its address is assigned to `*p` and `Nucleus_Status_Success` is returned. This function
fails if and only if
- `p` or `q` are null pointers, or
- the allocation of the memory block failed.

Under the former condition `Nucleus_Status_InvalidArgument` is returned,
under the latter condition `Nucleus_Status_AllocationFailed` is returned.

## Requirements

|                      | Windows                  | Linux                     |
|----------------------|--------------------------|---------------------------|
| *Header*             | `Nucleus/Memory.h`       | `Nucleus/Memory.h`        |
| *Static library*     | `Nucleus.Library.lib`    | `libNucleus.Library.a`    |


text:
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(non_camel_case_types)]

//! Code that is useful in various trans modules.

use driver::session::Session;
use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
use lib::llvm::{True, False, Bool};
use lib::llvm::llvm;
use lib;
use middle::lang_items::LangItem;
use middle::trans::build;
use middle::trans::cleanup;
use middle::trans::datum;
use middle::trans::datum::{Datum, Lvalue};
use middle::trans::debuginfo;
use middle::trans::type_::Type;
use middle::ty;
use middle::subst::Subst;
use middle::typeck;
use util::ppaux::Repr;
use util::nodemap::NodeMap;

use arena::TypedArena;
use collections::HashMap;
use libc::{c_uint, c_longlong, c_ulonglong, c_char};
use std::c_str::ToCStr;
use std::cell::{Cell, RefCell};
use std::vec::Vec;
use syntax::ast::Ident;
use syntax::ast;
use syntax::ast_map::{PathElem, PathName};
use syntax::codemap::Span;
use syntax::parse::token::InternedString;
use syntax::parse::token;

pub use middle::trans::context::CrateContext;

fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
    match ty::get(ty).sty {
        ty::ty_struct(def_id, ref substs) => {
            let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
            fields.len() == 1 &&
                fields.get(0).ident.name ==
                    token::special_idents::unnamed_field.name &&
                type_is_immediate(ccx, fields.get(0).mt.ty)
        }
        _ => false
    }
}

pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
    use middle::trans::machine::llsize_of_alloc;
    use middle::trans::type_of::sizing_type_of;
    let tcx = ccx.tcx();
    let simple = ty::type_is_scalar(ty) || ty::type_is_boxed(ty) ||
        ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
        type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
        ty::type_is_simd(tcx, ty);
    if simple {
        return true;
    }
    match ty::get(ty).sty {
        ty::ty_bot => true,
        ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) => {
            let llty = sizing_type_of(ccx, ty);
            llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type)
        }
        _ => type_is_zero_size(ccx, ty)
    }
}

pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
    /*!
     * Identify types which have size zero at runtime.
     */

    use middle::trans::machine::llsize_of_alloc;
    use middle::trans::type_of::sizing_type_of;
    let llty = sizing_type_of(ccx, ty);
    llsize_of_alloc(ccx, llty) == 0
}

pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
    /*!
     * Identifies types which we declare to be equivalent to `void`
     * in C for the purpose of function return types. These are
     * `()`, bot, and uninhabited enums. Note that all such types
     * are also zero-size, but not all zero-size types use a `void`
     * return type (in order to aid with C ABI compatibility).
     */

    ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx(), ty)
}

/// Generates a unique symbol based off the name given. This is used to create
/// unique symbols for things like closures.
pub fn gensym_name(name: &str) -> PathElem {
    let num = token::gensym(name);
    // use one colon which will get translated to a period by the mangler, and
    // we're guaranteed that `num` is globally unique for this crate.
    PathName(token::gensym(format!("{}:{}", name, num)))
}

pub struct tydesc_info {
    pub ty: ty::t,
    pub tydesc: ValueRef,
    pub size: ValueRef,
    pub align: ValueRef,
    pub name: ValueRef,
    pub visit_glue: Cell<Option<ValueRef>>,
}

/*
 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
 *
 * An "extern" is an LLVM symbol we wind up emitting an undefined external
 * reference to. This means "we don't have the thing in this compilation unit,
 * please make sure you link it in at runtime". This could be a reference to
 * C code found in a C library, or rust code found in a rust crate.
 *
 * Most "externs" are implicitly declared (automatically) as a result of a
 * user declaring an extern _module_ dependency; this causes the rust driver
 * to locate an extern crate, scan its compilation metadata, and emit extern
 * declarations for any symbols used by the declaring crate.
 *
 * A "foreign" is an extern that references C (or other non-rust ABI) code.
 * There is no metadata to scan for extern references so in these cases either
 * a header-digester like bindgen, or manual function prototypes, have to
 * serve as declarators. So these are usually given explicitly as prototype
 * declarations, in rust code, with ABI attributes on them noting which ABI to
 * link via.
 *
 * An "upcall" is a foreign call generated by the compiler (not corresponding
 * to any user-written call in the code) into the runtime library, to perform
 * some helper task such as bringing a task to life, allocating memory, etc.
 *
 */

pub struct NodeInfo {
    pub id: ast::NodeId,
    pub span: Span,
}

pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
    NodeInfo { id: expr.id, span: expr.span }
}

pub struct BuilderRef_res {
    pub b: BuilderRef,
}

impl Drop for BuilderRef_res {
    fn drop(&mut self) {
        unsafe {
            llvm::LLVMDisposeBuilder(self.b);
        }
    }
}

pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
    BuilderRef_res {
        b: b
    }
}

pub type ExternMap = HashMap<~str, ValueRef>;

// Here `self_ty` is the real type of the self parameter to this method. It
// will only be set in the case of default methods.
pub struct param_substs {
    pub substs: ty::substs,
    pub vtables: Option<typeck::vtable_res>,
    pub self_vtables: Option<typeck::vtable_param_res>
}

impl param_substs {
    pub fn validate(&self) {
        for t in self.substs.tps.iter() {
            assert!(!ty::type_needs_infer(*t));
        }
        for t in self.substs.self_ty.iter() {
            assert!(!ty::type_needs_infer(*t));
        }
    }
}

fn param_substs_to_str(this: &param_substs, tcx: &ty::ctxt) -> ~str {
    format!("param_substs({})", this.substs.repr(tcx))
}

impl Repr for param_substs {
    fn repr(&self, tcx: &ty::ctxt) -> ~str {
        param_substs_to_str(self, tcx)
    }
}

pub trait SubstP {
    fn substp(&self, tcx: &ty::ctxt, param_substs: Option<&param_substs>)
              -> Self;
}

impl<T:Subst+Clone> SubstP for T {
    fn substp(&self, tcx: &ty::ctxt, param_substs: Option<&param_substs>)
              -> T {
        match param_substs {
            Some(substs) => {
                self.subst(tcx, &substs.substs)
            }
            None => {
                (*self).clone()
            }
        }
    }
}

// work around bizarre resolve errors
pub type RvalueDatum = datum::Datum<datum::Rvalue>;
pub type LvalueDatum = datum::Datum<datum::Lvalue>;

// Function context.  Every LLVM function we create will have one of
// these.
pub struct FunctionContext<'a> {
    // The ValueRef returned from a call to llvm::LLVMAddFunction; the
    // address of the first instruction in the sequence of
    // instructions for this function that will go in the .text
    // section of the executable we're generating.
    pub llfn: ValueRef,

    // The environment argument in a closure.
    pub llenv: Option<ValueRef>,

    // The place to store the return value. If the return type is immediate,
    // this is an alloca in the function. Otherwise, it's the hidden first
    // parameter to the function. After function construction, this should
    // always be Some.
    pub llretptr: Cell<Option<ValueRef>>,

    pub entry_bcx: RefCell<Option<&'a Block<'a>>>,

    // These pub elements: "hoisted basic blocks" containing
    // administrative activities that have to happen in only one place in
    // the function, due to LLVM's quirks.
    // A marker for the place where we want to insert the function's static
    // allocas, so that LLVM will coalesce them into a single alloca call.
    pub alloca_insert_pt: Cell<Option<ValueRef>>,
    pub llreturn: Cell<Option<BasicBlockRef>>,

    // The a value alloca'd for calls to upcalls.rust_personality. Used when
    // outputting the resume instruction.
    pub personality: Cell<Option<ValueRef>>,

    // True if the caller expects this fn to use the out pointer to
    // return. Either way, your code should write into llretptr, but if
    // this value is false, llretptr will be a local alloca.
    pub caller_expects_out_pointer: bool,

    // Maps arguments to allocas created for them in llallocas.
    pub llargs: RefCell<NodeMap<LvalueDatum>>,

    // Maps the def_ids for local variables to the allocas created for
    // them in llallocas.
    pub lllocals: RefCell<NodeMap<LvalueDatum>>,

    // Same as above, but for closure upvars
    pub llupvars: RefCell<NodeMap<ValueRef>>,

    // The NodeId of the function, or -1 if it doesn't correspond to
    // a user-defined function.
    pub id: ast::NodeId,

    // If this function is being monomorphized, this contains the type
    // substitutions used.
    pub param_substs: Option<&'a param_substs>,

    // The source span and nesting context where this function comes from, for
    // error reporting and symbol generation.
    pub span: Option<Span>,

    // The arena that blocks are allocated from.
    pub block_arena: &'a TypedArena<Block<'a>>,

    // This function's enclosing crate context.
    pub ccx: &'a CrateContext,

    // Used and maintained by the debuginfo module.
    pub debug_context: debuginfo::FunctionDebugContext,

    // Cleanup scopes.
    pub scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
}

impl<'a> FunctionContext<'a> {
    pub fn arg_pos(&self, arg: uint) -> uint {
        let arg = self.env_arg_pos() + arg;
        if self.llenv.is_some() {
            arg + 1
        } else {
            arg
        }
    }

    pub fn out_arg_pos(&self) -> uint {
        assert!(self.caller_expects_out_pointer);
        0u
    }

    pub fn env_arg_pos(&self) -> uint {
        if self.caller_expects_out_pointer {
            1u
        } else {
            0u
        }
    }

    pub fn cleanup(&self) {
        unsafe {
            llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
                                                     .get()
                                                     .unwrap());
        }
        // Remove the cycle between fcx and bcx, so memory can be freed
        *self.entry_bcx.borrow_mut() = None;
    }

    pub fn get_llreturn(&self) -> BasicBlockRef {
        if self.llreturn.get().is_none() {

            self.llreturn.set(Some(unsafe {
                "return".with_c_str(|buf| {
                    llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx, self.llfn, buf)
                })
            }))
        }

        self.llreturn.get().unwrap()
    }

    pub fn new_block(&'a self,
                     is_lpad: bool,
                     name: &str,
                     opt_node_id: Option<ast::NodeId>)
                     -> &'a Block<'a> {
        unsafe {
            let llbb = name.with_c_str(|buf| {
                    llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
                                                        self.llfn,
                                                        buf)
                });
            Block::new(llbb, is_lpad, opt_node_id, self)
        }
    }

    pub fn new_id_block(&'a self,
                        name: &str,
                        node_id: ast::NodeId)
                        -> &'a Block<'a> {
        self.new_block(false, name, Some(node_id))
    }

    pub fn new_temp_block(&'a self,
                          name: &str)
                          -> &'a Block<'a> {
        self.new_block(false, name, None)
    }

    pub fn join_blocks(&'a self,
                       id: ast::NodeId,
                       in_cxs: &[&'a Block<'a>])
                       -> &'a Block<'a> {
        let out = self.new_id_block("join", id);
        let mut reachable = false;
        for bcx in in_cxs.iter() {
            if !bcx.unreachable.get() {
                build::Br(*bcx, out.llbb);
                reachable = true;
            }
        }
        if !reachable {
            build::Unreachable(out);
        }
        return out;
    }
}

// Basic block context.  We create a block context for each basic block
// (single-entry, single-exit sequence of instructions) we generate from Rust
// code.  Each basic block we generate is attached to a function, typically
// with many basic blocks per function.  All the basic blocks attached to a
// function are organized as a directed graph.
pub struct Block<'a> {
    // The BasicBlockRef returned from a call to
    // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
    // block to the function pointed to by llfn.  We insert
    // instructions into that block by way of this block context.
    // The block pointing to this one in the function's digraph.
    pub llbb: BasicBlockRef,
    pub terminated: Cell<bool>,
    pub unreachable: Cell<bool>,

    // Is this block part of a landing pad?
    pub is_lpad: bool,

    // AST node-id associated with this block, if any. Used for
    // debugging purposes only.
    pub opt_node_id: Option<ast::NodeId>,

    // The function context for the function to which this block is
    // attached.
    pub fcx: &'a FunctionContext<'a>,
}

impl<'a> Block<'a> {
    pub fn new<'a>(
               llbb: BasicBlockRef,
               is_lpad: bool,
               opt_node_id: Option<ast::NodeId>,
               fcx: &'a FunctionContext<'a>)
               -> &'a Block<'a> {
        fcx.block_arena.alloc(Block {
            llbb: llbb,
            terminated: Cell::new(false),
            unreachable: Cell::new(false),
            is_lpad: is_lpad,
            opt_node_id: opt_node_id,
            fcx: fcx
        })
    }

    pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
    pub fn tcx(&self) -> &'a ty::ctxt {
        &self.fcx.ccx.tcx
    }
    pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }

    pub fn ident(&self, ident: Ident) -> ~str {
        token::get_ident(ident).get().to_str()
    }

    pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
        self.tcx().map.node_to_str(id).to_owned()
    }

    pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
        e.repr(self.tcx())
    }

    pub fn def(&self, nid: ast::NodeId) -> ast::Def {
        match self.tcx().def_map.borrow().find(&nid) {
            Some(&v) => v,
            None => {
                self.tcx().sess.bug(format!(
                    "no def associated with node id {:?}", nid));
            }
        }
    }

    pub fn val_to_str(&self, val: ValueRef) -> ~str {
        self.ccx().tn.val_to_str(val)
    }

    pub fn llty_str(&self, ty: Type) -> ~str {
        self.ccx().tn.type_to_str(ty)
    }

    pub fn ty_to_str(&self, t: ty::t) -> ~str {
        t.repr(self.tcx())
    }

    pub fn to_str(&self) -> ~str {
        let blk: *Block = self;
        format!("[block {}]", blk)
    }
}

pub struct Result<'a> {
    pub bcx: &'a Block<'a>,
    pub val: ValueRef
}

impl<'a> Result<'a> {
    pub fn new(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
        Result {
            bcx: bcx,
            val: val,
        }
    }
}

pub fn val_ty(v: ValueRef) -> Type {
    unsafe {
        Type::from_ref(llvm::LLVMTypeOf(v))
    }
}

// LLVM constant constructors.
pub fn C_null(t: Type) -> ValueRef {
    unsafe {
        llvm::LLVMConstNull(t.to_ref())
    }
}

pub fn C_undef(t: Type) -> ValueRef {
    unsafe {
        llvm::LLVMGetUndef(t.to_ref())
    }
}

pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
    unsafe {
        llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
    }
}

pub fn C_floating(s: &str, t: Type) -> ValueRef {
    unsafe {
        s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
    }
}

pub fn C_nil(ccx: &CrateContext) -> ValueRef {
    C_struct(ccx, [], false)
}

pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
    C_integral(Type::bool(ccx), val as u64, false)
}

pub fn C_i1(ccx: &CrateContext, val: bool) -> ValueRef {
    C_integral(Type::i1(ccx), val as u64, false)
}

pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
    C_integral(Type::i32(ccx), i as u64, true)
}

pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
    C_integral(Type::i64(ccx), i as u64, true)
}

pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
    C_integral(Type::i64(ccx), i, false)
}

pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
    C_integral(ccx.int_type, i as u64, true)
}

pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
    C_integral(ccx.int_type, i as u64, false)
}

pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
    C_integral(Type::i8(ccx), i as u64, false)
}

// This is a 'c-like' raw string, which differs from
// our boxed-and-length-annotated strings.
pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
    unsafe {
        match cx.const_cstr_cache.borrow().find(&s) {
            Some(&llval) => return llval,
            None => ()
        }

        let sc = llvm::LLVMConstStringInContext(cx.llcx,
                                                s.get().as_ptr() as *c_char,
                                                s.get().len() as c_uint,
                                                !null_terminated as Bool);

        let gsym = token::gensym("str");
        let g = format!("str{}", gsym).with_c_str(|buf| {
            llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
        });
        llvm::LLVMSetInitializer(g, sc);
        llvm::LLVMSetGlobalConstant(g, True);
        lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);

        cx.const_cstr_cache.borrow_mut().insert(s, g);
        g
    }
}

// NB: Do not use `do_spill_noroot` to make this into a constant string, or
// you will be kicked off fast isel. See issue #4352 for an example of this.
pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
    unsafe {
        let len = s.get().len();
        let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false), Type::i8p(cx).to_ref());
        C_struct(cx, [cs, C_uint(cx, len)], false)
    }
}

pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
    unsafe {
        let len = data.len();
        let lldata = C_bytes(cx, data);

        let gsym = token::gensym("binary");
        let g = format!("binary{}", gsym).with_c_str(|buf| {
            llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
        });
        llvm::LLVMSetInitializer(g, lldata);
        llvm::LLVMSetGlobalConstant(g, True);
        lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);

        let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
        C_struct(cx, [cs, C_uint(cx, len)], false)
    }
}

pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
    unsafe {
        llvm::LLVMConstStructInContext(ccx.llcx,
                                       elts.as_ptr(), elts.len() as c_uint,
                                       packed as Bool)
    }
}

pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
    unsafe {
        llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
    }
}

pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
    unsafe {
        return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
    }
}

pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
    unsafe {
        let ptr = bytes.as_ptr() as *c_char;
        return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
    }
}

pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
    unsafe {
        llvm::LLVMGetParam(fndecl, param as c_uint)
    }
}

pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
                  -> ValueRef {
    unsafe {
        let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);

        debug!("const_get_elt(v={}, us={:?}, r={})",
               cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));

        return r;
    }
}

pub fn is_const(v: ValueRef) -> bool {
    unsafe {
        llvm::LLVMIsConstant(v) == True
    }
}

pub fn const_to_int(v: ValueRef) -> c_longlong {
    unsafe {
        llvm::LLVMConstIntGetSExtValue(v)
    }
}

pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
    unsafe {
        llvm::LLVMConstIntGetZExtValue(v)
    }
}

pub fn is_undef(val: ValueRef) -> bool {
    unsafe {
        llvm::LLVMIsUndef(val) != False
    }
}

pub fn is_null(val: ValueRef) -> bool {
    unsafe {
        llvm::LLVMIsNull(val) != False
    }
}

pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
    match bcx.fcx.param_substs {
        Some(ref substs) => {
            ty::subst(bcx.tcx(), &substs.substs, t)
        }
        _ => {
            assert!(!ty::type_has_params(t));
            assert!(!ty::type_has_self(t));
            t
        }
    }
}

pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
    let tcx = bcx.tcx();
    let t = ty::node_id_to_type(tcx, id);
    monomorphize_type(bcx, t)
}

pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
    node_id_type(bcx, ex.id)
}

pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
    monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
}

// Key used to lookup values supplied for type parameters in an expr.
#[deriving(Eq)]
pub enum ExprOrMethodCall {
    // Type parameters for a path like `None::<int>`
    ExprId(ast::NodeId),

    // Type parameters for a method call like `a.foo::<int>()`
    MethodCall(typeck::MethodCall)
}

pub fn node_id_substs(bcx: &Block,
                      node: ExprOrMethodCall)
                      -> ty::substs {
    let tcx = bcx.tcx();

    let substs = match node {
        ExprId(id) => {
            ty::node_id_item_substs(tcx, id).substs
        }
        MethodCall(method_call) => {
            tcx.method_map.borrow().get(&method_call).substs.clone()
        }
    };

    if !substs.tps.iter().all(|t| !ty::type_needs_infer(*t)) {
        bcx.sess().bug(
            format!("type parameters for node {:?} include inference types: {}",
                    node,
                    substs.repr(bcx.tcx())));
    }

    substs.substp(tcx, bcx.fcx.param_substs)
}

pub fn node_vtables(bcx: &Block, id: typeck::MethodCall)
                 -> Option<typeck::vtable_res> {
    bcx.tcx().vtable_map.borrow().find(&id).map(|vts| {
        resolve_vtables_in_fn_ctxt(bcx.fcx, vts.as_slice())
    })
}

// Apply the typaram substitutions in the FunctionContext to some
// vtables. This should eliminate any vtable_params.
pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext,
                                  vts: &[typeck::vtable_param_res])
                                  -> typeck::vtable_res {
    resolve_vtables_under_param_substs(fcx.ccx.tcx(),
                                       fcx.param_substs,
                                       vts)
}

pub fn resolve_vtables_under_param_substs(tcx: &ty::ctxt,
                                          param_substs: Option<&param_substs>,
                                          vts: &[typeck::vtable_param_res])
                                          -> typeck::vtable_res {
    vts.iter().map(|ds| {
      resolve_param_vtables_under_param_substs(tcx,
                                               param_substs,
                                               ds.as_slice())
    }).collect()
}

pub fn resolve_param_vtables_under_param_substs(
    tcx: &ty::ctxt,
    param_substs: Option<&param_substs>,
    ds: &[typeck::vtable_origin])
    -> typeck::vtable_param_res {
    ds.iter().map(|d| {
        resolve_vtable_under_param_substs(tcx,
                                          param_substs,
                                          d)
    }).collect()
}

pub fn resolve_vtable_under_param_substs(tcx: &ty::ctxt,
                                         param_substs: Option<&param_substs>,
                                         vt: &typeck::vtable_origin)
                                         -> typeck::vtable_origin {
    match *vt {
        typeck::vtable_static(trait_id, ref vtable_substs, ref sub) => {
            let vtable_substs = vtable_substs.substp(tcx, param_substs);
            typeck::vtable_static(
                trait_id, vtable_substs,
                resolve_vtables_under_param_substs(tcx, param_substs, sub.as_slice()))
        }
        typeck::vtable_param(n_param, n_bound) => {
            match param_substs {
                Some(substs) => {
                    find_vtable(tcx, substs, n_param, n_bound)
                }
                _ => {
                    tcx.sess.bug(format!(
                        "resolve_vtable_under_param_substs: asked to lookup \
                         but no vtables in the fn_ctxt!"))
                }
            }
        }
    }
}

pub fn find_vtable(tcx: &ty::ctxt,
                   ps: &param_substs,
                   n_param: typeck::param_index,
                   n_bound: uint)
                   -> typeck::vtable_origin {
    debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
           n_param, n_bound, ps.repr(tcx));

    let param_bounds = match n_param {
        typeck::param_self => ps.self_vtables.as_ref().expect("self vtables missing"),
        typeck::param_numbered(n) => {
            let tables = ps.vtables.as_ref()
                .expect("vtables missing where they are needed");
            tables.get(n)
        }
    };
    param_bounds.get(n_bound).clone()
}

pub fn filename_and_line_num_from_span(bcx: &Block, span: Span)
                                       -> (ValueRef, ValueRef) {
    let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
    let filename_cstr = C_cstr(bcx.ccx(),
                               token::intern_and_get_ident(loc.file
                                                              .name
                                                              .as_slice()),
                               true);
    let filename = build::PointerCast(bcx, filename_cstr, Type::i8p(bcx.ccx()));
    let line = C_int(bcx.ccx(), loc.line as int);
    (filename, line)
}

// Casts a Rust bool value to an i1.
pub fn bool_to_i1(bcx: &Block, llval: ValueRef) -> ValueRef {
    build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(bcx.ccx(), false))
}

pub fn langcall(bcx: &Block,
                span: Option<Span>,
                msg: &str,
                li: LangItem)
                -> ast::DefId {
    match bcx.tcx().lang_items.require(li) {
        Ok(id) => id,
        Err(s) => {
            let msg = format!("{} {}", msg, s);
            match span {
                Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
                None => { bcx.tcx().sess.fatal(msg); }
            }
        }
    }
}


text:
import Vue from 'vue'

export default {
  authenticate (data) {
    return Vue.http.post('oauth/token', data)
      .then((response) => Promise.resolve(response))
      .catch((error) => Promise.reject(error))
  },

  user () {
    return Vue.http.get('api/user')
      .then((response) => Promise.resolve(response))
      .catch((error) => Promise.reject(error))
  }
}


text:
package se.sitic.megatron.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import se.sitic.megatron.core.AppProperties;
import se.sitic.megatron.core.MegatronException;
import se.sitic.megatron.core.TypedProperties;
import se.sitic.megatron.entity.Organization;
import se.sitic.megatron.util.Constants;
import se.sitic.megatron.util.IpAddressUtil;

public class ImportSystemData {

	private static final Logger log = Logger.getLogger(ImportSystemData.class);
	private TypedProperties props;
    private Matcher commentMatcher;
    private Matcher classDefMatcher;
    private Matcher dataMatcher;
    private String currentClassName = null;
    private Object parentObject = null;
    private Map<String, String[]> relatedObjectsToAdd = null;
    private Map<String, Integer> objectKeyIndexes = null;
    private Map<String, String[]> objectParameterNames = null;
    private static final String ENITY_PACKAGE_PREFIX = "se.sitic.megatron.entity.";

    private static final String OBJECT_KEY_MARKER = "*";
    private static final String INTEGER_CLASS_NAME = "java.lang.Integer";
    private static final String STRING_CLASS_NAME = "java.lang.String";
    private static final String LONG_CLASS_NAME = "java.lang.Long";
    private static final String PRIORITY_CLASS_NAME = "Priority";
    private static final String ENTRYTYPE_CLASS_NAME = "EntryType";
    private static final String IPRANGE_CLASS_NAME = "IpRange";
    private static final String ORGANIZATION_CLASS_NAME = "Organization";
    private static final String SET_EMAILS_METHOD_NAME = "setEmailAddresses";
    private static final String GET_ORGANIZATION_ID = "getOrganizationId";
    private static final String SET_ORGANIZATION_ID = "setOrganizationId";

    private static final String COMMENT_REG_EXP = "^#";
    private static final String CLASSDEF_REG_EXP = "^!(.+);(.*)$";
    private static final String DATA_REG_EXP = "(^.+(;.)*)$";
    private static final String SET_CLASS_NAME_REG_EXP = "^java\\.util\\.Set<se\\.sitic\\.megatron\\.entity\\.(.+)>";

    private DbManager dbm = null;
    private int processedLinesC = 0;
    private int readLinesC = 0;

	public ImportSystemData(TypedProperties props) throws MegatronException {
        this.props = props;
        this.commentMatcher = Pattern.compile(COMMENT_REG_EXP).matcher("");

        this.classDefMatcher = Pattern.compile(CLASSDEF_REG_EXP).matcher("");

        this.dataMatcher = Pattern.compile(DATA_REG_EXP).matcher("");

        objectParameterNames = new HashMap<String,String[]>();
        objectKeyIndexes = new HashMap<String, Integer>();

        try {
			dbm = DbManager.createDbManager(props);
		} catch (DbException e) {
		    throw handleException("ImportSystemData", e);
		}

    }

	public void importFile() throws MegatronException {

	   importFile(null);

	}

	public void importFile(String fileName) throws MegatronException {

	    if (fileName == null || fileName.equals("")) {
	        //fileName = props.getString(AppProperties.CONTACTS_IMPORT_FILE_KEY, "/home/gope/workspace/megatron-java/conf/dev/systemdata.txt");
	        fileName = props.getString(AppProperties.CONTACTS_IMPORT_FILE_KEY, "/home/gope/workspace/megatron-java/db-import/systemdata.txt");
	    }

        File file = new File(fileName);
        log.info("Reading system data from file: " + file.getAbsolutePath());
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Constants.UTF8));
            String line = null;
            while ((line = in.readLine()) != null) {
                ++readLinesC;
                if (processLine(line)) {
                    ++processedLinesC;
                }
            }
            log.info("Import finished, number of processed lines: " + processedLinesC);
        } catch (IOException e) {
            throw handleException("importFile", e);
        } finally {
            try { if (in != null) in.close(); } catch (Exception ignored) {}
        }
    }

	private boolean processLine(String line) throws MegatronException {
        boolean result = false;

        log.debug("Processing line: " + line);

        if (isComment(line)){
        	log.debug("Line is comment");
        }
        else if (line.trim().equals("") == false) {
            result = true;
        	if (processClassDef(line) == false) {
        		processDataLine(line);
        	}
        }
        return result;
	}

	private boolean isComment(String line) {

		this.commentMatcher.reset(line);

		return this.commentMatcher.find();

	}

	private boolean processClassDef(String line) {

		boolean result = false;

		this.classDefMatcher.reset(line);

		if (this.classDefMatcher.matches()) {

			String className = this.classDefMatcher.group(1);
			log.debug("Class= " + className + ", attributeNames = " + this.classDefMatcher.group(2));
			String[] attributeNames = this.classDefMatcher.group(2).split(",");

			for (int i=0; i<attributeNames.length; i++) {
				if (attributeNames[i].startsWith(OBJECT_KEY_MARKER)) {
					log.debug("Object key index for " + attributeNames[i] + " is " + i);
					objectKeyIndexes.put(className, i);
					attributeNames[i] = attributeNames[i].substring(1);
				}
			}

			this.objectParameterNames.put(className, attributeNames);

			this.currentClassName = className;
			result = true;
		}
		return result;

	}

	private boolean processDataLine(String line)
		throws MegatronException {

		log.debug("Processing data line" + line);
		boolean result = false;

		this.dataMatcher.reset(line);

		if (this.dataMatcher.matches()) {

			String[] attributeValues = this.dataMatcher.group(1).split(";", this.objectParameterNames.get(this.currentClassName).length);

			this.relatedObjectsToAdd = new HashMap<String, String[]>();
			this.parentObject = createOrLoadObject(this.currentClassName, attributeValues);
			if (this.parentObject != null) {
			    setObjectAttributes(this.parentObject, attributeValues, true);
			}
			else {
			    log.error("Could not load or create parent object " + this.currentClassName);
			}
			result = true;
		}
		else {
			log.error("Data line did not match data format");
			throw new MegatronException("Data format error in line: " + line);
		}

		return result;
	}

	private Type getMethodParamType(String className, String methodName)
		throws MegatronException {

		Type type = null;

			try {
				for (Method method : Class.forName(ENITY_PACKAGE_PREFIX + className).getMethods()) {

					if (method.getName().equals(methodName)) {
					    Type[] types = method.getGenericParameterTypes();
					    if (types != null && types.length > 0) {
						  type = types[0];
					    }
					}
				}
			} catch (Exception e) {
				throw handleException("getMethodParamType", e);
			}

		return type;
	}

	private Object createOrLoadObject(String className, String[] attributeValues)
		throws MegatronException {

		Object obj = null;

		try {
			log.debug("Trying to load " + className);
			Integer objectKeyIndex = this.objectKeyIndexes.get(className);
			if (objectKeyIndex != null){
				// load object

				String keyValue = attributeValues[objectKeyIndex];
				// Check if value is empty
				if (keyValue == null || keyValue.equals("")) {
				    // Empty value field bail out...
				    return null;
				}

				String keyName = this.objectParameterNames.get(className)[objectKeyIndex];
				Type paramType = getMethodParamType(className, "set" + keyName);

				Object keyObject = setMethodParameter(keyValue, paramType);

				obj = dbm.genericLoadObject(className, keyName, keyObject);

			}
			if (obj == null){
				obj = Class.forName(ENITY_PACKAGE_PREFIX + className).newInstance();
				initNewObject(obj);
			}
		} catch (Exception e) {
			throw handleException("createOrLoadObject", e);
		}

		return obj;
	}

	private void initNewObject(Object obj) {
	    if (obj instanceof Organization) {
	        Organization organization = (Organization)obj;
	        organization.setEnabled(true);
	        organization.setCountryCode("SE");
	        organization.setLanguageCode("sv");
            organization.setAutoUpdateEmail(true);
            organization.setAutoUpdateMatchFields(true);
	    }
	}

	private void setObjectAttributes(Object object, String[] attributeValues, boolean isParentObject)
		throws MegatronException {

	    String className =  object.getClass().getSimpleName();
        log.debug("Decorating object of class " + className);

        if (attributeValues.length < 1) {
	        log.info("Empty attribute values for class " + className + ", exiting");
	        return;
	    }

		try {
			String[] attributeNames = this.objectParameterNames.get(className);

			if(attributeNames == null) {
			    throw new MegatronException("Emtpy attributeNames for object " + className);
			}

			Method[] methods = object.getClass().getMethods();
			for (int a=0; a<attributeNames.length; a++) {

				String methodName = "set" + attributeNames[a];
				//log.debug("Method is : " + methodName);

				for (Method method : methods) {
					//log.debug("Method is " + method.getName());
					// Check if method name matches and if it is allowed to be automaticly edited
					if (method.getName().equals(methodName) && canAutoEditAttribute(methodName, object)) {

						Class<?>[] paramTypes = method.getParameterTypes();
						for (Class<?> paramClass: paramTypes) {
							log.debug("Class found " + paramClass.getName());
							String paramTypeName = method.getGenericParameterTypes()[0].toString();
							Matcher classNameMatcher = Pattern.compile(SET_CLASS_NAME_REG_EXP).matcher(paramTypeName);
							if (classNameMatcher.matches() && canAutoEditSet(object)) {
								// Set
								log.debug("Found Set " + paramTypeName);

								String[] setValues = attributeValues[a].split(",");
								relatedObjectsToAdd.put(classNameMatcher.group(1), setValues);

							}
							else {

								Object valueObject = null;
								valueObject = setMethodParameter(attributeValues[a], paramClass);

	 							if (valueObject != null) {
	 								log.debug("Invoking method: " + method.getName() + " on " + object.getClass().getSimpleName() + " whith " +  valueObject.toString());
	 								log.debug("ParamClass = " + paramClass.getSimpleName());
	 								method.invoke(object, valueObject);
	 							}
							}
						}

					}
				}
			}
			if (isParentObject){
				Method dbMethod = dbm.getClass().getMethod("add" + className , this.parentObject.getClass());
				// Save the object
				log.debug("Saving object " + dbMethod.getName());
				dbMethod.invoke(dbm, this.parentObject);
				if (relatedObjectsToAdd.isEmpty() ==  false && addRelatedObjects()) {
					//save again
					dbMethod.invoke(dbm, this.parentObject);
				}
			}
			//dbm.getClass().getMethod("add" + className, null).invoke(dbm, theObject);
		} catch (Exception e) {
			throw handleException("setObjectAttributes", e);
		}
	}

	private Object setMethodParameter(String attributeValue, Type type)
		throws DbException {

		Object valueObject = null;

		log.debug("Type is " + type.toString());
		log.debug("Value is: " + attributeValue);

		if ((type.equals(Integer.TYPE) || type.toString().endsWith(INTEGER_CLASS_NAME)) && attributeValue.equals("") == false ) {
			valueObject = new Integer(attributeValue);
		}
		else if ((type.equals(Long.TYPE) || type.toString().endsWith(LONG_CLASS_NAME)) && attributeValue.equals("") == false ) {
			valueObject = new Long(attributeValue);
		}
		else if (type.equals(Boolean.TYPE) && attributeValue.equals("") == false) {
			valueObject = new Boolean(attributeValue);
		}
		else if (type.toString().endsWith(STRING_CLASS_NAME)) {
		    if (attributeValue.trim().equals("") == false) {
		        valueObject = attributeValue;
		    }
		}
		else if (type.toString().endsWith(PRIORITY_CLASS_NAME)) {
			log.debug("Object is prio, value is " + attributeValue);
			valueObject = dbm.getPriority(Integer.parseInt(attributeValue));
		}
		else if (type.toString().endsWith(ENTRYTYPE_CLASS_NAME)) {
			log.debug("Object is EntryType, value is " + attributeValue);
			valueObject = dbm.genericLoadObject(ENTRYTYPE_CLASS_NAME, "Name", attributeValue);
		}
		else {
			log.error("Unknown type " + type.toString());
		}
		return valueObject;
	}

	private boolean addRelatedObjects() throws MegatronException {

		boolean result = false;

		Set<String> objectNames = relatedObjectsToAdd.keySet();

		while (objectNames.iterator().hasNext()) {
			try {
				String relatedClassName = objectNames.iterator().next();
				Object obj;

				String[] valueList = relatedObjectsToAdd.get(relatedClassName);
				for (String objectValues : valueList) {
					log.debug("Object values: " + objectValues);
				}

				relatedObjectsToAdd.remove(relatedClassName);
				for (String objectValues : valueList) {
					String[] values = objectValues.split("-");

					// Dirty solution to convert ip-address for IpRange object from dotted format to numeric format.
					if (relatedClassName.endsWith(IPRANGE_CLASS_NAME)) {
						for (int i=0;i<values.length;i++) {
						    if (values[i]!= null && values[i].equals("") == false) {
						        values[i] = Long.toString(IpAddressUtil.convertIpAddress(values[i]));
						    }
						}
					}
					obj = createOrLoadObject(relatedClassName, values);
					if (obj != null) {
					    // Check that parent is same
					    Type paramType = getMethodParamType(obj.getClass().getSimpleName(), SET_ORGANIZATION_ID);
					    if (paramType != null) {
					        Object ownerId = obj.getClass().getMethod(GET_ORGANIZATION_ID).invoke(obj);
					        Object parentId = this.parentObject.getClass().getMethod("getId").invoke(this.parentObject);
					        if (ownerId != null && parentId != null && ownerId.equals(parentId) == false) {
					            // Object owned by another parent.
					            throw handleException ("", new MegatronException("Conflict! " + obj.getClass().getSimpleName() + " is allready owned by "
					                    + this.parentObject.getClass().getSimpleName() + " with id " + parentId));
					        }
					    }

					    setObjectAttributes(obj, values, false);

					    Method addToListMethod = parentObject.getClass().getMethod("addTo" + relatedClassName + "s", obj.getClass());
					    addToListMethod.invoke(this.parentObject, obj);
					}
				}

				log.debug("Empty " + relatedObjectsToAdd.isEmpty());
				result = true;

			} catch (Exception e) {
				throw handleException("addRelatedObjects", e);
			}

		}

		return result;

    }

	private boolean canAutoEditSet(Object obj) {

	    boolean result = true;

	    //Check if class is Organization
	    if (obj.getClass().getSimpleName() == ORGANIZATION_CLASS_NAME) {
	        // Check if automatic update is allowed.
	        result = ((Organization)obj).isAutoUpdateMatchFields();
	    }
	    return result;
	}

	private boolean canAutoEditAttribute(String methodName, Object obj) {

        boolean result = true;

        //Check if class is Organization
        if (methodName.equals(SET_EMAILS_METHOD_NAME) && obj.getClass().getSimpleName() == ORGANIZATION_CLASS_NAME) {
            // Check if automatic update is allowed.
            result = ((Organization)obj).isAutoUpdateEmail();
        }
        return result;
    }

	private MegatronException handleException(String methodName, Exception e) {

		MegatronException result = null;

		String msg = e.getClass().getSimpleName() + " in " + methodName + "; (import file line no: " + readLinesC + ") : " + e.getMessage();
		log.error(msg, e);
		if (e.getClass().getSimpleName().equals("MegatronException")){
			result = (MegatronException)e;
		}
		else {
			e.printStackTrace();
		    result = new MegatronException(msg);
		}
		return result;
	}

	public static void main(String[] args) {

		try {

			HashMap<String, String> propMap = new HashMap<String, String>();
			propMap.put("import.dataFile", "/home/gope/workspace/megatron-java/db-import/systemdata.txt");
			TypedProperties props = new TypedProperties(new HashMap<String, String>(), null);

			ImportSystemData sdp = new ImportSystemData(props);
			sdp.importFile();

		} catch (MegatronException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
}


text:
package chrome.system.memory.bindings

import scala.scalajs.js

class MemoryInfo extends js.Object {

  def capacity: Double = js.native

  def availableCapacity: Double = js.native

}


text:
<?php

require 'vendor/autoload.php';

use Aws\Iam\IamClient;
use Aws\Exception\AwsException;

/**
 * Create IAM user
 *
 * This code expects that you have AWS credentials set up per:
 * http://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/credentials.html
 */

$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->createUser(array(
        // UserName is required
        'UserName' => 'string',
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Template Name
    |--------------------------------------------------------------------------
    |
    | The name of the view template used to generate the flash code.
    |
    | Bootstrap 3                           : templates.bootstrap.default
    | ZURB Foundation                       : templates.foundation.default
    | ZURB Foundation (Small Border Radius) : templates.foundation.radius
    | ZURB Foundation (Round Border Radius) : templates.foundation.round
    |
    */

  'template' => 'flash::templates.bootstrap.default',

];


text: Corpo da Aula/lição


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="robots" content="index, follow, all" />
    <title>Thelia\Model\Tools\UrlRewritingTrait | Thelia 2 API</title>

            <link rel="stylesheet" type="text/css" href="../../../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../../../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../../../css/sami.css">

        <meta name="MobileOptimized" content="width">
        <meta name="HandheldFriendly" content="true">
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">

                <form id="search-form" action="../../../search.html" method="GET">

            <input name="search"
                   class="typeahead form-control"
                   type="search"
                   placeholder="Search">
        </form>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
                    Toggle navigation

                </button>
                Thelia 2 API

Classes

Namespaces

Interfaces

Traits

Index

Search

trait

Thelia

Model

Tools

UrlRewritingTrait

UrlRewritingTrait

    trait
    UrlRewritingTrait

A trait for managing Rewritten URLs from model classes

Methods

                    getRewrittenUrlViewName()

No description

                    getUrl(
    string $locale = null)

Get the object URL for the given locale, rewritten if rewriting is enabled.

                    generateRewrittenUrl(
    string $locale)

Generate a rewritten URL from the object title, and store it in the rewriting table

    null

                    getRewrittenUrl(
    string $locale)

return the rewritten URL for the given locale

                    markRewrittenUrlObsolete()

Mark the current URL as obseolete

    $this

                    setRewrittenUrl(
    string $locale, $url)

Set the rewritten URL for the given locale

Details

at line 32

            abstract

    getRewrittenUrlViewName()

at line 39

    getUrl(
    string $locale = null)

Get the object URL for the given locale, rewritten if rewriting is enabled.

Parameters

    string
                $locale
                a valid locale (e.g. en_US)

at line 53

    generateRewrittenUrl(
    string $locale)

Generate a rewritten URL from the object title, and store it in the rewriting table

Parameters

    string
                $locale
                a valid locale (e.g. en_US)

at line 109

    null
    getRewrittenUrl(
    string $locale)

return the rewritten URL for the given locale

Parameters

    string
                $locale
                a valid locale (e.g. en_US)

Return Value

    null

at line 131

    markRewrittenUrlObsolete()

Mark the current URL as obseolete

at line 150

    $this
    setRewrittenUrl(
    string $locale, $url)

Set the rewritten URL for the given locale

Parameters

    string
                $locale
                a valid locale (e.g. en_US)

                $url

Return Value

    $this

Exceptions

                UrlRewritingException

                UrlRewritingException

        Generated by Sami, the API Documentation Generator.


text:
<?php

declare(strict_types=1);

namespace Application\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20210326112100 extends AbstractMigration
{
    public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE scenario_objective (id INT AUTO_INCREMENT NOT NULL, scenario_id INT NOT NULL, name VARCHAR(255) NOT NULL, value DOUBLE PRECISION NOT NULL, priority INT NOT NULL, urgency INT NOT NULL, INDEX IDX_22F22C77E04E49DF (scenario_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET UTF8 COLLATE `UTF8_unicode_ci` ENGINE = InnoDB');
        $this->addSql('ALTER TABLE scenario_objective ADD CONSTRAINT FK_22F22C77E04E49DF FOREIGN KEY (scenario_id) REFERENCES scenario (id)');
    }

    public function down(Schema $schema): void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE scenario_objective');
    }
}


text: include_recipe 'conjur-logging::conjur-ruleset'