text:
@interface ChatViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *messageTable;
@end
@implementation ChatViewController

-(UITableView *)messageTable
{
    if (!_messageTable) {
        _messageTable = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _messageTable.delegate = self;
        _messageTable.dataSource = self;
        _messageTable.backgroundColor = HWColor(244, 244, 244);
        _messageTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _messageTable;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"香格里拉郎";
    self.view.backgroundColor = whiteC;

    [self.view addSubview:self.messageTable];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id cell = nil;
    OtherCell *oCell = [[OtherCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"otherCell"];
    PersonalCell *pCell = [[PersonalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"personalCell"];

    if (indexPath.row == 0) {
        cell = oCell;
    }
    else if (indexPath.row == 1) {
        cell = pCell;
    }
    else if (indexPath.row == 2) {
        cell = pCell;
    }
    else if (indexPath.row == 3) {
        cell = oCell;
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight = 0.0f;
    MessageLayout *olay = [[MessageLayout alloc]initOtherMessageCell];
    MessageLayout *play = [[MessageLayout alloc]initOwnMessageCell];
    switch (indexPath.row) {
        case 0:
        {
            cellHeight = olay.otherMessageHeight;
        }
            break;
        case 1:
        {
            cellHeight = play.ownMessageHeight;
        }
            break;
        case 2:
        {
            cellHeight = play.ownMessageHeight;
        }
            break;
        case 3:
        {
            cellHeight = olay.otherMessageHeight;
        }
            break;
        default:
            break;
    }

    return cellHeight;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


text:
<?php

namespace Digal\Bundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Description of ConsultType
 *
 * @author jesus
 */
class ConsultType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('name', 'text', array('label' => 'false'))
                ->add('email', 'email', array('label' => 'false'))
                ->add('description', 'textarea')
                ->add('save', 'submit')
                ->getForm();
    }

    public function getName() {
        return 'consult';
    }

}

?>

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using Liquid.NET.Expressions;

namespace Liquid.NET.Symbols
{

    public class LiquidExpression
    {

        public IExpressionDescription Expression { get; set; }

        public IList<FilterSymbol> FilterSymbols { get {return _filterSymbols;} }

        private readonly IList<FilterSymbol> _filterSymbols = new List<FilterSymbol>();

        public void AddFilterSymbol(FilterSymbol filterSymbol)
        {
            _filterSymbols.Add(filterSymbol);
        }

    }
}


text:
Subject: la création du compte {{{v.sn}}} {{{v.givenName}}} attend votre modération

Pour modérer la création du compte, accédez à l'application : {{{sv_url}}}.


text:
using System.Collections;
using UnityEngine;

public class UIFade : UITransitions
{
    /// <summary>
    /// Старт
    /// </summary>
    public override void Play()
    {
        base.Play();
    }
    /// <summary>
    /// Обратное выполнение
    /// </summary>
    public override void PlayReverse()
    {
        base.PlayReverse();
    }
    /// <summary>
    /// Затемняем изображение по кривульке
    /// </summary>
    /// <param name="reverse">Передав true будет реверсное выполнение</param>
    protected override IEnumerator Transition(bool reverse = false)
    {
        float keys = !reverse ? 0f : 1f;    // 1 если реверс (старт с конца)

        float _speed = TransitionTime / Time.deltaTime;

        // если пролаг или фпс ниже 20
        _speed = _speed < 20 ? 20 : _speed;

        while (!reverse ? (keys < AMPLITUDE) : keys > 0)
        {
            thisCanvasRenderer.SetAlpha(Curve.Evaluate(keys));

            if (childCanvasRenderer != null)
                foreach(CanvasRenderer cr in childCanvasRenderer)
                {
                    cr.SetAlpha(Curve.Evaluate(keys));
                }

            if (!reverse)
                keys += (AMPLITUDE / _speed);
            else
                keys -= (AMPLITUDE / _speed);
            yield return null;
        }

        thisCanvasRenderer.SetAlpha(!reverse ? 1f : 0f);

        if (childCanvasRenderer != null)
            foreach (CanvasRenderer cr in childCanvasRenderer)
            {
                cr.SetAlpha(!reverse ? 1f : 0f);
            }

        if (OnFinished != null)
            OnFinished.Invoke();
    }

    protected override IEnumerator TransitionLoop(bool reverse = false)
    {
        StartCoroutine(base.TransitionLoop(reverse));
        yield return null;
    }
}


text:
mod tests;

pub mod state;
pub use state::{print_crate, AnnNode, Comments, PpAnn, PrintState, State};

use rustc_ast as ast;
use rustc_ast::token::{Nonterminal, Token, TokenKind};
use rustc_ast::tokenstream::{TokenStream, TokenTree};

use std::borrow::Cow;

pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
    State::new().nonterminal_to_string(nt)
}

/// Print the token kind precisely, without converting `$crate` into its respective crate name.
pub fn token_kind_to_string(tok: &TokenKind) -> Cow<'static, str> {
    State::new().token_kind_to_string(tok)
}

/// Print the token precisely, without converting `$crate` into its respective crate name.
pub fn token_to_string(token: &Token) -> Cow<'static, str> {
    State::new().token_to_string(token)
}

pub fn ty_to_string(ty: &ast::Ty) -> String {
    State::new().ty_to_string(ty)
}

pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
    State::new().bounds_to_string(bounds)
}

pub fn pat_to_string(pat: &ast::Pat) -> String {
    State::new().pat_to_string(pat)
}

pub fn expr_to_string(e: &ast::Expr) -> String {
    State::new().expr_to_string(e)
}

pub fn tt_to_string(tt: &TokenTree) -> String {
    State::new().tt_to_string(tt)
}

pub fn tts_to_string(tokens: &TokenStream) -> String {
    State::new().tts_to_string(tokens)
}

pub fn item_to_string(i: &ast::Item) -> String {
    State::new().item_to_string(i)
}

pub fn path_to_string(p: &ast::Path) -> String {
    State::new().path_to_string(p)
}

pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
    State::new().path_segment_to_string(p)
}

pub fn vis_to_string(v: &ast::Visibility) -> String {
    State::new().vis_to_string(v)
}

pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
    State::new().meta_list_item_to_string(li)
}

pub fn attribute_to_string(attr: &ast::Attribute) -> String {
    State::new().attribute_to_string(attr)
}

pub fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
    State::new().to_string(f)
}


text:
/* Author: Ioan Sucan */

#ifndef MOVEIT_OMPL_INTERFACE_DETAIL_CONSTRAINED_SAMPLER_
#define MOVEIT_OMPL_INTERFACE_DETAIL_CONSTRAINED_SAMPLER_

#include <ompl/base/StateSampler.h>
#include <moveit/constraint_samplers/constraint_sampler.h>

namespace ompl_interface
{
class ModelBasedPlanningContext;

/** @class ConstrainedSampler
 *  This class defines a sampler that tries to find a sample that satisfies the constraints*/
class ConstrainedSampler : public ompl::base::StateSampler
{
public:
  /** @brief Default constructor
   *  @param pg The planning group
   *  @param cs A pointer to a kinematic constraint sampler
   */
  ConstrainedSampler(const ModelBasedPlanningContext* pc, const constraint_samplers::ConstraintSamplerPtr& cs);

  /** @brief Sample a state (uniformly)*/
  virtual void sampleUniform(ompl::base::State* state);

  /** @brief Sample a state (uniformly) within a certain distance of another state*/
  virtual void sampleUniformNear(ompl::base::State* state, const ompl::base::State* near, const double distance);

  /** @brief Sample a state using the specified Gaussian*/
  virtual void sampleGaussian(ompl::base::State* state, const ompl::base::State* mean, const double stdDev);

  double getConstrainedSamplingRate() const;

private:
  bool sampleC(ompl::base::State* state);

  const ModelBasedPlanningContext* planning_context_;
  ompl::base::StateSamplerPtr default_;
  constraint_samplers::ConstraintSamplerPtr constraint_sampler_;
  robot_state::RobotState work_state_;
  unsigned int constrained_success_;
  unsigned int constrained_failure_;
  double inv_dim_;
};
}

#endif


text:
class GeneratorTestsController < ApplicationController
  before_action :set_generator_test, only: [:show, :edit, :update, :destroy]

  # GET /generator_tests
  def index
    @generator_tests = GeneratorTest.all
  end

  # GET /generator_tests/1
  def show
  end

  # GET /generator_tests/new
  def new
    @generator_test = GeneratorTest.new
  end

  # GET /generator_tests/1/edit
  def edit
  end

  # POST /generator_tests
  def create
    @generator_test = GeneratorTest.new(generator_test_params)

    if @generator_test.save
      redirect_to @generator_test, notice: 'Generator test was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /generator_tests/1
  def update
    if @generator_test.update(generator_test_params)
      redirect_to @generator_test, notice: 'Generator test was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /generator_tests/1
  def destroy
    @generator_test.destroy
    redirect_to generator_tests_url, notice: 'Generator test was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_generator_test
      @generator_test = GeneratorTest.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def generator_test_params
      params.require(:generator_test).permit(:name)
    end
end


text:
import os
import subprocess
import sys

#  python run_with_pythonpath.py -I path1 ... -I pathN foo/bar/baz.py args...
#  ==> Run "python foo/bar/baz.py args..." with PYTHONPATH=path1:..:pathN
def main():
    python_paths = []
    args = sys.argv[1:]
    while len(args) >= 2 and args[0] == '-I':
        python_paths.append(args[1])
        args = args[2:]

    env = os.environ.copy()
    if len(python_paths) > 0:
        existing_pp = (
            os.pathsep + env['PYTHONPATH']) if 'PYTHONPATH' in env else ''
        env['PYTHONPATH'] = os.pathsep.join(python_paths) + existing_pp
    sys.exit(subprocess.call([sys.executable] + args, env=env))

if __name__ == '__main__':
    main()


text:
package org.devnexus.vo.contract;

import android.content.ContentValues;
import android.net.Uri;

import com.google.gson.Gson;

import org.devnexus.util.GsonUtils;
import org.devnexus.vo.Schedule;

/**
 * Created by summers on 2/14/14.
 */
public class ScheduleItemContract {
    public static final Uri URI = Uri.parse("content://org.devnexus.sync/ScheduleItem");
    public static final String _ID = "id";
    public static final String DATA = "DATA";

    public static final String NOTIFY = "NOTIFY";
    public static final String PRESENTATION_ID = "scheduleItemList.scheduleItems.presentations.id";
    public static final String TITLE = "scheduleItemList.scheduleItems.presentations.title";
    public static final String SPEAKER_FNAME = "scheduleItemList.scheduleItems.presentations.speaker.firstName";
    public static final String SPEAKER_NAME = "scheduleItemList.scheduleItems.presentations.speaker.lastName";

    public static final String[] COLUMNS = {DATA, NOTIFY};

    private static final Gson GSON = GsonUtils.GSON;
    public static final String FROM_TIME = "scheduleItemList.scheduleItems.fromTime";
    public static final String TRACK = "scheduleItemList.scheduleItems.presentations.track.name";

    /**
     * This method will turn a schedule into the appropriate ContentValues for the app.
     *
     * @param schedule
     * @return
     */
    public static ContentValues valueize(Schedule schedule) {
        ContentValues values = new ContentValues();
        values.put(DATA, GSON.toJson(schedule));
        return values;
    }

    /**
     * This method will make a query out of the selection arguments.
     *
     * @param selection the selections you wish to to query
     * @return a string formatted $selection && $selection1 (ex presentations.speaker.firstName && presentations.speaker.lastName)
     */
    public static String toQuery(String... selection) {
        StringBuilder builder = new StringBuilder();
        String and = "";
        for ( String key : selection ) {
            builder.append(and);
            builder.append(key.trim());
            and = " && ";
        }

        return builder.toString();
    }
}


text:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.0.2/fullcalendar.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.css" />
<link rel="stylesheet" href="css/calendar.css" />

<?=heading($page_title, 2); ?>

<?=$this->session->flashdata('message'); ?>

	<select class="chosen-select select-experiment" multiple data-placeholder="<?=lang('filter_experiment');?>">
		<?php
		foreach (experiment_options($experiments) as $id => $option)
		{
			echo '<option value="' . $id . '">' . $option . '</option>\n';
		}
		?>
	</select>

	<select class="chosen-select select-participant" multiple data-placeholder="<?=lang('filter_participant');?>">
		<?php
		foreach (participant_options($participants) as $id => $option)
		{
			echo '<option value="' . $id . '">' . $option . '</option>\n';
		}
		?>
	</select>

	<select class="chosen-select select-location" multiple data-placeholder="<?=lang('filter_location');?>">
		<?php
		foreach (location_options($locations) as $id => $option)
		{
			echo '<option value="' . $id . '">' . $option . '</option>\n';
		}
		?>
	</select>

	<select class="chosen-select select-leader" multiple data-placeholder="<?=lang('filter_leader');?>">
		<?php
		foreach (leader_options($leaders) as $id => $option)
		{
			echo '<option value="' . $id . '">' . $option . '</option>\n';
		}
		?>
	</select>

			<?=lang('clear_filters');?>

		<input type="checkbox" name="exclude-canceled" style="vertical-align: middle;" checked="checked" id="exclude-canceled" />
		 <?=lang('exclude_empty');?>

		<input type="checkbox" name="include-availability" style="vertical-align: middle;" checked="checked" id="include-availability"/>
		 <?=lang('show_availability');?>

<input type="hidden" name="date_picker" id="date_picker" />


text:
extern crate clap;

use clap::App;

fn main() {
    // You can have clap pull the application version directly from your Cargo.toml starting with
    // clap v0.4.14 on crates.io (or master#a81f915 on github). Using Rust's env! macro like this:
    //
    // let version = format!("{}.{}.{}{}",
    //                  env!("CARGO_PKG_VERSION_MAJOR"),
    //                  env!("CARGO_PKG_VERSION_MINOR"),
    //                  env!("CARGO_PKG_VERSION_PATCH"),
    //                  option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
    //
    // Starting from v0.6.6 on crates.io you can also use the crate_version!() macro instead of
    // manually using the env!() macros. Under the hood, the macro uses this exact method to get
    // the version.
    //
    // Thanks to https://github.com/jhelwig for pointing this out
    App::new("myapp")
        .about("does awesome things")
       // use crate_version! to pull the version number
       .version(&crate_version!()[..])
       .get_matches();

    // running the this app with the -V or --version will display whatever version is in your
    // Cargo.toml, the default being: myapp 0.0.1
}


text:
$("input.register").click(function(){
	window.location.href='./register.php';
});
$("input.back").click(function(){
	window.location.href='./user.php';
});

function update(){

	var	email = document.getElementById("email").innerHTML.substr(7);
	var message = document.getElementById("mess").innerHTML.substr(9);
	var csrftoken = document.getElementById("csrft").innerHTML.substr(11);

	var x = new XMLHttpRequest();
	x.open('POST', './api/update.php', true);
	x.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	x.send('message='+message+'&email='+email+'&csrftoken='+csrftoken);
}

function edit(){
	var newWin = window.open("./edit.php?callback=EditProfile",'','width=600,height=600');
	var loop = setInterval(function() {
	  if(newWin.closed) {
	    clearInterval(loop);
	    update();
	  }
	}, 1000);

};

function random(){
	var newWin = window.open("./edit.php?callback=RandomProfile",'','width=600,height=600');
	var loop = setInterval(function() {
	  if(newWin.closed) {
	    clearInterval(loop);
	    update();
	  }
	}, 1000);

};


text:
#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This file intended to serve as a drop-in replacement for
 *  unistd.h on Windows
 *  Please add functionality as neeeded
 */

#include <stdlib.h>
#include <io.h>
#include <process.h> /* for getpid() and the exec..() family */

#define srandom srand
#define random rand

/* Values for the second argument to access.
   These may be OR'd together.  */
#define R_OK    4       /* Test for read permission.  */
#define W_OK    2       /* Test for write permission.  */
//#define   X_OK    1       /* execute permission - unsupported in windows*/
#define F_OK    0       /* Test for existence.  */

#define access _access
#define ftruncate _chsize

#define ssize_t int

#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8            int8_t;
typedef __int16           int16_t;
typedef __int32           int32_t;
typedef __int64           int64_t;
typedef unsigned __int8   uint8_t;
typedef unsigned __int16  uint16_t;
typedef unsigned __int32  uint32_t;
typedef unsigned __int64  uint64_t;

#endif /* unistd.h  */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace mdryden.cflapi.v1.Models.Players
{
	public class GamePuntReturns : PuntReturns
	{
		[JsonIgnore]
		public int PlayerId { get; set; }

		[JsonProperty("game_id")]
		public int GameId { get; set; }

		[JsonProperty("game_date")]
		public string GameDate { get; set; }

		[JsonProperty("week")]
		public int Week { get; set; }

		[JsonProperty("season")]
		public int Season { get; set; }

		[JsonProperty("opponent_team_abbreviation")]
		public string OpponentTeamAbbreviation { get; set; }
	}
}


text:
package com.eaw1805.data.model.battles.field;

import com.eaw1805.data.model.battles.field.enumerations.FormationEnum;
import com.eaw1805.data.model.battles.field.enumerations.DetachmentPosition;
import com.eaw1805.data.model.battles.field.enumerations.OrdersEnum;
import com.eaw1805.data.model.Nation;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Order implements Serializable {

    /**
     * Required by Serializable interface.
     */
    static final long serialVersionUID = 42L; //NOPMD

    private int id;

    // basic properties
    private String orderType;
    private FieldBattlePosition checkpoint1;
    private FieldBattlePosition checkpoint2;
    private FieldBattlePosition checkpoint3;
    private boolean reachedCheckpoint1;
    private boolean reachedCheckpoint2;
    private boolean reachedCheckpoint3;
    private String formation;

    // order-specific
    private Integer maintainDistance;
    private FieldBattlePosition strategicPoint1;
    private FieldBattlePosition strategicPoint2;
    private FieldBattlePosition strategicPoint3;
    private Integer constructionCounter;
    private FieldBattlePosition defendPositionArtilleryTarget;
    private int detachmentLeaderId;
    private String detachmentPosition;

    // target filters
    private Set<Nation> targetNations = new HashSet<Nation>();
    private String targetArm;
    private String targetFormation;
    private boolean targetHighestHeadcount;
    private boolean targetClosestInRange;

    // alternative order triggers
    private int activationRound;
    private int headCountThreshold;
    private boolean lastDestinationReached;
    private boolean ownSideCapturedEnemyStrategicPoint;
    private boolean enemySideCapturedOwnStrategicPoint;
    private FieldBattlePosition customStrategicPoint1;
    private FieldBattlePosition customStrategicPoint2;
    private FieldBattlePosition customStrategicPoint3;
    private Order backup;

    public int getActivationRound() {
        return activationRound;
    }

    public void setActivationRound(int activationRound) {
        this.activationRound = activationRound;
    }

    public String getOrderType() {
        return orderType;
    }

    public void setOrderType(String orderType) {
        this.orderType = orderType;
    }

    public void setOrderTypeEnum(OrdersEnum orderType) {
        this.orderType = orderType.toString();
    }

    public OrdersEnum getOrderTypeEnum() {
        return OrdersEnum.valueOf(this.orderType);
    }

    public int getHeadCountThreshold() {
        return headCountThreshold;
    }

    public void setHeadCountThreshold(int headCountThreshold) {
        this.headCountThreshold = headCountThreshold;
    }

    public boolean isLastDestinationReached() {
        return lastDestinationReached;
    }

    public void setLastDestinationReached(boolean lastDestinationReached) {
        this.lastDestinationReached = lastDestinationReached;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public FieldBattlePosition getCheckpoint1() {
        return checkpoint1;
    }

    public void setCheckpoint1(FieldBattlePosition checkpoint1) {
        this.checkpoint1 = checkpoint1;
    }

    public FieldBattlePosition getCheckpoint2() {
        return checkpoint2;
    }

    public void setCheckpoint2(FieldBattlePosition checkpoint2) {
        this.checkpoint2 = checkpoint2;
    }

    public FieldBattlePosition getCheckpoint3() {
        return checkpoint3;
    }

    public void setCheckpoint3(FieldBattlePosition checkpoint3) {
        this.checkpoint3 = checkpoint3;
    }

    public boolean isReachedCheckpoint1() {
        return reachedCheckpoint1;
    }

    public void setReachedCheckpoint1(boolean reachedCheckpoint1) {
        this.reachedCheckpoint1 = reachedCheckpoint1;
    }

    public boolean isReachedCheckpoint2() {
        return reachedCheckpoint2;
    }

    public void setReachedCheckpoint2(boolean reachedCheckpoint2) {
        this.reachedCheckpoint2 = reachedCheckpoint2;
    }

    public boolean isReachedCheckpoint3() {
        return reachedCheckpoint3;
    }

    public void setReachedCheckpoint3(boolean reachedCheckpoint3) {
        this.reachedCheckpoint3 = reachedCheckpoint3;
    }

    public Integer getMaintainDistance() {
        return maintainDistance;
    }

    public void setMaintainDistance(Integer maintainDistance) {
        this.maintainDistance = maintainDistance;
    }

    @Override
    public String toString() {
        return orderType;
    }

    public FieldBattlePosition getStrategicPoint1() {
        return strategicPoint1;
    }

    public void setStrategicPoint1(FieldBattlePosition strategicPoint1) {
        this.strategicPoint1 = strategicPoint1;
    }

    public FieldBattlePosition getStrategicPoint2() {
        return strategicPoint2;
    }

    public void setStrategicPoint2(FieldBattlePosition strategicPoint2) {
        this.strategicPoint2 = strategicPoint2;
    }

    public FieldBattlePosition getStrategicPoint3() {
        return strategicPoint3;
    }

    public void setStrategicPoint3(FieldBattlePosition strategicPoint3) {
        this.strategicPoint3 = strategicPoint3;
    }

    public Set<Nation> getTargetNations() {
        return targetNations;
    }

    public void setTargetNations(Set<Nation> targetNations) {
        this.targetNations = targetNations;
    }

    public String getTargetArm() {
        return targetArm;
    }

    public void setTargetArm(String targetArm) {
        this.targetArm = targetArm;
    }

    public String getTargetFormation() {
        return targetFormation;
    }

    public void setTargetFormation(String targetFormation) {
        this.targetFormation = targetFormation;
    }

    public boolean isTargetHighestHeadcount() {
        return targetHighestHeadcount;
    }

    public void setTargetHighestHeadcount(boolean targetHighestHeadcount) {
        this.targetHighestHeadcount = targetHighestHeadcount;
    }

    public boolean isTargetClosestInRange() {
        return targetClosestInRange;
    }

    public void setTargetClosestInRange(boolean targetClosestInRange) {
        this.targetClosestInRange = targetClosestInRange;
    }

    public Integer getConstructionCounter() {
        return constructionCounter;
    }

    public void setConstructionCounter(Integer constructionCounter) {
        this.constructionCounter = constructionCounter;
    }

    public String getFormation() {
        return formation;
    }

    public void setFormation(String formation) {
        this.formation = formation;
    }

    public FormationEnum getFormationEnum() {
        return FormationEnum.valueOf(formation);
    }

    public void setFormationEnum(FormationEnum formationEnum) {
        this.formation = formationEnum.toString();
    }

    public boolean isOwnSideCapturedEnemyStrategicPoint() {
        return ownSideCapturedEnemyStrategicPoint;
    }

    public void setOwnSideCapturedEnemyStrategicPoint(
            boolean ownSideCapturedEnemyStrategicPoint) {
        this.ownSideCapturedEnemyStrategicPoint = ownSideCapturedEnemyStrategicPoint;
    }

    public boolean isEnemySideCapturedOwnStrategicPoint() {
        return enemySideCapturedOwnStrategicPoint;
    }

    public void setEnemySideCapturedOwnStrategicPoint(
            boolean enemySideCapturedOwnStrategicPoint) {
        this.enemySideCapturedOwnStrategicPoint = enemySideCapturedOwnStrategicPoint;
    }

    public FieldBattlePosition getCustomStrategicPoint1() {
        return customStrategicPoint1;
    }

    public void setCustomStrategicPoint1(FieldBattlePosition customStrategicPoint1) {
        this.customStrategicPoint1 = customStrategicPoint1;
    }

    public FieldBattlePosition getCustomStrategicPoint2() {
        return customStrategicPoint2;
    }

    public void setCustomStrategicPoint2(FieldBattlePosition customStrategicPoint2) {
        this.customStrategicPoint2 = customStrategicPoint2;
    }

    public FieldBattlePosition getCustomStrategicPoint3() {
        return customStrategicPoint3;
    }

    public void setCustomStrategicPoint3(FieldBattlePosition customStrategicPoint3) {
        this.customStrategicPoint3 = customStrategicPoint3;
    }

    public Order getBackup() {
        return backup;
    }

    public void setBackup(Order backup) {
        this.backup = backup;
    }

    public int getDetachmentLeaderId() {
        return detachmentLeaderId;
    }

    public void setDetachmentLeaderId(int detachmentLeaderId) {
        this.detachmentLeaderId = detachmentLeaderId;
    }

    public String getDetachmentPosition() {
        return detachmentPosition;
    }

    public void setDetachmentPosition(String detachmentPosition) {
        this.detachmentPosition = detachmentPosition;
    }

    public DetachmentPosition getDetachmentPositionEnum() {
        return DetachmentPosition.valueOf(detachmentPosition);
    }

    public void setDetachmentPosition(DetachmentPosition detachmentPosition) {
        this.detachmentPosition = detachmentPosition.toString();
    }

    public FieldBattlePosition getDefendPositionArtilleryTarget() {
        return defendPositionArtilleryTarget;
    }

    public void setDefendPositionArtilleryTarget(
            FieldBattlePosition defendPositionArtilleryTarget) {
        this.defendPositionArtilleryTarget = defendPositionArtilleryTarget;
    }
}


text:
<?php

namespace Magento\Backend\Test\Unit\Model\View\Layout\Filter;

class AclTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Backend\Model\View\Layout\Filter\Acl
     */
    protected $model;

    /**
     * @var \Magento\Framework\AuthorizationInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $authorizationMock;

    protected function setUp()
    {
        $this->authorizationMock = $this->getMockBuilder('Magento\Framework\AuthorizationInterface')
            ->getMock();

        $this->model = new \Magento\Backend\Model\View\Layout\Filter\Acl($this->authorizationMock);
    }

    public function testFilterAclElements()
    {
        $scheduledStructureMock = $this->getMockBuilder('Magento\Framework\View\Layout\ScheduledStructure')
            ->disableOriginalConstructor()
            ->getMock();

        $structureMock = $this->getMockBuilder('Magento\Framework\View\Layout\Data\Structure')
            ->disableOriginalConstructor()
            ->getMock();

        $elements = [
            'element_0' => [
                0 => '',
                1 => [
                    'attributes' => [
                        'name' => 'element_0',
                    ],
                ],
            ],
            'element_1' => [
                0 => '',
                1 => [
                    'attributes' => [
                        'name' => 'element_1',
                        'acl' => 'acl_authorised',
                    ],
                ],
            ],
            'element_2' => [
                0 => '',
                1 => [
                    'attributes' => [
                        'name' => 'element_2',
                        'acl' => 'acl_non_authorised',
                    ],
                ],
            ],
            'element_3' => [
                0 => '',
                1 => [
                    'attributes' => [
                        'name' => 'element_3',
                        'acl' => 'acl_non_authorised',
                    ],
                ],
            ],
        ];

        $scheduledStructureMock->expects($this->once())
            ->method('getElements')
            ->willReturn($elements);

        $this->authorizationMock->expects($this->exactly(3))
            ->method('isAllowed')
            ->willReturnMap(
                [
                    ['acl_authorised', null, true],
                    ['acl_non_authorised', null, false],
                ]
            );

        $structureMock->expects($this->exactly(3))
            ->method('getChildren')
            ->willReturnMap(
                [
                    ['element_2', ['element_2_child' => []]],
                    ['element_2_child', []],
                    ['element_3', []],
                ]
            );

        $scheduledStructureMock->expects($this->exactly(3))
            ->method('unsetElement')
            ->willReturnMap(
                [
                    ['element_2', null],
                    ['element_2_child', null],
                    ['element_3', null],
                ]
            );

        $structureMock->expects($this->exactly(2))
            ->method('unsetElement')
            ->willReturnMap(
                [
                    ['element_2', true, true],
                    ['element_3', true, true],
                ]
            );

        $this->model->filterAclElements($scheduledStructureMock, $structureMock);
    }
}


text:
#ifndef TextDecorationPainter_h
#define TextDecorationPainter_h

#include "Color.h"
#include "FloatPoint.h"
#include "RenderStyleConstants.h"

namespace WebCore {

class FontCascade;
class GraphicsContext;
class InlineTextBox;
class RenderStyle;
class RenderText;
class ShadowData;
class TextRun;

class TextDecorationPainter {
public:
    TextDecorationPainter(GraphicsContext&, TextDecoration, const RenderText&, bool isFirstLine);

    void setInlineTextBox(const InlineTextBox* inlineTextBox) { m_inlineTextBox = inlineTextBox; }
    void setFont(const FontCascade& font) { m_font = &font; }
    void setIsHorizontal(bool isHorizontal) { m_isHorizontal = isHorizontal; }
    void setWidth(float width) { m_width = width; }
    void setBaseline(int baseline) { m_baseline = baseline; }
    void addTextShadow(const ShadowData* textShadow) { m_shadow = textShadow; }

    void paintTextDecoration(const TextRun&, const FloatPoint& textOrigin, const FloatPoint& boxOrigin);

private:
    GraphicsContext& m_context;
    TextDecoration m_decoration;
    int m_wavyOffset { 0 };
    bool m_isPrinting { false };
    float m_width { 0 };
    int m_baseline { 0 };
    FloatPoint m_boxOrigin;
    bool m_isHorizontal { true };
    const ShadowData* m_shadow { nullptr };
    const InlineTextBox* m_inlineTextBox { nullptr };
    const FontCascade* m_font { nullptr };

    Color m_underlineColor;
    Color m_overlineColor;
    Color m_linethroughColor;
    TextDecorationStyle m_underlineStyle;
    TextDecorationStyle m_overlineStyle;
    TextDecorationStyle m_linethroughStyle;
    const RenderStyle& m_lineStyle;
};

} // namespace WebCore

#endif // TextDecorationPainter_h


text:
using Caliburn.Micro;
using SimpleDnsCrypt.Config;
using SimpleDnsCrypt.Helper;
using SimpleDnsCrypt.Models;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using DnsCrypt.Blacklist;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;

namespace SimpleDnsCrypt.ViewModels
{
	[Export(typeof(DomainBlockLogViewModel))]
	public class DomainBlockLogViewModel : Screen
	{
		private static readonly ILog Log = LogManagerHelper.Factory();
		private readonly IWindowManager _windowManager;
		private readonly IEventAggregator _events;

		private ObservableCollection<DomainBlockLogLine> _domainBlockLogLines;
		private string _domainBlockLogFile;
		private bool _isDomainBlockLogLogging;
		private DomainBlockLogLine _selectedDomainBlockLogLine;

		[ImportingConstructor]
		public DomainBlockLogViewModel(IWindowManager windowManager, IEventAggregator events)
		{
			_windowManager = windowManager;
			_events = events;
			_events.Subscribe(this);
			_isDomainBlockLogLogging = false;
			_domainBlockLogLines = new ObservableCollection<DomainBlockLogLine>();
		}

		private void AddLogLine(DomainBlockLogLine domainBlockLogLine)
		{
			Execute.OnUIThread(() =>
			{
				DomainBlockLogLines.Add(domainBlockLogLine);
			});
		}

		public void ClearDomainBlockLog()
		{
			Execute.OnUIThread(() => { DomainBlockLogLines.Clear(); });
		}

		public ObservableCollection<DomainBlockLogLine> DomainBlockLogLines
		{
			get => _domainBlockLogLines;
			set
			{
				if (value.Equals(_domainBlockLogLines)) return;
				_domainBlockLogLines = value;
				NotifyOfPropertyChange(() => DomainBlockLogLines);
			}
		}

		public string DomainBlockLogFile
		{
			get => _domainBlockLogFile;
			set
			{
				if (value.Equals(_domainBlockLogFile)) return;
				_domainBlockLogFile = value;
				NotifyOfPropertyChange(() => DomainBlockLogFile);
			}
		}

		public DomainBlockLogLine SelectedDomainBlockLogLine
		{
			get => _selectedDomainBlockLogLine;
			set
			{
				_selectedDomainBlockLogLine = value;
				NotifyOfPropertyChange(() => SelectedDomainBlockLogLine);
			}
		}

		public bool IsDomainBlockLogLogging
		{
			get => _isDomainBlockLogLogging;
			set
			{
				_isDomainBlockLogLogging = value;
				DomainBlockLog(DnscryptProxyConfigurationManager.DnscryptProxyConfiguration);
				NotifyOfPropertyChange(() => IsDomainBlockLogLogging);
			}
		}

		public async void UnblockBlockLogEntry()
		{
			try
			{
				if (_selectedDomainBlockLogLine == null) return;
				if (MainViewModel.Instance.DomainBlacklistViewModel == null) return;
				var dialogSettings = new MetroDialogSettings
				{
					DefaultText = _selectedDomainBlockLogLine.Message.ToLower(),
					AffirmativeButtonText = LocalizationEx.GetUiString("add", Thread.CurrentThread.CurrentCulture),
					NegativeButtonText = LocalizationEx.GetUiString("cancel", Thread.CurrentThread.CurrentCulture),
					ColorScheme = MetroDialogColorScheme.Theme
				};

				var metroWindow = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
				//TODO: translate
				var dialogResult = await metroWindow.ShowInputAsync(LocalizationEx.GetUiString("message_title_new_whitelist_rule", Thread.CurrentThread.CurrentCulture),
					"Rule:", dialogSettings);

				if (string.IsNullOrEmpty(dialogResult)) return;
				var newCustomRule = dialogResult.ToLower().Trim();
				var parsed = DomainBlacklist.ParseBlacklist(newCustomRule, true);
				var enumerable = parsed as string[] ?? parsed.ToArray();
				if (enumerable.Length != 1) return;
				MainViewModel.Instance.DomainBlacklistViewModel.DomainWhitelistRules.Add(enumerable[0]);
				MainViewModel.Instance.DomainBlacklistViewModel.SaveWhitelistRulesToFile();
			}
			catch (Exception exception)
			{
				Log.Error(exception);
			}
		}

		private async void DomainBlockLog(DnscryptProxyConfiguration dnscryptProxyConfiguration)
		{
			const string defaultLogFormat = "ltsv";
			try
			{
				if (_isDomainBlockLogLogging)
				{
					if (dnscryptProxyConfiguration == null) return;

					var saveAndRestartService = false;
					if (dnscryptProxyConfiguration.blacklist == null)
					{
						dnscryptProxyConfiguration.blacklist = new Blacklist
						{
							log_file = Global.DomainBlockLogFileName,
							log_format = defaultLogFormat
						};
						saveAndRestartService = true;
					}

					if (string.IsNullOrEmpty(dnscryptProxyConfiguration.blacklist.log_format) ||
						!dnscryptProxyConfiguration.blacklist.log_format.Equals(defaultLogFormat))
					{
						dnscryptProxyConfiguration.blacklist.log_format = defaultLogFormat;
						saveAndRestartService = true;
					}

					if (string.IsNullOrEmpty(dnscryptProxyConfiguration.blacklist.log_file))
					{
						dnscryptProxyConfiguration.blacklist.log_file = Global.DomainBlockLogFileName;
						saveAndRestartService = true;
					}

					if (saveAndRestartService)
					{
						DnscryptProxyConfigurationManager.DnscryptProxyConfiguration = dnscryptProxyConfiguration;
						if (DnscryptProxyConfigurationManager.SaveConfiguration())
						{
							if (DnsCryptProxyManager.IsDnsCryptProxyInstalled())
							{
								if (DnsCryptProxyManager.IsDnsCryptProxyRunning())
								{
									DnsCryptProxyManager.Restart();
									await Task.Delay(Global.ServiceRestartTime).ConfigureAwait(false);
								}
								else
								{
									DnsCryptProxyManager.Start();
									await Task.Delay(Global.ServiceStartTime).ConfigureAwait(false);
								}
							}
							else
							{
								await Task.Run(() => DnsCryptProxyManager.Install()).ConfigureAwait(false);
								await Task.Delay(Global.ServiceInstallTime).ConfigureAwait(false);
								if (DnsCryptProxyManager.IsDnsCryptProxyInstalled())
								{
									DnsCryptProxyManager.Start();
									await Task.Delay(Global.ServiceStartTime).ConfigureAwait(false);
								}
							}
						}
					}

					DomainBlockLogFile = Path.Combine(Directory.GetCurrentDirectory(), Global.DnsCryptProxyFolder,
						dnscryptProxyConfiguration.blacklist.log_file);

					if (!string.IsNullOrEmpty(_domainBlockLogFile))
					{
						if (!File.Exists(_domainBlockLogFile))
						{
							File.Create(_domainBlockLogFile).Dispose();
							await Task.Delay(50);
						}

						await Task.Run(() =>
						{
							using (var reader = new StreamReader(new FileStream(_domainBlockLogFile,
								FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
							{
								//start at the end of the file
								var lastMaxOffset = reader.BaseStream.Length;

								while (_isDomainBlockLogLogging)
								{
									Thread.Sleep(100);
									//if the file size has not changed, idle
									if (reader.BaseStream.Length == lastMaxOffset)
										continue;

									//seek to the last max offset
									reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

									//read out of the file until the EOF
									string line;
									while ((line = reader.ReadLine()) != null)
									{
										var blockLogLine = new DomainBlockLogLine(line);
										AddLogLine(blockLogLine);
									}

									//update the last max offset
									lastMaxOffset = reader.BaseStream.Position;
								}
							}
						}).ConfigureAwait(false);
					}
					else
					{
						IsDomainBlockLogLogging = false;
					}
				}
				else
				{
					//disable block log again
					_isDomainBlockLogLogging = false;
					dnscryptProxyConfiguration.blacklist.log_file = null;
					DnscryptProxyConfigurationManager.DnscryptProxyConfiguration = dnscryptProxyConfiguration;
					DnscryptProxyConfigurationManager.SaveConfiguration();
					if (DnsCryptProxyManager.IsDnsCryptProxyRunning())
					{
						DnsCryptProxyManager.Restart();
						await Task.Delay(Global.ServiceRestartTime).ConfigureAwait(false);
					}
					Execute.OnUIThread(() => { DomainBlockLogLines.Clear(); });
				}
			}
			catch (Exception exception)
			{
				Log.Error(exception);
			}
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JsonSchemaMappingsProjectConfiguration">
    <state>
      <map>
        <entry key="schema1">
          <value>
            <SchemaInfo>
              <option name="generatedName" value="New Schema" />
              <option name="name" value="schema1" />
              <option name="relativePathToSchema" value="data/schema1.json" />
              <option name="patterns">
                <list>
                  <Item>
                    <option name="path" value="data/spike.json" />
                  </Item>
                </list>
              </option>
            </SchemaInfo>
          </value>
        </entry>
      </map>
    </state>
  </component>
</project>


text:
ActiveRecord::Schema.define(version: 20150203220642) do

  create_table "actors", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "player_id"
    t.integer  "x"
    t.integer  "y"
  end

  add_index "actors", ["player_id"], name: "index_actors_on_player_id"

  create_table "game_actions", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "turn_id"
    t.integer  "moveto_x"
    t.integer  "moveto_y"
    t.integer  "actor_id"
  end

  create_table "game_events", force: true do |t|
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "turn_id"
  end

  create_table "games", force: true do |t|
    t.text     "terrain"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "current_turn", default: 0
  end

  create_table "players", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "game_id"
  end

  add_index "players", ["game_id"], name: "index_players_on_game_id"

  create_table "turns", force: true do |t|
    t.integer  "sequence"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "game_id"
  end

  add_index "turns", ["game_id"], name: "index_turns_on_game_id"

end


text:
Genderize
=========

Updated version of [redox/genderize](https://github.com/redox/genderize) to make it an initializer in rails 4.

From the original README:

"Genderize modifies existing I18n.translate method so it can provide gender-based distinctions."

This generator updates Genderize to use it an initializer for Rails 4 apps - used in 4.1 -.
gender option is added directly in I18n.

Example
=======

In fr.yml file

fr:
  test1: "affamé[[e]]"
  test2: "amat[[eur,rice]]"

I18n.t :test1, :gender => :male # "affamé"
I18n.t :test1, :gender => :female # "affamée"
I18n.t :test2, :gender => :male # "amateur"
I18n.t :test2, :gender => :female # "amatrice

Compatible with new hash syntax

I18n.t :test1, gender: :male # "affamé"
I18n.t :test1, gender: :female # "affamée"
I18n.t :test2, gender: :male # "amateur"
I18n.t :test2, gender: :female # "amatrice

Usage
=====

Gemfile

gem 'i18n-genderize', github: "eamexicano/genderize", group: :development, require: false

Terminal

$ bundle install

$ rails generate genderize
 # =>  create  config/initializers/i18n.rb

Follow example syntax in your i18n files


text:
package cz.jiripudil.intellij.nette.tester.lineMarker;

import com.intellij.execution.lineMarker.RunLineMarkerContributor;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import cz.jiripudil.intellij.nette.tester.TesterIcons;
import cz.jiripudil.intellij.nette.tester.action.TesterCreateMethodRunTestAction;
import cz.jiripudil.intellij.nette.tester.action.TesterMethodRunTestAction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class TesterMethodRunLineMarkerProvider extends RunLineMarkerContributor {
    static String TEST_METHOD_PREFIX = "test";

    @Override
    public @Nullable Info getInfo(@NotNull PsiElement psiElement) {
        if (psiElement.getNode().getElementType() == PhpTokenTypes.IDENTIFIER) {
            PsiElement method = psiElement.getParent();
            if (method instanceof Method) {
                String methodName = ((Method) method).getName();
                if (!methodName.startsWith(TEST_METHOD_PREFIX)) {
                    return null;
                }

                PhpClass phpClass = ((Method) method).getContainingClass();
                String className = phpClass != null ? phpClass.getName() : "null";

                if (psiElement.getText().equals(methodName)) {
                    AnAction[] actions = new AnAction[2];
                    actions[0] = new TesterMethodRunTestAction(psiElement, className, methodName);
                    actions[1] = new TesterCreateMethodRunTestAction(psiElement, className, methodName);

                    return new Info(TesterIcons.RUN_METHOD, actions, RunLineMarkerContributor.RUN_TEST_TOOLTIP_PROVIDER);
                }
            }
        }
        return null;
    }

}


text:
package com.bagri.xdm.process.coherence;

import static com.bagri.xdm.access.api.XDMCacheConstants.CN_XDM_ELEMENT;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.xml.transform.Source;

import com.bagri.common.query.ExpressionBuilder;
import com.bagri.common.query.ExpressionContainer;
import com.bagri.common.query.PathExpression;
import com.bagri.xdm.access.api.XDMDocumentManagementServer;
import com.bagri.xdm.access.coherence.impl.QueryHelper;
import com.bagri.xdm.common.XDMDataKey;
import com.bagri.xdm.domain.XDMDocument;
import com.bagri.xdm.domain.XDMElement;
import com.bagri.xdm.domain.XDMNodeKind;
import com.tangosol.net.BackingMapContext;
import com.tangosol.net.BackingMapManagerContext;
import com.tangosol.util.BinaryEntry;
import com.tangosol.util.Filter;
import com.tangosol.util.extractor.PofExtractor;
import com.tangosol.util.filter.AndFilter;
import com.tangosol.util.filter.EqualsFilter;
import com.tangosol.util.filter.InFilter;
//import com.tangosol.util.filter.KeyAssociatedFilter;

public class DocumentManagementServer extends XDMDocumentManagementServer {

    //private static final transient Logger logger = LoggerFactory.getLogger(CoherenceDocumentServer.class);

	@Override
	public Collection<String> buildDocument(Set<Long> docIds, String template,
			Map<String, String> params) {

		logger.trace("buildDocument.enter; docIds: {}", docIds.size());
		long stamp = System.currentTimeMillis();

		// TODO: get docTYpe..
		int docType = 0;
		BackingMapManagerContext ctx = null;

        Collection<String> result = new ArrayList<String>(docIds.size());
		if (ctx != null && docIds.size() > 0) {
			BackingMapContext bmc = ctx.getBackingMapContext(CN_XDM_ELEMENT);

			for (long docId: docIds) {
				StringBuilder buff = new StringBuilder(template);
				for (Map.Entry<String, String> param: params.entrySet()) {
					String key = param.getKey();
					String str = buildElement(bmc, param.getValue(), docId, docType);
					while (true) {
						int idx = buff.indexOf(key);
				        //logger.trace("buildDocument; searching key: {} in buff: {}; result: {}", new Object[] {key, buff, idx});
						if (idx < 0) break;
						buff.replace(idx, idx + key.length(), str);
				        //logger.trace("buildDocument; replaced key: {} with {}", key, str);
					}
				}
				result.add(buff.toString());
			}
		}

		stamp = System.currentTimeMillis() - stamp;
        logger.trace("buildDocument.exit; time taken: {}; returning: {}", stamp, result.size());
        return result;
    }

    private String buildElement(BackingMapContext bmc, String path, long docId, int docType) {

    	Set<Integer> parts = mDictionary.getPathElements(docType, path);
   		Filter f = new AndFilter(
   			new EqualsFilter(new PofExtractor(Long.TYPE, 2), docId),
			new InFilter(new PofExtractor(Integer.TYPE, 4), parts));

        Set<Map.Entry> xdEntries = QueryHelper.INSTANCE.query(bmc, f, true, false, null);
       	return null; //buildXml(xdEntries);
    }

	@Override
	public XDMDocument createDocument(Entry<Long, XDMDocument> entry, String uri, String xml) {
		logger.trace("createDocument.enter; entry: {}", entry);
		BinaryEntry docEntry = (BinaryEntry) entry;
		if (docEntry.isPresent()) {
			throw new IllegalStateException("Document Entry with id " + entry.getKey() + " already exists");
		}

		Long id = entry.getKey();
		List<XDMElement> data = null; //parseDocument(xml, id);
		XDMElement root = null; //getDocumentRoot(data);

		if (root != null) {
			int docType = 0; //mDictionary.translateDocumentType(root.getPath());

		    BackingMapManagerContext ctx = docEntry.getContext();
			for (Iterator<XDMElement> itr = data.iterator(); itr.hasNext();) {
				createElement(ctx, itr.next(), docType);
			}

			String user = "system"; // get user from context!
			XDMDocument doc = new XDMDocument(id, uri, docType, user); // + version, createdAt, encoding
			docEntry.setValue(doc, false);

			mDictionary.normalizeDocumentType(docType);
			logger.trace("createDocument.exit; returning: {}", doc);
			return doc;
		} else {
			logger.warn("createDocument.exit; the document is not valid as it has no root element, returning null");
			return null;
		}
	}

	private Object createElement(BackingMapManagerContext ctx, XDMElement xdm, int docType) {

		//XDMDataKey xdk = mFactory.newXDMDataKey(xdm.getElementId(), 0L); //xdm.getDocumentId());
		XDMDataKey xdk = mFactory.newXDMDataKey(0L, 0); //xdm.getDocumentId());
		Object xdk1 = ctx.getKeyToInternalConverter().convert(xdk);

		BackingMapContext xdmCtx = ctx.getBackingMapContext(CN_XDM_ELEMENT);
		BinaryEntry xdmEntry = (BinaryEntry) xdmCtx.getBackingMapEntry(xdk1);
		if (xdmEntry == null) {
			throw new IllegalStateException("XDM entry is null; means we're on the wrong partition! key: " + xdk);
		}

		if (xdmEntry.isPresent()) {
			throw new IllegalStateException("XDM Entry with id " + xdmEntry.getKey() + " already exists");
		}
		//xdm.setPathId(mDictionary.translatePath(docType, xdm.getPath(), XDMNodeKind.fromPath(xdm.getPath())));
		xdmEntry.setValue(xdm, false);
/*
		if (xdm.getPath() != null) {
			PathDocumentKey pdk = new PathDocumentKey(xdm.getPath(), xdm.getDocumentId());
			Object pdk1 = ctx.getKeyToInternalConverter().convert(pdk);

			BackingMapContext pdCtx = ctx.getBackingMapContext(CN_XDM_PATH_INDEX);
			BinaryEntry pdEntry = (BinaryEntry) pdCtx.getBackingMapEntry(pdk1);
			if (pdEntry == null) {
				throw new IllegalStateException("Path entry is null; means we're on the wrong partition! key: " + pdk);
			}

			XDMIndex<Boolean> idx;
			if (pdEntry.isPresent()) {
				idx = (XDMIndex<Boolean>) pdEntry.getValue();
				idx.addIndex(xdm.getDocumentId(), xdm.getDataId());
			} else {
				idx = new XDMIndex<Boolean>(xdm.getPath(), true, xdm.getDocumentId(), xdm.getDataId());
			}
			pdEntry.setValue(idx, false);
		}
*/
		//logger.trace("create.exit; store entry: {}", xdmEntry);
		return xdmEntry.getKey(); //xdm.getId();
	}

	@Override
	public void deleteDocument(Entry<Long, XDMDocument> entry) {
		logger.trace("deleteDocument.enter; entry: {}", entry);
		BinaryEntry docEntry = (BinaryEntry) entry;
		if (!docEntry.isPresent()) {
			throw new IllegalStateException("Document Entry with id " + entry.getKey() + " not found");
		}

		Long id = entry.getKey();
		BackingMapManagerContext ctx = docEntry.getContext();
		BackingMapContext xdmCtx = ctx.getBackingMapContext(CN_XDM_ELEMENT);

   		Filter f = new EqualsFilter(new PofExtractor(Long.class, 2), id);
        Set<Map.Entry> xdEntries = QueryHelper.INSTANCE.query(xdmCtx, f, true, false, null);
		logger.trace("deleteDocument; removing {} entries for docId: {}", xdEntries.size(), id);
        for (Map.Entry xdEntry : xdEntries) {
        	//((BinaryEntry) xdEntry).remove(false);
        	Object xdKey = ((BinaryEntry) xdEntry).getBinaryKey();
    		//logger.trace("process; removing entry for key: {}", xdKey);
        	xdmCtx.getBackingMap().remove(xdKey);
        	//xdEntry.setValue(null);
    		//logger.trace("process; removing {} entries for docId: {}", xdEntry.size(), id);
        }

        docEntry.remove(false);
		logger.trace("deleteDocument.exit; removed: {}", true);
	}

	@Override
	public XDMDocument updateDocument(Entry<Long, XDMDocument> entry, boolean newVersion, String xml) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public XDMDocument getDocument(long docId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long getDocumentId(String uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getDocumentAsString(long docId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public XDMDocument storeDocument(String xml) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public XDMDocument storeDocument(long docId, String uri, String xml) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void removeDocument(long docId) {
		// TODO Auto-generated method stub

	}

	@Override
	public void close() {
		// TODO Auto-generated method stub

	}

	@Override
	public Collection<Long> getDocumentIDs(ExpressionContainer query) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Collection<String> getDocumentURIs(ExpressionContainer query) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Collection<String> getXML(ExpressionContainer query, String template, Map params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object executeXCommand(String command, Map bindings, Properties props) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object executeXQuery(String query, Map bindings, Properties props) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Set<Long> queryPathKeys(Set<Long> found, PathExpression pex, Object value) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Source getDocumentSource(long arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void putDocumentSource(long arg0, Source arg1) {
		// TODO Auto-generated method stub

	}

}


text:
{
   stringLoading: "Vérification de disponibilité ...",
   stringAvailable: "La ressource est disponible !",
   stringUnAvailable: "La ressource est indisponible",
   errorDataText : "Une erreur s'est produite"
}


text:
from keras import initializers, regularizers, activations, constraints
from keras.engine import Layer, InputSpec
from keras.layers import Reshape, Concatenate, Conv2D, MaxPooling2D, interfaces
from keras import backend as K

class Highway(Layer):
    def __init__(self,
                 init='glorot_uniform',
                 activation=None,
                 weights=None,
                 W_regularizer=None,
                 b_regularizer=None,
                 activity_regularizer=None,
                 W_constraint=None,
                 b_constraint=None,
                 bias=True,
                 input_dim=None,
                 **kwargs):

        self.init = initializers.get(init)
        self.activation = activations.get(activation)

        self.W_regularizer = regularizers.get(W_regularizer)
        self.b_regularizer = regularizers.get(b_regularizer)
        self.activity_regularizer = regularizers.get(activity_regularizer)

        self.W_constraint = constraints.get(W_constraint)
        self.b_constraint = constraints.get(b_constraint)

        self.bias = bias
        self.initial_weights = weights
        self.input_spec = InputSpec(ndim=2)

        self.input_dim = input_dim
        if self.input_dim:
            kwargs['input_shape'] = (self.input_dim,)
        super(Highway, self).__init__(**kwargs)

    def build(self, input_shape):
        input_dim = input_shape[1]
        self.input_spec = InputSpec(dtype=K.floatx(),
                                    shape=(None, input_dim))

        self.W = self.add_weight((input_dim, input_dim),
                                 initializer=self.init,
                                 name='W',
                                 regularizer=self.W_regularizer,
                                 constraint=self.W_constraint)
        self.W_carry = self.add_weight((input_dim, input_dim),
                                       initializer=self.init,
                                       name='W_carry')
        if self.bias:
            self.b = self.add_weight((input_dim,),
                                     initializer='zero',
                                     name='b',
                                     regularizer=self.b_regularizer,
                                     constraint=self.b_constraint)
            self.b_carry = self.add_weight((input_dim,),
                                           initializer='one',
                                           name='b_carry')
        else:
            self.b_carry = None

        if self.initial_weights is not None:
            self.set_weights(self.initial_weights)
            del self.initial_weights
        self.built = True

    def call(self, x):
        y = K.dot(x, self.W_carry)
        if self.bias:
            y += self.b_carry
        transform_weight = activations.sigmoid(y)
        y = K.dot(x, self.W)
        if self.bias:
            y += self.b
        act = self.activation(y)
        act *= transform_weight
        output = act + (1 - transform_weight) * x
        return output

    def get_config(self):
        config = {'init': initializers.serialize(self.init),
                  'activation': activations.serialize(self.activation),
                  'W_regularizer': regularizers.serialize(self.W_regularizer),
                  'b_regularizer': regularizers.serialize(self.b_regularizer),
                  'activity_regularizer': regularizers.serialize(self.activity_regularizer),
                  'W_constraint': constraints.serialize(self.W_constraint),
                  'b_constraint': constraints.serialize(self.b_constraint),
                  'bias': self.bias,
                  'input_dim': self.input_dim}
        base_config = super(Highway, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

def dot_product(x, kernel):
    """
    Wrapper for dot product operation, in order to be compatible with both
    Theano and Tensorflow
    Args:
        x (): input
        kernel (): weights
    Returns:
    """
    if K.backend() == 'tensorflow':
        return K.squeeze(K.dot(x, K.expand_dims(kernel)), axis=-1)
    else:
        return K.dot(x, kernel)

class AttentionWithContext(Layer):
    """
        Attention operation, with a context/query vector, for temporal data.
        Supports Masking.
        Follows the work of Yang et al. [https://www.cs.cmu.edu/~diyiy/docs/naacl16.pdf]
        "Hierarchical Attention Networks for Document Classification"
        by using a context vector to assist the attention
        # Input shape
            3D tensor with shape: `(samples, steps, features)`.
        # Output shape
            2D tensor with shape: `(samples, features)`.
        :param kwargs:
        Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.
        The dimensions are inferred based on the output shape of the RNN.
        Example:
            model.add(LSTM(64, return_sequences=True))
            model.add(AttentionWithContext())
        """

    def __init__(self,
                 W_regularizer=None, u_regularizer=None, b_regularizer=None,
                 W_constraint=None, u_constraint=None, b_constraint=None,
                 W_dropout=0., u_dropout=0., bias=True, **kwargs):

        self.supports_masking = True
        self.W_init = initializers.get('orthogonal')
        self.u_init = initializers.get('glorot_uniform')

        self.W_regularizer = regularizers.get(W_regularizer)
        self.u_regularizer = regularizers.get(u_regularizer)
        self.b_regularizer = regularizers.get(b_regularizer)

        self.W_constraint = constraints.get(W_constraint)
        self.u_constraint = constraints.get(u_constraint)
        self.b_constraint = constraints.get(b_constraint)

        self.W_dropout = min(1., max(0., W_dropout))
        self.u_dropout = min(1., max(0., u_dropout))

        self.bias = bias

        super(AttentionWithContext, self).__init__(**kwargs)

    def build(self, input_shape):
        assert len(input_shape) == 3

        self.W = self.add_weight((input_shape[-1], input_shape[-1]),
                                 initializer=self.W_init,
                                 name='{}_W'.format(self.name),
                                 regularizer=self.W_regularizer,
                                 constraint=self.W_constraint)
        if self.bias:
            self.b = self.add_weight((input_shape[-1],),
                                     initializer='zero',
                                     name='{}_b'.format(self.name),
                                     regularizer=self.b_regularizer,
                                     constraint=self.b_constraint)

        self.u = self.add_weight((input_shape[-1],),
                                 initializer=self.u_init,
                                 name='{}_u'.format(self.name),
                                 regularizer=self.u_regularizer,
                                 constraint=self.u_constraint)

        super(AttentionWithContext, self).build(input_shape)

    def compute_mask(self, input, input_mask=None):
        # do not pass the mask to the next layers
        return None

    def call(self, x, mask=None):
        if 0. < self.W_dropout < 1.:
            def dropped_inputs():
                return K.dropout(x, self.W_dropout)
            x_dp = K.in_train_phase(dropped_inputs, x)
        else:
            x_dp = x
        uit = dot_product(x_dp, self.W)
        if self.bias:
            uit += self.b
        uit = K.tanh(uit)

        if 0. < self.u_dropout < 1.:
            def dropped_inputs():
                return K.dropout(uit, self.u_dropout)
            u_dp = K.in_train_phase(dropped_inputs, uit)
        else:
            u_dp = uit
        ait = dot_product(u_dp, self.u)
        a = K.exp(ait)
        a = K.expand_dims(a)
        a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())
        weighted_input = x * a
        output = K.sum(weighted_input, axis=1)

        return output

    def compute_output_shape(self, input_shape):
        return input_shape[0], input_shape[-1]

    def get_config(self):
        config = {'W_regularizer': regularizers.serialize(self.W_regularizer),
                  'u_regularizer': regularizers.serialize(self.u_regularizer),
                  'b_regularizer': regularizers.serialize(self.b_regularizer),
                  'W_constraint': constraints.serialize(self.W_constraint),
                  'u_constraint': constraints.serialize(self.u_constraint),
                  'b_constraint': constraints.serialize(self.b_constraint),
                  'W_dropout': self.W_dropout,
                  'u_dropout': self.u_dropout,
                  'bias': self.bias}
        base_config = super(AttentionWithContext, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

def CNN(seq_length, length, input_size, feature_maps, kernels, x):
    concat_input = []
    for feature_map, kernel in zip(feature_maps, kernels):
        reduced_l = length - kernel + 1
        conv = Conv2D(feature_map, (1, kernel), activation='tanh', data_format="channels_last")(x)
        maxp = MaxPooling2D((1, reduced_l), data_format="channels_last")(conv)
        concat_input.append(maxp)
    con = Concatenate()(concat_input)
    con = Reshape((seq_length, sum(feature_maps)))(con)
    return con


text:
Ahora que ya sabemos los conceptos básicos de Vue, vamos a aprender a crear aplicaciones web más profesionales.

Hasta ahora vimos que implementar el framework es muy fácil, simplemente tenemos que agregar la referencia y crear la instancia escribiendo `new Vue({})`. El asunto es que en la mayoría de los casos vamos a querer hacer aplicaciones mas complejas en lugar de prototipos o *landing pages*.

Recordemos que Vue esta basado en un concepto progresivo y que a medida que nuestra aplicación incremente la complejidad podemos acompañar ese proceso con herramientas o librerías que nos permitan trabajar de manera más óptima.

## *Single File Components* (`.vue`)

Lo primero que vamos aprender ahora es la *magia* de los archivos `.vue` (SFC: *Single File Components*). Esto nos permite crear componentes en archivos (1 componente = 1 archivo) y escribir todo el código, vista y estilos que pertenece a ese componente.

La estructura de un archivo `.vue` es la siguente:

![vue-file](../img/sfc.png)

Como ven es muy intuitivo, usamos el tag `template` para HTML, `script` para JS y `style` para CSS.
Las ventajas de los archivos `.vue` son las siguientes:

1. Facilitamos el manejo de código HTML en cada componente ya que no usamos mas una variable `string`.
2. Podemos agregar estilos (CSS) específicos para nuestros componentes. Incluso, usando el atributo `scoped` podemos hacer que sos estilos apliquen unicamente al componente en cuestion.
3. Nos permiten integrar *pre procesadores* como [Bebel](http://babeljs.io/), [Sass](http://sass-lang.com/) y [Pug](https://pugjs.org/api/getting-started.html).

Si bien los archivos `.vue` son geniales para los desarrolladores, tenemos un pequeño problema. El browser no soporta este tipo de archivos 😅

Para poder utilizarlos vamos a tener que incorporar algún sistema de *build*. Esto quiere decir que nosotros como programadores vamos a codear nuestra aplicación en componentes dentro de archivos `.vue` pero con la ayuda de herramientas como [Webpack](https://webpack.github.io/) o [Rollup](https://rollupjs.org/), nuestro código se va a compilar a archivos `.js` que el browser puede interpretar.

En general este proceso de compilación tiende a ser un poco mas complejo y esta fuera del alcance de este Workshop.

Por suerte para nosotros, vamos a hacer de este proceso una **caja negra**, ya que vamos confiar en el ecosistema de Vue para configurar e iniciar nuestro proyectos. 💪🏼😎.

[⏪](https://github.com/ianaya89/workshop-vuejs/blob/master/ex/04.md)  [⏩](https://github.com/ianaya89/workshop-vuejs/blob/master/ex/06.md)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>CSS buttons | Upstage Component</title>
    <link rel="stylesheet" href="assets/assemble.css">
    <link rel="stylesheet" href="assets/sections.css">
    <link rel="stylesheet" href="assets/github.css">
    <link rel="stylesheet" href="assets/docs.css">

          UPSTAGE
          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="nav-collapse">

          </button>

Component

                GitHub Repo

                Issues

CSS buttons

Small Buttons

            Small Button
            Small Button
            Small Button
            Small Button
            Small Button
            Small Button
            Small Button

Standard Buttons

            Button
            Button
            Button
            Button
            Button
            Button
            Button

Large Buttons

            Large Button
            Large Button
            Large Button
            Large Button
            Large Button
            Large Button
            Large Button

Jumbo Buttons

            Jumbo Button
            Jumbo Button
            Jumbo Button
            Jumbo Button
            Jumbo Button
            Jumbo Button
            Jumbo Button


text:
cConfiguration = inherit(cSingleton)

--[[

]]

-- ///////////////////////////////
-- ///// checkFile  		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:checkFile()
    self.xml    = xmlLoadFile(self.m_sFileName);

    if not(self.xml) then
        self.xml    = xmlCreateFile(self.m_sFileName, "config");

        if(self.m_bInsertJustOnNoneExists == true) then
            for index, val in pairs(self.defaultValues2) do
                self:setConfig(index, val)
            end
            if(self.xtraValues) then
                for index, val in pairs(self.xtraValues) do
                    self:setConfig(index, val)
                end
            end
        end
    end

    xmlSaveFile(self.xml);
end

-- ///////////////////////////////
-- ///// setConfig  		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:setConfig(sConfig, sValue)
    if not(self.xml) then
        outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
        return false;
    end

    local node      = xmlFindChild(self.xml, sConfig, 0);
    if not(node) then
        node    = xmlCreateChild(self.xml, sConfig);
    end
    local sucess    = xmlNodeSetValue(node, tostring(sValue));
    xmlSaveFile(self.xml)

    if(sucess) then
        return sValue;
    end

    return false;
end

-- ///////////////////////////////
-- ///// getConfig  		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:getConfig(sConfig)
    if not(self.xml) then
        outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
        return false;
    end
    local node  = xmlFindChild(self.xml, sConfig, 0);

    if not(node) then
        node    = xmlCreateChild(self.xml, sConfig);
    end
    local value = xmlNodeGetValue(node);

    if not(value) or (string.len(value) < 1) then
        if(self.defaultValues[sConfig]) then
            value = self.defaultValues[sConfig];
            self:setConfig(sConfig, value);
            outputDebugString("[CONFIG] Config "..sConfig.." not found, using default ("..tostring(value)..")");
            return value
        else
            return false;
        end
    else
        return value
    end
    return false;
end

-- ///////////////////////////////
-- ///// removeConfig  		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:removeConfig(sConfig)
    if not(self.xml) then
        outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
        return false;
    end
    local node  = xmlFindChild(self.xml, sConfig, 0);

    if(node) then
        local sucess = xmlDestroyNode(node)
        xmlSaveFile(self.xml)
        return sucess
    end
    return false;
end

-- ///////////////////////////////
-- ///// getAllConfig  		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:getAllConfig()
    if not(self.xml) then
        outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
        return false;
    end

    local childs = xmlNodeGetChildren(self.xml);

    local tbl       = {}

    for index, _ in ipairs(childs) do
        tbl[xmlNodeGetName(childs[index])] = xmlNodeGetValue(childs[index])
    end

    return tbl
end

-- ///////////////////////////////
-- ///// loadCoreConfig 	//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:loadCoreConfig()
    -- FPS --

    local fps       = tonumber(self:getConfig("fps"));
    setFPSLimit(fps);

    -- CURSOR --
    local cursor    = self:getConfig("cursorbind");

    local function bindDat(sKey)
        bindKey(sKey, "both", function( key, state)
            if	not (cursorOverride) then
                showCursor(state == "down")
            end
        end)
    end

    bindDat(cursor)
    addCommandHandler("bindcursor", function(cmd, key) bindDat(key) end)

    -- DEV MODE --
    local devmode   = toBoolean(self:getConfig("development"))
    setDevelopmentMode(devmode)

    -- HEAT HAZE --
    local heatHaze  = tonumber(self:getConfig("heathaze"));
    if not(heatHaze) then
        resetHeatHaze()
    else
        setHeatHaze(heatHaze)
    end

    -- INTERIOR SOUNDS --
    local intSound  = toBoolean(self:getConfig("interior_sounds"))
    setInteriorSoundsEnabled(intSound);

    -- Occlusions --

    local occlusions    = toBoolean(self:getConfig("occlusions"))
    setOcclusionsEnabled(occlusions);

    -- Moon size --
    local moon_size     = tonumber(self:getConfig("moon_size"))
    if(moon_size) then
        setMoonSize(moon_size)
    end

    -- Hotsound --
    hitsoundEnabled     = toBoolean(self:getConfig("hitsound_enabled"))

    addCommandHandler("hitsound", function()
        hitsoundEnabled = not(hitsoundEnabled)

        if(hitsoundEnabled) then
            outputChatBox("Der Hitsound wurde angeschaltet!", 0, 255, 0)
        else
            outputChatBox("Der Hitsound wurde ausgeschaltet!", 0, 255, 0)
        end

        self:setConfig("hitsound_enabled", tostring(hitsoundEnabled));
    end)

    addCommandHandler("changelog", function()
        local file      = File("res/txt/changelog.txt")
        local content   = file:read(file:getSize())
        for index, row in ipairs(split(content, "\n")) do
            outputConsole(row);
        end
        file:close()
    end)

    if(toboolean(self:getConfig("load_world_textures")) == false) then
        local _engineApplyShaderToWorldTexture        = engineApplyShaderToWorldTexture

        function engineApplyShaderToWorldTexture(...)
            return false
        end
    end
end

-- ///////////////////////////////
-- ///// loadBasicConfig	//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:loadBasicConfig()
    for config, default in pairs(self.defaultValues) do
        local dat = self:getConfig(config);
        setElementData(localPlayer, config, dat);
    end
end

-- ///////////////////////////////
-- ///// loadCommands 		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:loadCommands()
    addCommandHandler("scrambleword", function(cmd, ...)
        local s = scrambleWord((table.concat({...}, " ") or "hello"))
        outputConsole("Wort: "..s)
        setClipboard(s)
    end)
end

-- ///////////////////////////////
-- ///// Constructor 		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function cConfiguration:constructor(sFileName, sDefaultValues, insertOnNonExists)
    -- Klassenvariablen --

    self.defaultValues =
    {
        ["fps"]                     = "60",
        ["cursorbind"]              = "m",
        ["moon_size"]               = "0",
        ["heathaze"]                = "reset",
        ["interior_sounds"]         = "true",
        ["occlusions"]              = "false",
        ["development"]             = "true",
        ["upload_blitzer_images"]   = "true",
        ["log_console"]             = "false",
        ["nametags_enabled"]        = "true",
        ["hud_enabled"]             = "true",
        ["render_infotext"]         = "true",
        ["render_3dtext"]           = "true",
        ["save_password"]           = "false",
        ["saved_password"]          = "-",
        ["hitsound_enabled"]        = "false",
        ["ooc_chat"]                = "true",
        ["popsound"]                = "res/sounds/poke.ogg",
        ["hide_scoreboard_avatar"]  = "false",
        ["lowrammode"]              = "false",
        ["log_actions"]             = "true",
        ["load_world_textures"]     = "true",
        ["log_debug"]               = "false",

    }

    if not(sFileName) then
        sFileName = "config.xml";
    end

    if(sDefaultValues) then
        self.defaultValues  = {}
        self.defaultValues2 = sDefaultValues;
    end

    self.m_sFileName                = sFileName;
    self.m_bInsertJustOnNoneExists = insertOnNonExists

    -- Funktionen --
    self:checkFile()

    if(sFileName == "config.xml") then
        self:loadCommands();
        self:loadCoreConfig()
        self:loadBasicConfig();
    end

    addEventHandler("onClientResourceStop", getResourceRootElement(getThisResource()), function()
        if(self.xml) then
            xmlSaveFile(self.xml)
            xmlUnloadFile(self.xml)
        end
    end)
    -- Events --
end

-- EVENT HANDLER --


text:
<?php
$lang['sales_giftcard_number'] = 'Номер подарочных карт';
$lang['sales_giftcard'] = 'Подарочная карта';
$lang['sales_register'] = 'Продажи журнала';
$lang['sales_mode'] = 'режим журнала';
$lang['sales_new_item'] = 'Новый Товар';
$lang['sales_item_name'] = 'Название товара';
$lang['sales_item_number'] = 'Номер товара';
$lang['sales_new_customer'] = 'Новый клиент';
$lang['sales_customer'] = 'клиент';
$lang['sales_no_items_in_cart'] = 'Там нет товаров в корзине';
$lang['sales_total'] = 'сумма';
$lang['sales_tax_percent'] = 'Налоговые %';
$lang['sales_price'] = 'цена';
$lang['sales_quantity'] = 'Кол-во.';
$lang['sales_discount'] = 'скидка %';
$lang['sales_edit'] = 'редактировать';
$lang['sales_payment'] = 'Вид оплаты';
$lang['sales_edit_item'] = 'Редактировать Товар';
$lang['sales_find_or_scan_item'] = 'Найти/Сканировать Товара';
$lang['sales_find_or_scan_item_or_receipt'] = 'Найти/Сканировать Товара ИЛИ Квитанция';
$lang['sales_select_customer'] = 'Выберите клиента (необязательно)';
$lang['sales_start_typing_item_name'] = 'Начните печатать название товара или сканировайте штрих-кода...';
$lang['sales_start_typing_customer_name'] = 'Начните печатать название клиента...';
$lang['sales_sub_total'] = 'промежуточный итог';
$lang['sales_tax'] = 'налог';
$lang['sales_comment'] = 'комментировать';
$lang['sales_unable_to_add_item'] = 'Невозможно добавить товар продажи';
$lang['sales_sale_for_customer'] = 'Клиент:';
$lang['sales_remove_customer'] = 'Удалите клиентов';
$lang['sales_error_editing_item'] = 'Ошибка редактирования товара';
$lang['sales_complete_sale'] = 'Завершить продажу';
$lang['sales_cancel_sale'] = 'Отменить продажу';
$lang['sales_add_payment'] = 'Добавить оплаты';
$lang['sales_receipt'] = 'товарный чек';
$lang['sales_id'] = 'Номер Продажы';
$lang['sales_sale'] = 'Продажа';
$lang['sales_return'] = 'возвращать';
$lang['sales_confirm_finish_sale'] = 'Вы уверены, что хотите заверщить эту продажу? Не может быть отменено.';
$lang['sales_confirm_cancel_sale'] = 'Вы уверены, что хотите удалить эту продажу? Все детали будут очищены.';
$lang['sales_cash'] = 'наличные деньги';
$lang['sales_check'] = 'банковский чек';
$lang['sales_debit'] = 'Дебетовая карта';
$lang['sales_credit'] = 'кредитная карта';
$lang['sales_giftcard'] = 'Подарочная карта';
$lang['sales_amount_tendered'] = 'предложенная сумма';
$lang['sales_change_due'] = 'сдача должное';
$lang['sales_payment_not_cover_total'] = 'оплачиваемая сумма недостаточно';
$lang['sales_transaction_failed'] = 'Транзакция не удалось';
$lang['sales_must_enter_numeric'] = 'числовое значение необходимое для предложенная сумма';
$lang['sales_must_enter_numeric_giftcard'] = 'числовое значение необходимое для число подарочную карту';
$lang['sales_serial'] = 'серийный номер';
$lang['sales_description_abbrv'] = 'описание';
$lang['sales_item_out_of_stock'] = 'Товар распродано';
$lang['sales_item_insufficient_of_stock'] = 'Товар недостаточно на складе';
$lang['sales_quantity_less_than_zero'] = 'Внимание Желаемое количество является недостаточным. Вы все еще можете обрабатывать продажи, но проверить ваш инвентарь';
$lang['sales_successfully_updated'] = 'Продажа успешно обновлен';
$lang['sales_unsuccessfully_updated'] = 'Продажа безуспешно обновлен';
$lang['sales_edit_sale'] = 'Редактировать продажи';
$lang['sales_employee'] = 'сотрудник';
$lang['sales_successfully_deleted'] = 'продажи успешно удален';
$lang['sales_unsuccessfully_deleted'] = 'продажи безуспешно удален';
$lang['sales_delete_entire_sale'] = 'Удалить всего продажи';
$lang['sales_delete_confirmation'] = 'Вы уверены, что хотите удалить эту продажу, это действие не может быть отменено';
$lang['sales_delete_successful'] = 'Вы успешно удален продаже';
$lang['sales_delete_unsuccessful'] = 'Вы безуспешно удален продаже';
$lang['sales_suspend_sale'] = 'Приостановить продажи';
$lang['sales_confirm_suspend_sale'] = 'Вы уверены, что хотите приостановить эту продажу?';
$lang['sales_suspended_sales'] = 'приостановила продажи';
$lang['sales_suspended_sale_id'] = 'приостановила продажи ID';
$lang['sales_date'] = 'Число';
$lang['sales_comments'] = 'Комментарии';
$lang['sales_unsuspend_and_delete'] = 'Разблокировать и удалить';
$lang['sales_unsuspend'] = 'Разблокировать';
$lang['sales_successfully_suspended_sale'] = 'Ваши продажи успешно приостановлена';
$lang['sales_email_receipt'] = 'послать квитанция по E-Mail';
$lang['sales_discount_short']='%';
$lang["sales_discount_included"]='% Discount';
$lang['sales_sale_time']='Time';
$lang['sales_payments_total'] = 'Payments Total';
$lang['sales_amount_due'] = 'Amount Due';
$lang['sales_payment_type'] = "тип";
$lang['sales_payment_amount'] = "количество";
$lang['sales_basic_information'] = "информацию о билетах";
?>


text:
*************
Courses Notes
*************

Notes for chosen courses during studying at ISchool.

.. toctree::

    info203/index
    info205/index


text:
    && defined BOOST_BCB_PARTIAL_SPECIALIZATION_BUG
// BCB (up to 5.64) has the following bug:
//   If there is a member function/operator template of the form
//     template<class Expr> mfunc( Expr expr ) ;
//   some calls are resolved to this even if there are other better matches.
//   The effect of this bug is that calls to converting ctors and assignments
//   are incorrectly sink to this general catch-all member function template as shown above.
# define BOOST_OPTIONAL_WEAK_OVERLOAD_RESOLUTION
#endif

#if !defined(BOOST_NO_MAY_ALIAS)
// GCC since 3.3 and some other compilers have may_alias attribute that helps to alleviate
// optimizer issues with regard to violation of the strict aliasing rules. The optional< T >
// storage type is marked with this attribute in order to let the compiler know that it will
// alias objects of type T and silence compilation warnings.
# define BOOST_OPTIONAL_DETAIL_USE_ATTRIBUTE_MAY_ALIAS
#endif

#if (defined(_MSC_VER) && _MSC_VER <= 1800)
// on MSCV 2013 and earlier an unwanted temporary is created when you assign from
// a const lvalue of integral type. Thus we bind not to the original address but
// to a temporary.
# define BOOST_OPTIONAL_CONFIG_NO_PROPER_ASSIGN_FROM_CONST_INT
#endif

#if (defined __GNUC__) && (!defined BOOST_INTEL_CXX_VERSION) && (!defined __clang__)
// On some GCC versions an unwanted temporary is created when you copy-initialize
// from a const lvalue of integral type. Thus we bind not to the original address but
// to a temporary.

# if (__GNUC__ < 4)
#  define BOOST_OPTIONAL_CONFIG_NO_PROPER_CONVERT_FROM_CONST_INT
# endif

# if (__GNUC__ == 4 && __GNUC_MINOR__ <= 5)
#  define BOOST_OPTIONAL_CONFIG_NO_PROPER_CONVERT_FROM_CONST_INT
# endif

# if (__GNUC__ == 5 && __GNUC_MINOR__ < 2)
#  define BOOST_OPTIONAL_CONFIG_NO_PROPER_CONVERT_FROM_CONST_INT
# endif

# if (__GNUC__ == 5 && __GNUC_MINOR__ == 2 && __GNUC_PATCHLEVEL__ == 0)
#  define BOOST_OPTIONAL_CONFIG_NO_PROPER_CONVERT_FROM_CONST_INT
# endif

#endif // defined(__GNUC__)

#if (defined __GNUC__) && (!defined BOOST_NO_CXX11_RVALUE_REFERENCES)
// On some initial rvalue reference implementations GCC does it in a strange way,
// preferring perfect-forwarding constructor to implicit copy constructor.

# if (__GNUC__ == 4 && __GNUC_MINOR__ == 4)
#  define BOOST_OPTIONAL_CONFIG_NO_LEGAL_CONVERT_FROM_REF
# endif

# if (__GNUC__ == 4 && __GNUC_MINOR__ == 5)
#  define BOOST_OPTIONAL_CONFIG_NO_LEGAL_CONVERT_FROM_REF
# endif

#endif // defined(__GNUC__)

#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_DECLTYPE) && !BOOST_WORKAROUND(BOOST_MSVC, < 1800) && !BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500) && !defined(__SUNPRO_CC)
  // this condition is a copy paste from is_constructible.hpp
  // I also disable SUNPRO, as it seems not to support type_traits correctly
#else
# define BOOST_OPTIONAL_DETAIL_NO_IS_CONSTRUCTIBLE_TRAIT
#endif

#if defined __SUNPRO_CC
# define BOOST_OPTIONAL_DETAIL_NO_SFINAE_FRIENDLY_CONSTRUCTORS
#elif (defined _MSC_FULL_VER) && (_MSC_FULL_VER < 190023026)
# define BOOST_OPTIONAL_DETAIL_NO_SFINAE_FRIENDLY_CONSTRUCTORS
#elif defined BOOST_GCC && !defined BOOST_GCC_CXX11
# define BOOST_OPTIONAL_DETAIL_NO_SFINAE_FRIENDLY_CONSTRUCTORS
#elif defined BOOST_GCC_VERSION && BOOST_GCC_VERSION < 40800
# define BOOST_OPTIONAL_DETAIL_NO_SFINAE_FRIENDLY_CONSTRUCTORS
#endif

// Detect suport for defaulting move operations
// (some older compilers implement rvalue references,
// defaulted funcitons but move operations are not special members and cannot be defaulted)

#ifdef BOOST_NO_CXX11_DEFAULTED_FUNCTIONS
# define BOOST_OPTIONAL_DETAIL_NO_DEFAULTED_MOVE_FUNCTIONS
#elif BOOST_WORKAROUND(BOOST_MSVC, < 1900)
# define BOOST_OPTIONAL_DETAIL_NO_DEFAULTED_MOVE_FUNCTIONS
#elif BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40600)
# define BOOST_OPTIONAL_DETAIL_NO_DEFAULTED_MOVE_FUNCTIONS
#endif

#ifdef BOOST_OPTIONAL_CONFIG_NO_DIRECT_STORAGE_SPEC
# define BOOST_OPTIONAL_DETAIL_NO_DIRECT_STORAGE_SPEC
#endif

#endif // header guard


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

package org.chromium.components.browser_ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewParent;

import org.chromium.ui.resources.dynamics.ViewResourceAdapter;
import org.chromium.ui.widget.OptimizedFrameLayout;

/**
 * Extension to FrameLayout that handles tracking the necessary invalidates to generate
 * a corresponding {@link org.chromium.ui.resources.Resource} for use in the browser compositor.
 */
public class ViewResourceFrameLayout extends OptimizedFrameLayout {
    private ViewResourceAdapter mResourceAdapter;
    private Rect mTempRect;

    /**
     * Constructs a ViewResourceFrameLayout.
     * <p>
     * This constructor is used when inflating from XML.
     *
     * @param context The context used to build this view.
     * @param attrs The attributes used to determine how to construct this view.
     */
    public ViewResourceFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mResourceAdapter = createResourceAdapter();
    }

    /**
     * @return A {@link ViewResourceAdapter} instance.  This can be overridden for custom behavior.
     */
    protected ViewResourceAdapter createResourceAdapter() {
        return new ViewResourceAdapter(this);
    }

    /**
     * @return The {@link ViewResourceAdapter} that exposes this {@link View} as a CC resource.
     */
    public ViewResourceAdapter getResourceAdapter() {
        return mResourceAdapter;
    }

    /**
     * @return Whether the control container is ready for capturing snapshots.
     */
    protected boolean isReadyForCapture() {
        return true;
    }

    @SuppressLint("NewApi") // Used on O+, invalidateChildInParent used for previous versions.
    @Override
    public void onDescendantInvalidated(View child, View target) {
        super.onDescendantInvalidated(child, target);
        if (isReadyForCapture()) {
            if (mTempRect == null) mTempRect = new Rect();
            int x = (int) Math.floor(child.getX());
            int y = (int) Math.floor(child.getY());
            mTempRect.set(x, y, x + child.getWidth(), y + child.getHeight());
            mResourceAdapter.invalidate(mTempRect);
        }
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        ViewParent retVal = super.invalidateChildInParent(location, dirty);
        if (isReadyForCapture()) mResourceAdapter.invalidate(dirty);
        return retVal;
    }
}


text:
import React, {
  AppRegistry,
  Component,
  Text,
  StyleSheet,
  View,
  TouchableHighlight,
  Navigator
} from 'react-native';

import Header from './Header';

class Question extends Component {
  nextQuestion() {
    this.props.nextQuestion();
  }

  generateOptions() {
    let context = this;
    const options = [
      "Less than 1 month ago",
      "1 to 3 months ago",
      "3 to 6 months ago ",
      "More than 6 months ago"
    ];

    return options.map((option, index)=>{
      return (
        <TouchableHighlight
          underlayColor={"#ffffff"}
          onPress={context.nextQuestion.bind(context)}
          key={index}
          activeOpacity= {4}
          >
          <View>
            <Text style={styles.option}>
              {option}
            </Text>
          </View>
        </TouchableHighlight>
      );
    });
  }

  render() {
    return (
      <View style={{backgroundColor:'#0C94B9', flex: 1}}>
        <Header navigator={this.props.navigator} value={this.props.header} />
        <View style={styles.container} >
          <Text style={styles.text}>
            {this.props.question}
          </Text>
          {this.generateOptions()}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 11,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#0C94B9',

  },
  option: {
    paddingTop: 20,
    paddingBottom: 20,
    textAlign: 'center',
    backgroundColor: '#35A5C2',
    margin: 5,
    width: 300,
    color: '#fff',
    fontSize: 16
  },
  text: {
    width: 300,
    fontSize: 22,
    textAlign: 'center',
    marginBottom: 15,
    color: '#fff'
  }
});

export default Question


text:
"""
Convert a simulated set of stars into an instcat file for imsim.
"""
__author__ = "Alex Drlica-Wagner"

import os
import copy
from collections import OrderedDict as odict
import numpy as np

FILTER = 'g'
MAG = 'MAG_%s'%FILTER.upper()

MAGLIMS =odict([('u',23),('g',25),('r',25),('i',24.5),('z',24),('y',23)])
FILTERS = odict([('u',0),('g',1),('r',2),('i',3),('z',4),('y',5)])

DEFAULTS = odict([
    ('rightascension', 31.1133844),
    ('declination', -10.0970060),
    ('mjd', 59797.2854090),
    ('altitude', 43.6990272),
    ('azimuth', 73.7707957),
    ('filter', 2),
    ('rotskypos', 69.0922930),
    ('rottelpos', 0.000),
    ('dist2moon', 145.1095257),
    ('moonalt', -11.1383568),
    ('moondec', -18.7702120),
    ('moonphase', 59.6288830),
    ('moonra', 230.9832941),
    ('nsnap', 2),
    ('obshistid', 1),
    ('seed', 1),
    ('seeing', 0.7613760),
    ('rawSeeing', 0.7613760),
    ('FWHMgeom', 1.210734),
    ('FWHMeff', 1.409653),
    ('sunalt', -59.1098785),
    ('vistime', 33.0000000),
    ])

POINT = "object %(ID)i %(RA)12.6f %(DEC)12.6f %({})12.6f starSED/phoSimMLT/lte031-4.5-1.0a+0.4.BT-Settl.spec.gz 0 0 0 0 0 0 point none CCM 0.0 3.1".format(MAG)

SERSIC = "object %(ID)i %(RA)12.6f %(DEC)12.6f %({})12.6f starSED/phoSimMLT/lte031-4.5-1.0a+0.4.BT-Settl.spec.gz 0 0 0 0 0 0 sersic2d %(EXT)12.6f %(EXT)12.6f 0 0.5 none CCM 0.0 3.1".format(MAG)

def set_defaults(kwargs,defaults):
    for k,v in defaults.items():
        kwargs.setdefault(k,v)
    return kwargs

def read_instcat(filename,**kwargs):
    """ Read an instcat file into a numpy.recarray """
    defaults =dict(skip_header=23,usecols=[1,2,3,4],
                   dtype=[('ID',int),('RA',float),('DEC',float),('MAG',float)])
    set_defaults(kwargs,defaults)
    return np.genfromtxt(filename,**kwargs)

class InstCatWriter(object):

    def write_toppart(self, filename, dwarf, force=True):
        if isinstance(filename,basestring):
            if os.path.exists(filename) and not force:
                msg = "File %s already exists"%filename
                raise IOError(msg)
            out = open(filename,'w')
        elif isinstance(filename,file):
            out = filename
        else:
            msg ="Unrecongnized file object"
            raise IOError(msg)

        out.write(self.comment_string())
        out.write(self.header_string(dwarf))
        return out

    def write_middlepart(self, filename, dwarf, data, idx, force=True):
        if isinstance(filename,basestring):
            if os.path.exists(filename) and not force:
                msg = "File %s already exists"%filename
                raise IOError(msg)
            out = open(filename,'a')
        elif isinstance(filename,file):
            out = filename
        else:
            msg ="Unrecongnized file object"
            raise IOError(msg)
        out.write(self.unresolved_string(dwarf,data, idx))

        return out

    def write_endpart(self, filename, dwarf, data, force=True):
        if isinstance(filename,basestring):
            if os.path.exists(filename) and not force:
                msg = "File %s already exists"%filename
                raise IOError(msg)
            out = open(filename,'a')
        elif isinstance(filename,file):
            out = filename
        else:
            msg ="Unrecongnized file object"
            raise IOError(msg)
        out.write(self.resolved_string(dwarf,data))
        out.write('\n')
        return out

    def comment_string(self,comment=None):
        if comment is None: comment = "instcat file written by dsphsim"
        return "# %s \n"%comment

    def header_string(self, dwarf,**kwargs):
        header = self.parse_dwarf(dwarf,**kwargs)
        return "\n".join(["%s %s"%(k,v) for k,v in header.items()])+'\n'

    def parse_dwarf(self, dwarf, **kwargs):
        header = set_defaults(odict(),DEFAULTS)
        header.update(kwargs)
        header['rightascension'] = dwarf.lon
        header['declination'] = dwarf.lat
        header['filter'] = FILTERS[FILTER]
        return header

    def resolved_string(self, dwarf, data, **kwargs):
        sel = (data[MAG] <= MAGLIMS[FILTER])
        return '\n'.join(np.char.mod([POINT],data[sel]))

    def unresolved_string(self, dwarf, data, idx, **kwargs):
        sel = (data[MAG] > MAGLIMS[FILTER])
        params = dict(ID=idx,
                      RA=dwarf.lon,
                      DEC=dwarf.lat,
                      EXT=dwarf.extension*3600 / 1.68, # arcsec
        )
        params[MAG] = self.cumulative_magnitude(data[sel])
        return SERSIC%(params) + '\n'

    def cumulative_magnitude(self,data):
        return -2.5 * np.log10(np.sum(10**(data[MAG]/-2.5)))


text:
package com.swfarm.biz.ebay.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.ebay.bo.EbayAccount;
import com.swfarm.biz.ebay.bo.EbayDecisionEnum;
import com.swfarm.biz.ebay.bo.EbayPostOrderReturn;
import com.swfarm.biz.ebay.srv.EbayService;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.pub.framework.Const;

public class DeclinePostOrderReturnController extends AbstractController {

	private EbayService ebayService;

	public void setEbayService(EbayService ebayService) {
		this.ebayService = ebayService;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		String returnId = req.getParameter("returnId");
		String accountNumber = req.getParameter("accountNumber");
		req.setAttribute("pages", "ebaypostorderreturnsdecline");
		try {
			EbayAccount ebayAccount = ebayService
					.findEbayAccountByName(accountNumber);
			String paramText = req.getParameter("comments");
			JSONObject content = new JSONObject();
			content.put("content", paramText);
			JSONObject params = new JSONObject();
			params.put("decision", EbayDecisionEnum.DECLINE.name());
			params.put("content", content);
			if (StringUtils.isNotEmpty(returnId) && ebayAccount != null) {
				String state = ebayService.processReturnRequestDecide(returnId,
						ebayAccount, params.toString());
				logger.warn("EbayDeclinReturnResponse    states [  " + state
						+ "   ]");
			}
			User user = (User) req.getSession().getAttribute(Const.CREDENTIAL);
			EbayPostOrderReturn ebayPostOrderReturn = ebayService
					.findEbayPostOrderReturnByReturnId(returnId);
			ebayPostOrderReturn.setReplyUsername(user.getChineseName());
			ebayPostOrderReturn.setReplyDate(new Date());
			ebayPostOrderReturn.setIsReplied(true);
			this.ebayService.saveEbayPostOrderReturn(ebayPostOrderReturn);

		} catch (Exception e) {
			logger.warn("DeclinePostOrderReturn returnId[]" +returnId);
		} finally {
			return new ModelAndView("forward:/ebay/ebaypostorderreturndetail.shtml");
		}

	}

}