text:
@implementation PendenciasCardSectionBuilder

-(instancetype)initWithSectionDelegate:(id<CardSectionDelegate>) cardSectionDelegate {
    self = [super init];
    if(self) {
        self.delegate = cardSectionDelegate;
    }
    return self;
}

-(id<Section>)section {

    CardSectionImpl *section = [[CardSectionImpl alloc] init];

    PendenciasCardSectionCell *pendenciasCardSection = [[PendenciasCardSectionCell alloc] init];

    section.regularSectionCell = pendenciasCardSection;

    return section;
}

@end


text:
#pragma once

#include <libudev.h>

#include <osquery/events.h>
#include <osquery/status.h>

namespace osquery {

enum udev_event_action {
  UDEV_EVENT_ACTION_ADD = 1,
  UDEV_EVENT_ACTION_REMOVE = 2,
  UDEV_EVENT_ACTION_CHANGE = 3,
  UDEV_EVENT_ACTION_UNKNOWN = 4,

  // Custom subscriber-only catch-all for actions.
  UDEV_EVENT_ACTION_ALL = 10,
};

/**
 * @brief Subscriptioning details for UdevEventPublisher events.
 *
 */
struct UdevSubscriptionContext : public SubscriptionContext {
  /// The hardware event action, add/remove/change.
  udev_event_action action;

  /// Restrict to a specific subsystem.
  std::string subsystem;

  /// Restrict to a specific devnode.
  std::string devnode;

  /// Restrict to a specific devtype.
  std::string devtype;

  /// Limit to a specific driver name.
  std::string driver;
};

/**
 * @brief Event details for UdevEventPublisher events.
 */
struct UdevEventContext : public EventContext {
  /// A pointer to the device object, most subscribers will only use device.
  struct udev_device* device{nullptr};

  /// The udev_event_action identifier.
  udev_event_action action;

  /// Action as a string (as given by udev).
  std::string action_string;

  std::string subsystem;
  std::string devnode;
  std::string devtype;
  std::string driver;
};

using UdevEventContextRef = std::shared_ptr<UdevEventContext>;
using UdevSubscriptionContextRef = std::shared_ptr<UdevSubscriptionContext>;

/**
 * @brief A Linux `udev` EventPublisher.
 *
 */
class UdevEventPublisher
    : public EventPublisher<UdevSubscriptionContext, UdevEventContext> {
  DECLARE_PUBLISHER("udev");

 public:
  virtual ~UdevEventPublisher() {
    tearDown();
  }

  Status setUp() override;

  void tearDown() override;

  Status run() override;

  /**
   * @brief Return a string representation of a udev property.
   *
   * @param device the udev device pointer.
   * @param property the udev property identifier string.
   * @return string representation of the property or empty if null.
   */
  static std::string getValue(struct udev_device* device,
                              const std::string& property);

  /**
   * @brief Return a string representation of a udev system attribute.
   *
   * @param device the udev device pointer.
   * @param property the udev system attribute identifier string.
   * @return string representation of the attribute or empty if null.
   */
  static std::string getAttr(struct udev_device* device,
                             const std::string& attr);

 private:
  /// udev handle (socket descriptor contained within).
  struct udev* handle_{nullptr};

  /// udev monitor.
  struct udev_monitor* monitor_{nullptr};

  /// Protection around udev resources.
  Mutex mutex_;

 private:
  /// Check subscription details.
  bool shouldFire(const UdevSubscriptionContextRef& mc,
                  const UdevEventContextRef& ec) const override;

  /// Helper function to create an EventContext using a udev_device pointer.
  UdevEventContextRef createEventContextFrom(struct udev_device* device);
};
}

redpajama_set_name: RedPajamaGithub


text:
const path = require('path');

module.exports = {
  entry: path.resolve(__dirname, 'examples/index.js'),
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
    ]
  },
  resolve: {
    alias: {
      'react-redux-simple-validate': path.resolve(__dirname, 'src/index.js')
    }
  },
  devServer: {
    contentBase: path.join(__dirname, 'examples'),
    compress: true,
    port: 9000,
    hot: true
  }
};


text:
function varargout = horzcat(varargin)

% OVERLOADED: depvar/vertcat
% Prevent concatenation of depvar objects

% ----------------------------------------------------------------------- %
%        Author:    Giovanni Fantuzzi
%                   Department of Aeronautics
%                   Imperial College London
%       Created:    25/04/2016
% Last Modified:    05/05/2016
% ----------------------------------------------------------------------- %

error('Concatenation of depvar objects is not allowed.')


text:
/* temporal_tables/temporal_tables--1.0.2--1.1.0.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION temporal_tables UPDATE TO '1.1.0'" to load this file.\quit

CREATE FUNCTION set_system_time(timestamptz)
RETURNS VOID
AS 'MODULE_PATHNAME'
LANGUAGE C;

COMMENT ON FUNCTION set_system_time(timestamptz) IS 'Set the system time used by versioning triggers to the specific value. NULL reverts back to the default behaviour and uses CURRENT_TIMESTAMP';


text:
package com.edgar.module.sys.web;

import com.edgar.core.mvc.ToQueryExample;
import com.edgar.core.repository.Pagination;
import com.edgar.core.repository.QueryExample;
import com.edgar.core.shiro.AuthHelper;
import com.edgar.core.view.ResponseMessage;
import com.edgar.module.sys.repository.domain.SysRole;
import com.edgar.module.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 角色的rest接口
 *
 * @author Edgar Zhang
 * @version 1.0
 */
@Controller
@RequestMapping("/sys/role")
public class SysRoleResource {
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 保存角色
     *
     * @param sysRole 角色
     * @return 保存成功返回1,失败返回0
     */
    @AuthHelper("Create Role")
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView save(@RequestBody SysRole sysRole) {
        sysRoleService.save(sysRole);
        return ResponseMessage.success();
    }

    /**
     * 更新角色
     *
     * @param roleId  角色ID
     * @param sysRole 角色
     * @return 保存成功,返回1,保存失败,返回0
     */
    @AuthHelper("Update Role")
    @RequestMapping(method = RequestMethod.PUT, value = "/{roleId}")
    @ResponseBody
    public ModelAndView update(@PathVariable("roleId") int roleId, @RequestBody SysRole sysRole) {
        sysRole.setRoleId(roleId);
        sysRoleService.update(sysRole);
        return ResponseMessage.success();
    }

    /**
     * 根据角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色
     */
    @AuthHelper("View Role")
    @RequestMapping(method = RequestMethod.GET, value = "/{roleId}")
    @ResponseBody
    public SysRole get(@PathVariable("roleId") int roleId) {
        return sysRoleService.get(roleId);
    }

    /**
     * 分页查询角色
     *
     * @param page     当前页,默认为1
     * @param pageSize 每页显示数量,默认为10
     * @param example  查询条件
     * @return 角色的分页类
     */
    @AuthHelper("Query Role")
    @RequestMapping(method = RequestMethod.GET, value = "/pagination")
    @ResponseBody
    public Pagination<SysRole> pagination(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @ToQueryExample QueryExample example) {
        return sysRoleService.pagination(example, page, pageSize);
    }

    /**
     * 根据角色ID和时间戳删除角色
     *
     * @param roleId      角色ID
     * @param updatedTime 时间戳
     * @return 如果删除成功,返回1
     */
    @AuthHelper("Delete Role")
    @RequestMapping(method = RequestMethod.DELETE, value = "/{roleId}")
    @ResponseBody
    public ModelAndView delete(@PathVariable("roleId") int roleId,
                               @RequestParam("updatedTime") long updatedTime) {
        sysRoleService.deleteWithLock(roleId, updatedTime);
        return ResponseMessage.success();
    }

}


text:
import {
  AsyncTestCompleter,
  beforeEach,
  ddescribe,
  describe,
  el,
  expect,
  iit,
  inject,
  it,
  xit,
} from 'angular2/test_lib';

import {TestBed} from 'angular2/src/test_lib/test_bed';

import {Injectable, Optional} from 'angular2/di';
import {QueryList} from 'angular2/core';
import {Query, Component, Directive, View} from 'angular2/annotations';

import {NgIf, NgFor} from 'angular2/angular2';
import {ListWrapper} from 'angular2/src/facade/collection';

import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';

export function main() {
  BrowserDomAdapter.makeCurrent();
  describe('Query API', () => {

    describe("querying by directive type", () => {
      it('should contain all direct child directives in the light dom',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '

' +
                          '<needs-query text="2">
' +
                          '

' +
                          '
</needs-query>' +
                          '

';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 view.detectChanges();
                 expect(view.rootNodes).toHaveText('2|3|');

                 async.done();
               });
         }));

      it('should contain all directives in the light dom when descendants flag is used',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '

' +
                          '<needs-query-desc text="2">
' +
                          '

' +
                          '
</needs-query-desc>' +
                          '

';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 view.detectChanges();
                 expect(view.rootNodes).toHaveText('2|3|4|');

                 async.done();
               });
         }));

      it('should contain all directives in the light dom',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '

' +
                          '<needs-query text="2">

</needs-query>' +
                          '

';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 view.detectChanges();
                 expect(view.rootNodes).toHaveText('2|3|');

                 async.done();
               });
         }));

      // TODO(rado): The test below should be using descendants: false,
      // but due to a bug with how injectors are hooked up query considers the
      // directives to be distances 2 instead of direct children.
      it('should reflect dynamically inserted directives',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template =
               '

' +
               '<needs-query-desc text="2">

</needs-query-desc>' +
               '

';

           tb.createView(MyComp, {html: template})
               .then((view) => {

                 view.detectChanges();
                 expect(view.rootNodes).toHaveText('2|');

                 view.context.shouldShow = true;
                 view.detectChanges();
                 expect(view.rootNodes).toHaveText('2|3|');

                 async.done();
               });
         }));

      it('should reflect moved directives',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template =
               '

' +
               '<needs-query-desc text="2">

</needs-query-desc>' +
               '

';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 view.detectChanges();

                 expect(view.rootNodes).toHaveText('2|1d|2d|3d|');

                 view.context.list = ['3d', '2d'];
                 view.detectChanges();
                 view.detectChanges();
                 expect(view.rootNodes).toHaveText('2|3d|2d|');

                 async.done();
               });
         }));
    });

    describe("onChange", () => {
      it('should notify query on change',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '<needs-query-desc #q>' +
                          '

' +
                          '

' +
                          '</needs-query-desc>';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 var q = view.rawView.locals.get("q");
                 view.detectChanges();

                 q.query.onChange(() => {
                   expect(q.query.first.text).toEqual("1");
                   expect(q.query.last.text).toEqual("2");
                   async.done();
                 });

                 view.context.shouldShow = true;
                 view.detectChanges();
               });
         }));

      it("should notify child's query before notifying parent's query",
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '<needs-query-desc #q1>' +
                          '<needs-query-desc #q2>' +
                          '

' +
                          '</needs-query-desc>' +
                          '</needs-query-desc>';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 var q1 = view.rawView.locals.get("q1");
                 var q2 = view.rawView.locals.get("q2");

                 var firedQ2 = false;

                 q2.query.onChange(() => { firedQ2 = true; });
                 q1.query.onChange(() => {
                   expect(firedQ2).toBe(true);
                   async.done();
                 });

                 view.detectChanges();
               });
         }));
    });

    describe("querying by var binding", () => {
      it('should contain all the child directives in the light dom with the given var binding',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template =
               '<needs-query-by-var-binding #q>' +
               '

' +
               '</needs-query-by-var-binding>';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 var q = view.rawView.locals.get("q");

                 view.context.list = ['1d', '2d'];

                 view.detectChanges();

                 expect(q.query.first.text).toEqual("1d");
                 expect(q.query.last.text).toEqual("2d");

                 async.done();
               });
         }));

      it('should support querying by multiple var bindings',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '<needs-query-by-var-bindings #q>' +
                          '

' +
                          '

' +
                          '</needs-query-by-var-bindings>';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 var q = view.rawView.locals.get("q");
                 view.detectChanges();

                 expect(q.query.first.text).toEqual("one");
                 expect(q.query.last.text).toEqual("two");

                 async.done();
               });
         }));

      it('should reflect dynamically inserted directives',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template =
               '<needs-query-by-var-binding #q>' +
               '

' +
               '</needs-query-by-var-binding>';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 var q = view.rawView.locals.get("q");

                 view.context.list = ['1d', '2d'];

                 view.detectChanges();

                 view.context.list = ['2d', '1d'];

                 view.detectChanges();

                 expect(q.query.last.text).toEqual("1d");

                 async.done();
               });
         }));

      it('should contain all the elements in the light dom with the given var binding',
         inject([TestBed, AsyncTestCompleter], (tb: TestBed, async) => {
           var template = '<needs-query-by-var-binding #q>' +
                          '
' +
                          '
{{item}}
' +
                          '
' +
                          '</needs-query-by-var-binding>';

           tb.createView(MyComp, {html: template})
               .then((view) => {
                 var q = view.rawView.locals.get("q");

                 view.context.list = ['1d', '2d'];

                 view.detectChanges();

                 expect(q.query.first.domElement).toHaveText("1d");
                 expect(q.query.last.domElement).toHaveText("2d");

                 async.done();
               });
         }));
    });
  });
}

@Directive({selector: '[text]', properties: ['text'], exportAs: 'textDir'})
@Injectable()
class TextDirective {
  text: string;
  constructor() {}
}

@Component({selector: 'needs-query'})
@View({directives: [NgFor], template: '
{{dir.text}}|
'})
@Injectable()
class NeedsQuery {
  query: QueryList<TextDirective>;
  constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
}

@Component({selector: 'needs-query-desc'})
@View({directives: [NgFor], template: '
{{dir.text}}|
'})
@Injectable()
class NeedsQueryDesc {
  query: QueryList<TextDirective>;
  constructor(@Query(TextDirective, {descendants: true}) query: QueryList<TextDirective>) {
    this.query = query;
  }
}

@Component({selector: 'needs-query-by-var-binding'})
@View({directives: [], template: '<content>'})
@Injectable()
class NeedsQueryByLabel {
  query: QueryList<any>;
  constructor(@Query("textLabel", {descendants: true}) query: QueryList<any>) {
    this.query = query;
  }
}

@Component({selector: 'needs-query-by-var-bindings'})
@View({directives: [], template: '<content>'})
@Injectable()
class NeedsQueryByTwoLabels {
  query: QueryList<any>;
  constructor(@Query("textLabel1,textLabel2", {descendants: true}) query: QueryList<any>) {
    this.query = query;
  }
}

@Component({selector: 'my-comp'})
@View({
  directives: [
    NeedsQuery,
    NeedsQueryDesc,
    NeedsQueryByLabel,
    NeedsQueryByTwoLabels,
    TextDirective,
    NgIf,
    NgFor
  ]
})
@Injectable()
class MyComp {
  shouldShow: boolean;
  list;
  constructor() {
    this.shouldShow = false;
    this.list = ['1d', '2d', '3d'];
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="Use the appropriate getXXX and setXXX methods for the type" />
<meta name="abstract" content="For performance reasons, use the recommended getXXX method when retrieving values, and use the recommended setXXX method when setting values for parameters." />
<meta name="description" content="For performance reasons, use the recommended getXXX method when retrieving values, and use the recommended setXXX method when setting values for parameters." />
<meta content="methods, getxxx, setxxx" name="DC.subject" />
<meta content="methods, getxxx, setxxx" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="ctunperf25864.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf18705.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf10679.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperfstatistics.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf54492.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf10065.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf23868.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf16556.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperf16800.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperftablefunctions.html" />
<meta scheme="URI" name="DC.Relation" content="ctunperfinmemdb.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="ctunperf98197" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Use the appropriate getXXX and setXXX methods for the type</title>

Use the appropriate getXXX and setXXX methods for the type

For performance reasons, use the recommended getXXX method
when retrieving values, and use the recommended setXXX method when
setting values for parameters.

JDBC is permissive. It lets you use java.sql.ResultSet.getFloat to
retrieve an int, java.sql.ResultSet.getObject to retrieve any type,
and so on.  (java.sql.ResultSet and java.sql.CallableStatement provide getXXX methods,
and java .sql.PreparedStatement and java.sql.CallableStatement provide setXXX methods.)
This permissiveness is convenient but expensive in terms of performance.

The following table shows the recommended getXXX methods for given java.sql (JDBC)
types, and their corresponding SQL types.

Table 1. Mapping of java.sql.Types to SQL types

Recommended getXXX Method

java.sql.Types

SQL Types

getLong

BIGINT

BIGINT

getBytes

BINARY

CHAR FOR BIT DATA

getBlob

BLOB

BLOB

getString

CHAR

CHAR

getClob

CLOB

CLOB

getDate

DATE

DATE

getBigDecimal

DECIMAL

DECIMAL

getDouble

DOUBLE

DOUBLE PRECISION

getDouble

FLOAT

DOUBLE PRECISION

getInt

INTEGER

INTEGER

getBinaryStream

LONGVARBINARY

LONG VARCHAR FOR BIT DATA

getAsciiStream, getUnicodeStream

LONGVARCHAR

LONG VARCHAR

getBigDecimal

NUMERIC

DECIMAL

getFloat

REAL

REAL

getShort

SMALLINT

SMALLINT

getTime

TIME

TIME

getTimestamp

TIMESTAMP

TIMESTAMP

getBytes

VARBINARY

VARCHAR FOR BIT DATA

getString

VARCHAR

VARCHAR

None supported. You must use XMLSERIALIZE and then the
corresponding getXXX method.

SQLXML

XML

Parent topic: The tips

Related concepts

Use prepared statements with substitution parameters

Create indexes, and make sure they are being used

Ensure table statistics are accurate

Increase the size of the data page cache

Tune the size of database pages

Avoid expensive queries

Tune database booting/class loading

Avoid inserts in autocommit mode if possible

Improve the performance of table functions

Configure Derby to use an in-memory database


text:
require 'test_helper'

class OrcamentosControllerTest < ActionController::TestCase
  setup do
    @orcamento = orcamentos(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:orcamentos)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create orcamento" do
    assert_difference('Orcamento.count') do
      post :create, orcamento: {  }
    end

    assert_redirected_to orcamento_path(assigns(:orcamento))
  end

  test "should show orcamento" do
    get :show, id: @orcamento
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @orcamento
    assert_response :success
  end

  test "should update orcamento" do
    patch :update, id: @orcamento, orcamento: {  }
    assert_redirected_to orcamento_path(assigns(:orcamento))
  end

  test "should destroy orcamento" do
    assert_difference('Orcamento.count', -1) do
      delete :destroy, id: @orcamento
    end

    assert_redirected_to orcamentos_path
  end
end


text:
using Gum.DataTypes.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ToolsUtilities;

namespace Gum.DataTypes
{
    public class ComponentSave : ElementSave
    {
        public List<ElementBehaviorReference> Behaviors { get; set; } = new List<ElementBehaviorReference>();

        public override string FileExtension
        {
            get { return GumProjectSave.ComponentExtension; }
        }

        public override string Subfolder
        {
            get { return ElementReference.ComponentSubfolder; }
        }

        public ComponentSave Clone()
        {
            var cloned = FileManager.CloneSaveObject(this);
            return cloned;

        }

    }
}


text:
package com.github.ansell.dwca;

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * Tests for {@link DarwinCoreField}.
 *
 * @author Peter Ansell p_ansell@yahoo.com
 */
public class DarwinCoreFieldTest {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	/**
	 * Test method for {@link com.github.ansell.dwca.DarwinCoreField#getIndex()}
	 * .
	 */
	@Test
	public final void testGetIndex() {
		DarwinCoreField testField = new DarwinCoreField();
		assertNull(testField.getIndex());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setIndex(java.lang.Integer)}
	 * .
	 */
	@Test
	public final void testSetIndex() {
		DarwinCoreField testField = new DarwinCoreField();
		assertNull(testField.getIndex());
		testField.setIndex(2);
		assertEquals(2, testField.getIndex().intValue());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setIndex(java.lang.Integer)}
	 * .
	 */
	@Test
	public final void testSetIndexMultiple() {
		DarwinCoreField testField = new DarwinCoreField();
		assertNull(testField.getIndex());
		testField.setIndex(2);
		assertEquals(2, testField.getIndex().intValue());
		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("Cannot specify multiple indexes for a field");
		testField.setIndex(3);
	}

	/**
	 * Test method for {@link com.github.ansell.dwca.DarwinCoreField#getTerm()}.
	 */
	@Test
	public final void testGetTermError() {
		DarwinCoreField testField = new DarwinCoreField();
		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("Term was required for field, but was not set");
		testField.getTerm();
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setTerm(java.lang.String)}.
	 */
	@Test
	public final void testSetTerm() {
		DarwinCoreField testField = new DarwinCoreField();
		testField.setTerm("test");
		assertEquals("test", testField.getTerm());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setTerm(java.lang.String)}.
	 */
	@Test
	public final void testSetTermMultiple() {
		DarwinCoreField testField = new DarwinCoreField();
		testField.setTerm("test");
		assertEquals("test", testField.getTerm());
		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("Cannot specify multiple terms for a field");
		testField.setTerm("another");
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#getDefault()}.
	 */
	@Test
	public final void testGetDefault() {
		DarwinCoreField testField = new DarwinCoreField();
		assertNull(testField.getDefault());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setDefault(java.lang.String)}
	 * .
	 */
	@Test
	public final void testSetDefault() {
		DarwinCoreField testField = new DarwinCoreField();
		testField.setDefault("test");
		assertEquals("test", testField.getDefault());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setDefault(java.lang.String)}
	 * .
	 */
	@Test
	public final void testSetDefaultMultiple() {
		DarwinCoreField testField = new DarwinCoreField();
		testField.setDefault("test");
		assertEquals("test", testField.getDefault());
		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("Cannot specify multiple default values for a field");
		testField.setDefault("another");
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#getVocabulary()}.
	 */
	@Test
	public final void testGetVocabulary() {
		DarwinCoreField testField = new DarwinCoreField();
		assertNull(testField.getVocabulary());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setVocabulary(java.lang.String)}
	 * .
	 */
	@Test
	public final void testSetVocabulary() {
		DarwinCoreField testField = new DarwinCoreField();
		testField.setVocabulary("test");
		assertEquals("test", testField.getVocabulary());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreField#setVocabulary(java.lang.String)}
	 * .
	 */
	@Test
	public final void testSetVocabularyMultiple() {
		DarwinCoreField testField = new DarwinCoreField();
		testField.setVocabulary("test");
		assertEquals("test", testField.getVocabulary());
		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("Cannot specify multiple vocabularies for a field");
		testField.setVocabulary("another");
	}

}


text:
//----------------------------------------------------------------------------
/** @file GoPlayer.h
    Player.
*/
//----------------------------------------------------------------------------

#ifndef GO_PLAYER_H
#define GO_PLAYER_H

#include <string>
#include "GoBoard.h"
#include "GoBoardSynchronizer.h"
#include "GoPlayerMove.h"
#include "SgBoardColor.h"
#include "SgPoint.h"

class SgNode;
class SgTimeRecord;

//----------------------------------------------------------------------------

/** Player. */
class GoPlayer
    : public GoBoardSynchronizer
{
public:
    /** Constructor.
    */
    GoPlayer(const GoBoard& bd);

    virtual ~GoPlayer();

    /** See m_board */
    GoBoard& Board();

    /** See m_board */
    const GoBoard& Board() const;

    /** Generate a move. */
    virtual SgPoint GenMove(const SgTimeRecord& time,
                            SgBlackWhite toPlay) = 0;

    /** Get the name of this player.
        Default implementation returns "Unknown"
    */
    virtual std::string Name() const;

    /** Get node for appending search traces */
    SgNode* CurrentNode() const;

    /** Set node for appending search traces */
    void SetCurrentNode(SgNode* node);

    /** Return value for a move.
        Not all players assign values to moves.
        If a player cannot score moves in general, or cannot score this move
        in particular, it should return numeric_limits<int>::min()
        (which is what the default implementation does).
        Values can be positive or negative; better moves should have higher
        values; the units of the values are not specified.
     */
    virtual int MoveValue(SgPoint p);

    /** Inform the player that the game was finished.
        This function gives the player the opportunity to do some work at
        the end of a game, for example perform some learning.
        However it is not guaranteed that this function will be called at
        all, the player should not rely on it. The reason is that a game
        start and end is not always well-defined (setup, undo, etc.)
        For example, it will be called in the GTP interface if after a change
        on the board GoBoardUtil::EndOfGame() is true.
        The default implementation does nothing.
    */
    virtual void OnGameFinished();

    /** Inform the player that a new game was started.
        This function gives the player the opportunity to clear some cached
        data, that is useful only within the same game.
        However it is not guaranteed that this function will be called at
        all, the player should not rely on it. The reason is that a game
        start and end is not always well-defined (setup, undo, etc.)
        For example, it will be called in the GTP interface in
        GoGtpEngine::Init(), or on the clear_board and loadsgf commands.
        The default implementation does nothing.
    */
    virtual void OnNewGame();

    /** Think during opponent's time.
        This function should poll SgUserAbort() and return immediately if
        it returns true.
        It is good style to enable pondering in the player with a parameter
        and return immediately if it is not enabled. If it is enabled, it
        should stop after some resource limit is reached to avoid that a
        program is hogging the CPU if it is just waiting for commands.
        The function Ponder() is typically called from a different thread but
        without overlap with other uses of the player, so the player does not
        have to care about thread-safety.
        Default implementation does nothing and returns immediately.
    */
    virtual void Ponder();

    /** See m_variant */
    int Variant() const;

    /** See m_variant */
    void SetVariant(int variant);

protected:
    /** Node in game tree. Used for appending search traces */
    SgNode* m_currentNode;

private:
    /** The player's own Go board */
    GoBoard m_bd;

    /** Player variant. Used for short-term testing of small modifications.
        The default variant is 0.
        Do not use to create significantly different players -
        implement a new player instead.
    */
    int m_variant;

    /** Not implemented */
    GoPlayer(const GoPlayer&);

    /** Not implemented */
    GoPlayer& operator=(const GoPlayer&);
};

inline GoBoard& GoPlayer::Board()
{
    return m_bd;
}

inline const GoBoard& GoPlayer::Board() const
{
    return m_bd;
}

inline SgNode* GoPlayer::CurrentNode() const
{
    return m_currentNode;
}

inline void GoPlayer::SetCurrentNode(SgNode* node)
{
    m_currentNode = node;
}

inline int GoPlayer::Variant() const
{
    return m_variant;
}

inline void GoPlayer::SetVariant(int variant)
{
    m_variant = variant;
}

//----------------------------------------------------------------------------

#endif // GO_PLAYER_H


text:
package namespace

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"path"
	"strings"
	"sync"
	"testing"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/unversioned"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
	"k8s.io/kubernetes/pkg/client/restclient"
	"k8s.io/kubernetes/pkg/client/testing/core"
	"k8s.io/kubernetes/pkg/client/typed/dynamic"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/sets"
)

func TestFinalized(t *testing.T) {
	testNamespace := &api.Namespace{
		Spec: api.NamespaceSpec{
			Finalizers: []api.FinalizerName{"a", "b"},
		},
	}
	if finalized(testNamespace) {
		t.Errorf("Unexpected result, namespace is not finalized")
	}
	testNamespace.Spec.Finalizers = []api.FinalizerName{}
	if !finalized(testNamespace) {
		t.Errorf("Expected object to be finalized")
	}
}

func TestFinalizeNamespaceFunc(t *testing.T) {
	mockClient := &fake.Clientset{}
	testNamespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{
			Name:            "test",
			ResourceVersion: "1",
		},
		Spec: api.NamespaceSpec{
			Finalizers: []api.FinalizerName{"kubernetes", "other"},
		},
	}
	finalizeNamespace(mockClient, testNamespace, api.FinalizerKubernetes)
	actions := mockClient.Actions()
	if len(actions) != 1 {
		t.Errorf("Expected 1 mock client action, but got %v", len(actions))
	}
	if !actions[0].Matches("create", "namespaces") || actions[0].GetSubresource() != "finalize" {
		t.Errorf("Expected finalize-namespace action %v", actions[0])
	}
	finalizers := actions[0].(core.CreateAction).GetObject().(*api.Namespace).Spec.Finalizers
	if len(finalizers) != 1 {
		t.Errorf("There should be a single finalizer remaining")
	}
	if "other" != string(finalizers[0]) {
		t.Errorf("Unexpected finalizer value, %v", finalizers[0])
	}
}

func testSyncNamespaceThatIsTerminating(t *testing.T, versions *unversioned.APIVersions) {
	now := unversioned.Now()
	namespaceName := "test"
	testNamespacePendingFinalize := &api.Namespace{
		ObjectMeta: api.ObjectMeta{
			Name:              namespaceName,
			ResourceVersion:   "1",
			DeletionTimestamp: &now,
		},
		Spec: api.NamespaceSpec{
			Finalizers: []api.FinalizerName{"kubernetes"},
		},
		Status: api.NamespaceStatus{
			Phase: api.NamespaceTerminating,
		},
	}
	testNamespaceFinalizeComplete := &api.Namespace{
		ObjectMeta: api.ObjectMeta{
			Name:              namespaceName,
			ResourceVersion:   "1",
			DeletionTimestamp: &now,
		},
		Spec: api.NamespaceSpec{},
		Status: api.NamespaceStatus{
			Phase: api.NamespaceTerminating,
		},
	}

	// when doing a delete all of content, we will do a GET of a collection, and DELETE of a collection by default
	dynamicClientActionSet := sets.NewString()
	groupVersionResources := testGroupVersionResources()
	for _, groupVersionResource := range groupVersionResources {
		urlPath := path.Join([]string{
			dynamic.LegacyAPIPathResolverFunc(groupVersionResource.GroupVersion()),
			groupVersionResource.Group,
			groupVersionResource.Version,
			"namespaces",
			namespaceName,
			groupVersionResource.Resource,
		}...)
		dynamicClientActionSet.Insert((&fakeAction{method: "GET", path: urlPath}).String())
		dynamicClientActionSet.Insert((&fakeAction{method: "DELETE", path: urlPath}).String())
	}

	scenarios := map[string]struct {
		testNamespace          *api.Namespace
		kubeClientActionSet    sets.String
		dynamicClientActionSet sets.String
	}{
		"pending-finalize": {
			testNamespace: testNamespacePendingFinalize,
			kubeClientActionSet: sets.NewString(
				strings.Join([]string{"get", "namespaces", ""}, "-"),
				strings.Join([]string{"create", "namespaces", "finalize"}, "-"),
				strings.Join([]string{"list", "pods", ""}, "-"),
				strings.Join([]string{"delete", "namespaces", ""}, "-"),
			),
			dynamicClientActionSet: dynamicClientActionSet,
		},
		"complete-finalize": {
			testNamespace: testNamespaceFinalizeComplete,
			kubeClientActionSet: sets.NewString(
				strings.Join([]string{"get", "namespaces", ""}, "-"),
				strings.Join([]string{"delete", "namespaces", ""}, "-"),
			),
			dynamicClientActionSet: sets.NewString(),
		},
	}

	for scenario, testInput := range scenarios {
		testHandler := &fakeActionHandler{statusCode: 200}
		srv, clientConfig := testServerAndClientConfig(testHandler.ServeHTTP)
		defer srv.Close()

		mockClient := fake.NewSimpleClientset(testInput.testNamespace)
		clientPool := dynamic.NewClientPool(clientConfig, dynamic.LegacyAPIPathResolverFunc)

		err := syncNamespace(mockClient, clientPool, &operationNotSupportedCache{m: make(map[operationKey]bool)}, groupVersionResources, testInput.testNamespace, api.FinalizerKubernetes)
		if err != nil {
			t.Errorf("scenario %s - Unexpected error when synching namespace %v", scenario, err)
		}

		// validate traffic from kube client
		actionSet := sets.NewString()
		for _, action := range mockClient.Actions() {
			actionSet.Insert(strings.Join([]string{action.GetVerb(), action.GetResource().Resource, action.GetSubresource()}, "-"))
		}
		if !actionSet.Equal(testInput.kubeClientActionSet) {
			t.Errorf("scenario %s - mock client expected actions:\n%v\n but got:\n%v\nDifference:\n%v", scenario,
				testInput.kubeClientActionSet, actionSet, testInput.kubeClientActionSet.Difference(actionSet))
		}

		// validate traffic from dynamic client
		actionSet = sets.NewString()
		for _, action := range testHandler.actions {
			actionSet.Insert(action.String())
		}
		if !actionSet.Equal(testInput.dynamicClientActionSet) {
			t.Errorf("scenario %s - dynamic client expected actions:\n%v\n but got:\n%v\nDifference:\n%v", scenario,
				testInput.dynamicClientActionSet, actionSet, testInput.dynamicClientActionSet.Difference(actionSet))
		}
	}
}

func TestRetryOnConflictError(t *testing.T) {
	mockClient := &fake.Clientset{}
	numTries := 0
	retryOnce := func(kubeClient clientset.Interface, namespace *api.Namespace) (*api.Namespace, error) {
		numTries++
		if numTries <= 1 {
			return namespace, errors.NewConflict(api.Resource("namespaces"), namespace.Name, fmt.Errorf("ERROR!"))
		}
		return namespace, nil
	}
	namespace := &api.Namespace{}
	_, err := retryOnConflictError(mockClient, namespace, retryOnce)
	if err != nil {
		t.Errorf("Unexpected error %v", err)
	}
	if numTries != 2 {
		t.Errorf("Expected %v, but got %v", 2, numTries)
	}
}

func TestSyncNamespaceThatIsTerminatingNonExperimental(t *testing.T) {
	testSyncNamespaceThatIsTerminating(t, &unversioned.APIVersions{})
}

func TestSyncNamespaceThatIsTerminatingV1Beta1(t *testing.T) {
	testSyncNamespaceThatIsTerminating(t, &unversioned.APIVersions{Versions: []string{"extensions/v1beta1"}})
}

func TestSyncNamespaceThatIsActive(t *testing.T) {
	mockClient := &fake.Clientset{}
	testNamespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{
			Name:            "test",
			ResourceVersion: "1",
		},
		Spec: api.NamespaceSpec{
			Finalizers: []api.FinalizerName{"kubernetes"},
		},
		Status: api.NamespaceStatus{
			Phase: api.NamespaceActive,
		},
	}
	err := syncNamespace(mockClient, nil, &operationNotSupportedCache{m: make(map[operationKey]bool)}, testGroupVersionResources(), testNamespace, api.FinalizerKubernetes)
	if err != nil {
		t.Errorf("Unexpected error when synching namespace %v", err)
	}
	if len(mockClient.Actions()) != 0 {
		t.Errorf("Expected no action from controller, but got: %v", mockClient.Actions())
	}
}

// testServerAndClientConfig returns a server that listens and a config that can reference it
func testServerAndClientConfig(handler func(http.ResponseWriter, *http.Request)) (*httptest.Server, *restclient.Config) {
	srv := httptest.NewServer(http.HandlerFunc(handler))
	config := &restclient.Config{
		Host: srv.URL,
	}
	return srv, config
}

// fakeAction records information about requests to aid in testing.
type fakeAction struct {
	method string
	path   string
}

// String returns method=path to aid in testing
func (f *fakeAction) String() string {
	return strings.Join([]string{f.method, f.path}, "=")
}

// fakeActionHandler holds a list of fakeActions received
type fakeActionHandler struct {
	// statusCode returned by this handler
	statusCode int

	lock    sync.Mutex
	actions []fakeAction
}

// ServeHTTP logs the action that occurred and always returns the associated status code
func (f *fakeActionHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	f.lock.Lock()
	defer f.lock.Unlock()

	f.actions = append(f.actions, fakeAction{method: request.Method, path: request.URL.Path})
	response.Header().Set("Content-Type", runtime.ContentTypeJSON)
	response.WriteHeader(f.statusCode)
	response.Write([]byte("{\"kind\": \"List\",\"items\":null}"))
}

// testGroupVersionResources returns a mocked up set of resources across different api groups for testing namespace controller.
func testGroupVersionResources() []unversioned.GroupVersionResource {
	results := []unversioned.GroupVersionResource{}
	results = append(results, unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"})
	results = append(results, unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "services"})
	results = append(results, unversioned.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "deployments"})
	return results
}


text:
package org.skfiy.typhon.spi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.cache.Cache;
import javax.cache.Caching;
import javax.inject.Inject;
import javax.inject.Singleton;

import org.skfiy.typhon.AbstractComponent;
import org.skfiy.typhon.ComponentException;
import org.skfiy.typhon.Typhons;
import org.skfiy.typhon.dobj.LargessVigor;
import org.skfiy.typhon.dobj.VipRechargingDobj;
import org.skfiy.typhon.domain.FightGroup;
import org.skfiy.typhon.domain.Friend;
import org.skfiy.typhon.domain.HeroProperty;
import org.skfiy.typhon.domain.IHeroEntity;
import org.skfiy.typhon.domain.Incident;
import org.skfiy.typhon.domain.Invisible;
import org.skfiy.typhon.domain.Mail;
import org.skfiy.typhon.domain.Normal;
import org.skfiy.typhon.domain.Player;
import org.skfiy.typhon.domain.Role;
import org.skfiy.typhon.domain.User;
import org.skfiy.typhon.domain.VacantData;
import org.skfiy.typhon.domain.item.HeroItem;
import org.skfiy.typhon.domain.item.MonthCardObject;
import org.skfiy.typhon.domain.item.RecordObject;
import org.skfiy.typhon.packet.Namespaces;
import org.skfiy.typhon.packet.Packet;
import org.skfiy.typhon.packet.PacketError;
import org.skfiy.typhon.packet.PacketFriend;
import org.skfiy.typhon.packet.SingleValue;
import org.skfiy.typhon.repository.IncidentRepository;
import org.skfiy.typhon.repository.RoleRepository;
import org.skfiy.typhon.session.Session;
import org.skfiy.typhon.session.SessionConstants;
import org.skfiy.typhon.session.SessionContext;
import org.skfiy.typhon.session.SessionManager;
import org.skfiy.typhon.session.SessionUtils;
import org.skfiy.typhon.spi.activity.ActivityProvider;
import org.skfiy.typhon.spi.ranking.UpdateRankingList;
import org.skfiy.typhon.spi.role.ExpLevel;
import org.skfiy.typhon.spi.role.RoleListener;
import org.skfiy.typhon.spi.society.Member;
import org.skfiy.typhon.spi.society.Society;
import org.skfiy.typhon.spi.society.SocietyProvider;
import org.skfiy.typhon.spi.store.MarketStoreProvider;
import org.skfiy.typhon.spi.store.SocietyStoreProvider;
import org.skfiy.typhon.spi.store.WesternStoreProvider;
import org.skfiy.typhon.util.ComponentUtils;
import org.skfiy.typhon.util.FastRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 *
 * @author Kevin Zou <kevinz@skfiy.org>
 */
@Singleton
public class RoleProvider extends AbstractComponent {

    private static final Logger LOG = LoggerFactory.getLogger(RoleProvider.class);

    private final List<ExpLevel> expLevels = new ArrayList<>();
    private final List<Vip> vips = new ArrayList<>();
    private final List<VipRechargingDobj> vipRechargingDobjs = new ArrayList<>();
    private final List<Integer> buyVigors = new ArrayList<>();
    private final List<LargessVigor> largessVigors = new ArrayList<>();

    private final Random ROLE_NAME_RANDOM = new FastRandom();

    @Resource
    private Set<RoleListener> roleListeners;
    @Inject
    private SessionManager sessionManager;
    @Inject
    private RoleRepository roleReposy;
    @Inject
    private IncidentRepository incidentReposy;
    @Inject
    private UpdateRankingList updateRankingLists;
    @Inject
    private MarketStoreProvider marketStorePvodier;
    @Inject
    private WesternStoreProvider westernStoreProvider;
    @Inject
    private SocietyProvider societyProvider;
    @Inject
    private ActivityProvider activityProvider;
    @Inject
    private IncidentRepository incidentRepository;
    @Inject
    private SocietyStoreProvider societyStoreProvider;
    @Inject
    private TaskManager taskManager;

    @Resource(name = "iPlayerNameValidated")
    private Set<IPlayerNameValidated> playerNameValidates;
    private Cache<Integer, VacantData> roleVacantDataCache;
    private final List<String> prefixes = new ArrayList<>();
    private final List<String> suffixes = new ArrayList<>();
    // 好友模糊查询返回数量
    private int friendsNumber;
    // 充值抽奖
    private int luckeyDrawNumber;

    @Override
    protected void doInit() {
        loadDatas();

        roleVacantDataCache
                = Caching.getCacheManager().getCache(CacheKeys.ROLE_VACANT_DATA_CACHE_KEY);

        JSONArray array = JSONArray.parseArray(ComponentUtils.readDataFile("random_name.json"));
        for (int i = 0; i < array.size(); i++) {

            if (array.getJSONObject(i).containsKey("prefix")) {
                prefixes.add(array.getJSONObject(i).getString("prefix"));
            }
            if (array.getJSONObject(i).containsKey("suffix")) {
                suffixes.add(array.getJSONObject(i).getString("suffix"));
            }
        }
        friendsNumber = Typhons.getInteger("typhon.spi.roleProvider.friendsNumber");
        luckeyDrawNumber = Typhons.getInteger("typhon.spi.activity.luckeyDraw");
    }

    @Override
    protected void doReload() {
    }

    @Override
    protected void doDestroy() {
    }

    /**
     * 获取{@code ExpLevel }实例.
     *
     * @param level 等级
     * @return
     */
    public ExpLevel getExpLevel(int level) {
        if (level < 0 || level > expLevels.size()) {
            throw new ComponentException("Not found level[" + level + "]");
        }

        return expLevels.get(level - 1);
    }

    /**
     *
     * @return
     */
    public ExpLevel getLastExpLevel() {
        return expLevels.get(expLevels.size() - 1);
    }

    /**
     *
     * @param level
     * @return
     */
    public boolean isMaxLevel(int level) {
        return (level == expLevels.size());
    }

    /**
     *
     * @param normal
     * @param exp
     */
    public void pushExp(Normal normal, int exp) {
        if (isMaxLevel(normal.getLevel()) || exp <= 0) {
            return;
        }

        ExpLevel expLevel;
        int oldExp = normal.getExp();
        int newExp = oldExp + exp;
        int newLevel = normal.getLevel();

        while (true) {
            expLevel = getExpLevel(newLevel);
            if (newExp < expLevel.getExp()) {
                break;
            }

            newLevel++;
            normal.setVigor(normal.getVigor() + getExpLevel(newLevel).getPresentVigor());
            if (isMaxLevel(newLevel)) {
                newExp = 0;
                break;
            }

            newExp -= expLevel.getExp();
        }

        if (newLevel > normal.getLevel()) {
            normal.setLevel(newLevel);
            updateRankingLists.updateLevelRanking();
            updateInformation();

            // FIXME 刷新商店
            int minLevel = Typhons.getInteger("typhon.spi.store.marketMinLevel", 30);
            if (newLevel == minLevel || (newLevel > minLevel && (newLevel - minLevel) % 20 == 0)) {
                marketStorePvodier.autoRefreshCommodity(normal.player());
            }

            if (newLevel == 50 || (newLevel > 30 && (newLevel - 50) % 20 == 0)) {
                westernStoreProvider.autoRefreshCommodity(normal.player());
            }

            if (newLevel == 30 || newLevel == 35 || newLevel == 40) {
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(normal.player().getRole().getCreationTime());
                clearCalendar(cal);
                cal.add(Calendar.DATE, 3);

                if (cal.getTimeInMillis() >= System.currentTimeMillis()) {
                    normal.addUpgradeGifts(new RecordObject(newLevel, 0));
                }
            }
        }
        Player player = SessionUtils.getPlayer();
        if (newLevel >= activityProvider.inviteLevelLimit()
                && !player.getInvisible().isInviteBool()) {

            int uid = player.getInvisible().getInviteUid();
            Session otherSession = sessionManager.getSession(uid);
            if (uid > 0) {
                if (otherSession != null) {
                    Player otherPlayer = SessionUtils.getPlayer(otherSession);
                    Invisible invisible = otherPlayer.getInvisible();
                    invisible.getInvite().add(player.getRole().getRid());
                } else {
                    Incident inc = new Incident();
                    inc.setUid(uid);
                    inc.setEventName(IncidentConstants.INVITE_MANAGER);
                    inc.setData(JSONObject.toJSONString(player.getRole().getRid()));
                    incidentRepository.save(inc);
                }
                player.getInvisible().setInviteBool(true);
            }
        }
        if (normal.getSocietyCommodities().size() <= 0 && newLevel == 32) {
            societyStoreProvider.refreshCommodity(player);
        }
        normal.setExp(newExp);
    }

    /**
     *
     * @param recharging
     */
    public synchronized void recharge(Recharging recharging) {
        // 冲值
        Session otherSession = sessionManager.getSession(recharging.getRid());
        if (otherSession != null) {
            recharge(SessionUtils.getPlayer(otherSession), recharging);
        } else {
            Incident incident = new Incident();
            incident.setEventName(IncidentConstants.EVENT_VIP_RECHARGING);
            incident.setUid(recharging.getRid());
            incident.setData(JSON.toJSONString(recharging));
            incidentReposy.save(incident);
        }
    }

    /**
     *
     * @param player
     * @param recharging
     */
    public void recharge(Player player, Recharging recharging) {
        Normal normal = player.getNormal();

        for (VipRechargingDobj vipRechargingDobj : vipRechargingDobjs) {
            if (vipRechargingDobj.getCash() == recharging.getCash()) {
                int val = vipRechargingDobj.getDiamond() + vipRechargingDobj.getPresent();
                if (!normal.containsVigRechargingFlag(recharging.getCash())) {
                    val += vipRechargingDobj.getFirstExtraPresent();
                    normal.addVipRecharginFlag(recharging.getCash());
                }

                if (vipRechargingDobj.getCash() == 25) {
                    rechargeMonthCard(normal);
                }

//                if (System.currentTimeMillis() >= activityProvider.getVipActivityStar()
//                        && System.currentTimeMillis() < activityProvider.getVipActivityEnd()) {
//                    normal.setVipSavingsActivity(normal.getVipSavingsActivity()
//                            + vipRechargingDobj.getCash());
//
//                    player.getInvisible().setVipActivityStarTime(
//                            activityProvider.getVipActivityStar());
//                }
                if (System.currentTimeMillis() >= activityProvider.getVipDayStar()
                        && System.currentTimeMillis() < activityProvider.getVipDayEnd()) {
                    Calendar calendar = Calendar.getInstance();
                    if (player.getInvisible().getVipDate() == calendar.get(Calendar.DAY_OF_YEAR)) {
                        normal.setVipSavingsDay(normal.getVipSavingsDay()
                                + vipRechargingDobj.getCash());
                    } else {
                        normal.setVipSavingsDay(vipRechargingDobj.getCash());
                        player.getInvisible().setVipDate(calendar.get(Calendar.DAY_OF_YEAR));
                    }
                }

                JSONObject object = new JSONObject();
                object.put("place", "Recharge");

                normal.setDiamond(normal.getDiamond() + val);;
                inviteReturnDiamond(player, val);
                normal.setVipSavings(normal.getVipSavings() + vipRechargingDobj.getDiamond());
                // 充值抽奖次数
                normal.setLuckeyDrawCounts(normal.getLuckeyDrawCounts()
                        + (recharging.getCash() / luckeyDrawNumber));
                // 升级VIP
                int newVipLevel = 0;
                for (int i = normal.getVipLevel(); i < vips.size(); i++) {
                    Vip vip = vips.get(i);
                    if (vip.storedMoney <= normal.getVipSavings()) {
                        newVipLevel = i;
                    } else {
                        break;
                    }
                }

                if (normal.getVipLevel() != newVipLevel) {
                    normal.setVipLevel(newVipLevel);

                    Vip vip = getVip(newVipLevel);
                    if (vip.privileged.market_store_enabled) {
                        marketStorePvodier.autoRefreshCommodity(player);
                    }
                    if (vip.privileged.western_store_enabled) {
                        westernStoreProvider.autoRefreshCommodity(player);
                    }
                }
                return;
            }
        }

        throw new ComponentException("No [" + recharging.getCash() + "] cash");
    }

    private void rechargeMonthCard(Normal normal) {
        long expiredTime = normal.getMonthCardObject().getExpiredTime();

        Calendar cal = Calendar.getInstance();
        MonthCardObject monthCard;
        if (expiredTime != 0 && expiredTime > System.currentTimeMillis()) {
            cal.setTimeInMillis(expiredTime);
            monthCard = normal.getMonthCardObject();
        } else {
            monthCard = new MonthCardObject();
        }

        cal.add(Calendar.DATE, 30);
        clearCalendar(cal);

        monthCard.setExpiredTime(cal.getTimeInMillis());

        normal.setMonthCardObject(monthCard);
    }

    public void clearCalendar(Calendar c) {
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }

    private void inviteReturnDiamond(Player player, int val) {
        int uid = player.getInvisible().getInviteUid();
        if (uid > 0) {
            Mail mail = new Mail();
            mail.setTitle("邀请者钻石返还");
            mail.setContent("您所邀请的玩家已充值成功,返还给您钻石");
            mail.setAppendix(Typhons.getProperty("typhon.spi.singleDiamondItemId"));
            mail.setCount((int) (val * 0.2));
            mail.setType(Mail.REPARATION_NOTICE_TYPE);
            sendMail(uid, mail);
        }
    }

    /**
     *
     * @param vip
     * @return
     */
    public Vip getVip(int vip) {
        if (vip >= vips.size()) {
            throw new NotFoundVipException("Not found [" + vip + "] vip.");
        }
        return vips.get(vip);
    }

    /**
     *
     * @param uid
     * @return
     */
    public boolean existsRole(int uid) {
        if (roleVacantDataCache.containsKey(uid)) {
            return true;
        }

        return roleReposy.get(uid) != null;
    }

    /**
     *
     * @param rid
     * @return
     */
    public VacantData loadVacantData(int rid) {
        VacantData data = roleVacantDataCache.get(rid);
        if (data == null) {
            data = roleReposy.loadVacantData(rid);
            roleVacantDataCache.put(rid, data);
        }
        return data;
    }

    /**
     *
     * @param name
     */
    public void create(String name) {
        // save role
        Role role = new Role();
        role.setRid(SessionUtils.getUser().getUid());
        role.setName(name);
        role.setEnabled(true);
        roleReposy.save(role);

        LOG.debug("create role [rid={}, name={}] successful", role.getRid(), role.getName());

        create0(role);
        load0(role);
    }

    /**
     *
     */
    public void preload() {
        Session session = SessionContext.getSession();
        User user = SessionUtils.getUser();

        Role role;
        Player player = (Player) session.getAttribute(SessionUtils.ATTR_PLAYER);
        if (player != null) {
            role = player.getRole();
        } else {
            // 从数据库查询角色信息
            role = roleReposy.get(user.getUid());
            if (role == null) {
                session.write(Namespaces.ROLE, "{}");
                return;
            }
        }

        load0(role);
    }

    /**
     * 购买体力.
     *
     * @param packet 包
     */
    public void buyVigor(Packet packet) {
        Player player = SessionUtils.getPlayer();
        Normal normal = player.getNormal();

        Vip vip = getVip(normal.getVipLevel());
        if (normal.getBuyVigorCount() >= vip.privileged.buy_vigor_count) {
            // 没有足够的次数继续购买体力
            PacketError error = PacketError.createResult(packet, PacketError.Condition.conflict);
            error.setText("Not enough buy vigor count");
            player.getSession().write(error);
            return;
        }

        int dep;
        if (normal.getBuyVigorCount() >= buyVigors.size()) {
            dep = buyVigors.get(buyVigors.size() - 1);
        } else {
            dep = buyVigors.get(normal.getBuyVigorCount());
        }
        JSONObject object = new JSONObject();
        object.put("place", "BuyVigor");
        object.put("buyCounts", normal.getBuyVigorCount());
        SessionUtils.decrementDiamond(dep, object.toString());
        normal.setVigor(normal.getVigor() + Typhons.getInteger("typhon.spi.role.buyVigorVal"));
        normal.setBuyVigorCount(normal.getBuyVigorCount() + 1);

        player.getSession().write(Packet.createResult(packet));
    }

    /**
     *
     * @param rid
     * @param mail
     */
    public void sendMail(int rid, Mail mail) {
        Session session = sessionManager.getSession(rid);
        if (session != null) {
            Player player = SessionUtils.getPlayer(session);
            Normal normal = player.getNormal();
            normal.addMail(mail);
        } else {
            // 通过事件机制发送邮件
            Incident inc = new Incident();
            inc.setUid(rid);
            inc.setEventName(IncidentConstants.EVENT_MAIL_NEW);
            inc.setData(JSONObject.toJSONString(mail));
            incidentReposy.save(inc);
        }
    }

    //
    public List<Role> findFriend(String uname, int number) {
        List<Role> roles = roleReposy.findRoles(uname, number);
        return roles;
    }

    /**
     *
     * @param uid
     */
    public void addFriend(int uid) {
        Player player = SessionUtils.getPlayer();
        List<Object> addFriends = new ArrayList<>();
        Session othernSession = sessionManager.getSession(uid);
        int rid = player.getRole().getRid();
        int levelLimit = 0;
        int index = 0;
        if (othernSession != null) {
            Normal normal = SessionUtils.getPlayer(othernSession).getNormal();
            Vip vip = getVip(normal.getVipLevel());
            Collection<Incident> validateIncidents = getFriendMsgSessionMap(othernSession).values();
            levelLimit = vip.privileged.max_friend_limit;
            for (Incident vinc : validateIncidents) {
                Friend friend = JSON.parseObject(vinc.getData(), Friend.class);
                if (friend.getRid() == rid) {
                    addFriends.add(0, vinc.getPid());
                    continue;
                }
                if (validateIncidents.size() - addFriends.size() >= levelLimit + 10) {
                    addFriends.add(vinc.getPid());
                }
            }
            if (validateIncidents.size() >= levelLimit + 10) {
                index = validateIncidents.size() - (levelLimit + 10) + 1;

            } else {
                index = addFriends.size();
            }
            // 删除Session中的消息,通知客户端删除请求.
            JSONObject result = new JSONObject();
            List<Integer> pids = new ArrayList<>();
            for (int i = 0; i < index; i++) {
                getFriendMsgSessionMap(othernSession).remove((int) addFriends.get(i));
                pids.add((int) addFriends.get(i));
            }
            result.put("pid", pids);
            othernSession.write(Namespaces.FRIEND_DELETE_REQUEST, result);
        } else {

            Map<Integer, String> maps
                    = incidentReposy.findPidData(uid, IncidentConstants.EVENT_FRIEND_REQUEST);
            int vipLevel = loadVacantData(uid).getVipLevel();
            Vip vip = getVip(vipLevel);
            levelLimit = vip.privileged.max_friend_limit;

            for (Entry<Integer, String> entry : maps.entrySet()) {
                Friend friend = JSON.parseObject(entry.getValue(), Friend.class);
                if (friend.getRid() == rid) {
                    addFriends.add(0, entry.getKey());
                    continue;
                }
                if (maps.size() - addFriends.size() >= levelLimit + 10) {
                    addFriends.add(entry.getKey());
                }
            }
            if (maps.size() >= levelLimit + 10) {
                index = maps.size() - (levelLimit + 10) + 1;

            } else {
                index = addFriends.size();
            }
        }

        Incident incident = new Incident();
        incident.setUid(uid);
        incident.setEventName(IncidentConstants.EVENT_FRIEND_REQUEST);
        incident.setData(JSONObject.toJSONString(integrationFriend(player)));
        incidentReposy.save(incident);

        if (othernSession != null) {
            Map<Integer, Incident> othernFriendMsgMap = getFriendMsgSessionMap(othernSession);
            othernFriendMsgMap.put(incident.getPid(), incident);

            JSONObject result = new JSONObject();
            result.put("data", incident.getJSONData());
            result.put("pid", incident.getPid());
            othernSession.write(Namespaces.FRIEND_ADD, result);
        }
        // 删除数据库.
        for (int i = 0; i < index; i++) {
            incidentReposy.delete((int) addFriends.get(i));
        }
    }

    /**
     *
     * @param packet
     */
    public void acceptFriend(PacketFriend packet) {
        int pid = packet.getPid();

        Player player = SessionUtils.getPlayer();
        Session session = player.getSession();
        Normal normal = player.getNormal();

        Map<Integer, Incident> friendMsgMap = getFriendMsgSessionMap(session);
        Incident incident = friendMsgMap.get(pid);
        if (incident == null) {
            PacketError error = PacketError.createResult(packet, PacketError.Condition.conflict);
            error.setText("Not found friend request[" + pid + "]");
            session.write(error);
            return;
        }
        Friend friend = JSON.parseObject(incident.getData(), Friend.class);

        if (!(checkFriendLimit(player) && checkFriendLimit(friend.getRid()))) {
            PacketError error = PacketError.createResult(packet, PacketError.Condition.size_limit);
            error.setText("friend size limit");
            session.write(error);
            return;
        }

        normal.addFriend(friend);

        // 清理数据
        friendMsgMap.remove(pid);
        incidentReposy.delete(pid);

        Session otherSession = sessionManager.getSession(friend.getRid());
        if (otherSession != null) {
            Normal otherNormal = SessionUtils.getPlayer(otherSession).getNormal();
            otherNormal.addFriend(integrationFriend(player));
        } else {
            Incident otherIncident = new Incident();
            otherIncident.setUid(friend.getRid());
            otherIncident.setEventName(IncidentConstants.EVENT_FRIEND_ACCEPTED);
            otherIncident.setData(JSONObject.toJSONString(integrationFriend(player)));
            incidentReposy.save(otherIncident);
        }
        session.write(Packet.createResult(packet));
    }

    /**
     *
     * @param pid
     */
    public void rejectFriend(int pid) {
        Player player = SessionUtils.getPlayer();
        Map<Integer, Incident> friendMsgMap = getFriendMsgSessionMap(player.getSession());
        Incident incident = friendMsgMap.get(pid);
        if (incident == null) {
            LOG.debug("Not found friend message[{}].", pid);
            return;
        }

        friendMsgMap.remove(pid);
        incidentReposy.delete(pid);
    }

    /**
     *
     * @param uid
     */
    public void deleteFriend(int uid) {
        Player player = SessionUtils.getPlayer();
        Role role = player.getRole();

        // 删除已方的好友
        Normal normal = player.getNormal();
        normal.deleteFriend(uid);

        // 删除对方的好友
        Session otherSession = sessionManager.getSession(uid);
        if (otherSession != null) {
            Normal otherNormal = SessionUtils.getPlayer(otherSession).getNormal();
            otherNormal.deleteFriend(role.getRid());
        } else {
            Incident incident = new Incident();
            incident.setUid(uid);
            incident.setEventName(IncidentConstants.EVENT_FRIEND_DELETEED);
            incident.setData(JSONObject.toJSONString(integrationFriend(player)));
            incidentReposy.save(incident);
        }
    }

    /**
     *
     * @param uid
     * @return
     */
    public String primaryHeroId(int uid) {
        Session beSession = sessionManager.getSession(uid);
        String id;
        if (beSession != null) {
            Normal normal = SessionUtils.getPlayer(beSession).getNormal();
            FightGroup fightGroup = normal.getFightGroup(normal.getLastFidx());
            HeroItem heroItem = fightGroup.getHeroItem(fightGroup.getCaptain());
            id = heroItem.getId();
        } else {
            VacantData vacantData = loadVacantData(uid);
            int lastFidx = vacantData.getLastFidx();
            id = loadVacantData(uid).getFightGroups()[lastFidx][vacantData.getCaptain()];
        }
        return id;
    }

    public int findHeroFighting(int uid) {
        Session session = sessionManager.getSession(uid);
        int powerGuessSum = 0;

        if (session != null) {
            Normal normal = SessionUtils.getPlayer(session).getNormal();
            FightGroup fightGroup = normal.getFightGroup(normal.getLastFidx());
            for (HeroItem heroItem : fightGroup.getHeroItems()) {
                powerGuessSum += heroItem.getPowerGuess();
            }
        } else {
            VacantData vacantData = loadVacantData(uid);
            HeroProperty heroProperty;
            for (String itemId : vacantData.getFightGroups()[vacantData.getLastFidx()]) {
                heroProperty = vacantData.findHeroProperty(itemId);
                powerGuessSum += heroProperty.getPowerGuess();
            }
        }
        return powerGuessSum;
    }

    public void showFightGroups(SingleValue packet) {
        Player player = SessionUtils.getPlayer();
        int uid = (int) packet.getVal();

        // 玩家在线则拿即时数据
        Session beSession = sessionManager.getSession(uid);
        IHeroEntity heroEntity;
        if (beSession != null) {
            Normal beNormal = SessionUtils.getPlayer(beSession).getNormal();
            FightGroup fightGoup = beNormal.getFightGroup(beNormal.getLastFidx());
            heroEntity = fightGoup.getHeroItem(fightGoup.getCaptain());
        } else {
            VacantData vacantData = loadVacantData(uid);
            heroEntity
                    = vacantData
                    .findHeroProperty(vacantData.getFightGroup(vacantData.getLastFidx())[vacantData
                            .getCaptain()]);
        }

        JSONObject beresult = new JSONObject();
        beresult.put("id", packet.getId());
        beresult.put("extraInfo", heroEntity);
        beresult.put("type", Packet.Type.rs);
        player.getSession().write(Namespaces.SHOW_HEROLIST, beresult);
    }

    /**
     *
     * @return
     */
    public String randomName() {
        int prefix = ROLE_NAME_RANDOM.nextInt(prefixes.size());
        int suffix = ROLE_NAME_RANDOM.nextInt(suffixes.size());

        StringBuilder name = new StringBuilder();
        name.append(prefixes.get(prefix));
        name.append(suffixes.get(suffix));
        return name.toString();
    }

    /**
     *
     * @param packet
     */
    public void createName(SingleValue packet) {
        Player player = SessionUtils.getPlayer();
        int sum = suffixes.size() * prefixes.size();
        int size = playerNameValidates.size();
        int i = 0;
        for (;;) {
            String name = randomName();
            for (IPlayerNameValidated pnv : playerNameValidates) {

                i++;
                if (pnv.validate(name)) {
                    SingleValue result = new SingleValue();
                    Packet.assignResult(packet, result);
                    packet.setVal(name);
                    player.getSession().write(result);
                    break;
                }
                if ((i - sum * size) == 0) {
                    PacketError error
                            = PacketError.createResult(packet, PacketError.Condition.conflict);
                    error.setText("More than random upper limit");
                    player.getSession().write(error);
                    break;
                }
            }
        }
    }

    /**
     *
     * @return
     */
    public String randomUniqueName() {
        int sum = suffixes.size() * prefixes.size();
        int size = playerNameValidates.size();
        int i = 0;
        for (;;) {
            String name = randomName();
            for (IPlayerNameValidated pnv : playerNameValidates) {
                i++;
                if (pnv.validate(name)) {
                    return name;
                }
                if ((i - sum * size) == 0) {
                    throw new IllegalStateException("More than random upper limit");
                }
            }
        }
    }

    /**
     *
     * @param uid
     * @return
     */
    public boolean checkFriendLimit(int uid) {
        Session session = sessionManager.getSession(uid);
        if (session != null) {
            return checkFriendLimit(SessionUtils.getPlayer(session));
        } else {
            VacantData data = loadVacantData(uid);
            return (data.getFriendSize() < getVip(data.getVipLevel()).privileged.max_friend_limit);
        }
    }

    /**
     *
     * @param player
     * @return
     */
    public boolean checkFriendLimit(Player player) {
        Vip vip = getVip(player.getNormal().getVipLevel());
        int limit = vip.privileged.max_friend_limit;
        return (player.getNormal().getFriends().size() < limit);
    }

    public Friend integrationFriend(Player player) {
        Role role = player.getRole();
        Normal normal = player.getNormal();
        Friend friend
                = new Friend(role.getRid(), role.getName(), role.getLevel(),
                        findHeroFighting(role.getRid()), primaryHeroId(role.getRid()),
                        normal.getAvatar(), normal.getAvatarBorder(), normal.getSocietyName());
        return friend;
    }

    /**
     *
     * @param session
     * @return
     */
    public Map<Integer, Incident> getFriendMsgSessionMap(Session session) {
        Map map = (LinkedHashMap) session.getAttribute("__FriendMsg");
        if (map == null) {
            map = new LinkedHashMap<>();
            session.setAttribute("__FriendMsg", map);
        }
        return map;
    }

    /**
     * @param role
     */
    protected void create0(Role role) {
        // fire RoleListener
        for (RoleListener roleListener : roleListeners) {
            roleListener.roleCreated(role);
        }
    }

    /**
     *
     */
    public void updateInformation() {
        taskManager.execute(new TaskManager.Task() {

            @Override
            public void run() {
                Player player = SessionUtils.getPlayer();
                int rid = player.getRole().getRid();
                for (Friend friend : player.getNormal().getFriends()) {
                    Session besession = sessionManager.getSession(friend.getRid());
                    if (besession == null) {
                        List<String> datas
                                = incidentReposy.findData(friend.getRid(),
                                        IncidentConstants.EVENT_UPDATE_FRIENDS);
                        for (String data : datas) {
                            Friend fr = JSON.parseObject(data, Friend.class);
                            if (fr.getRid() == rid) {
                                int pid = incidentReposy.findByData(data);
                                incidentReposy.delete(pid);
                            }
                        }
                        Incident incident = new Incident();
                        incident.setUid(friend.getRid());
                        incident.setData(JSONObject.toJSONString(integrationFriend(player)));
                        incident.setEventName(IncidentConstants.EVENT_UPDATE_FRIENDS);
                        incidentReposy.save(incident);

                    } else {
                        Player beplayer = SessionUtils.getPlayer(besession);
                        for (Friend befriend : beplayer.getNormal().getFriends()) {
                            if (befriend.getRid() == rid) {
                                updateFriends(befriend, player);
                            }
                        }
                    }
                }
                // 公会
                int sid = player.getNormal().getSocietyId();
                if (sid != 0) {
                    Society society = societyProvider.findBySid(sid);
                    for (Member member : society.getMembers()) {
                        if (member.getRid() == rid) {
                            updateSocietyMember(member, player);
                        }
                    }
                }
            }
        });
    }

    public void updateSocietyMember(Member member, Player player) {
        Normal normal = player.getNormal();
        Role role = player.getRole();
        member.setRid(role.getRid());
        member.setName(role.getName());
        member.setAvatar(normal.getAvatar());
        member.setAvatarBorder(normal.getAvatarBorder());
        member.setLevel(normal.getLevel());
    }

    public void updateFriends(Friend befriend, Player player) {
        Normal normal = player.getNormal();
        Role role = player.getRole();
        if (befriend.getAvatar() != normal.getAvatar()) {
            befriend.setAvatar(normal.getAvatar());
        }
        if (befriend.getAvatarBorder() != normal.getAvatarBorder()) {
            befriend.setAvatarBorder(normal.getAvatarBorder());
        }
        if (befriend.getLevel() != role.getLevel()) {
            befriend.setLevel(role.getLevel());
        }
        if (!befriend.getName().equals(role.getName())) {
            befriend.setName(role.getName());
        }
        if (befriend.getPowerGuessSum() != findHeroFighting(role.getRid())) {
            befriend.setPowerGuessSum(findHeroFighting(role.getRid()));
        }
        if (befriend.getSocietyName() != normal.getSocietyName()) {
            befriend.setSocietyName(normal.getSocietyName());
        }
    }

    /**
     * 玩家基础信息
     */
    public void roleBase(SingleValue packet) {
        Player player = SessionUtils.getPlayer();
        int rid = (int) packet.getVal();
        JSONObject object = new JSONObject();
        Session session = sessionManager.getSession(rid);
        if (session == null) {
            VacantData vacantData = loadVacantData(rid);
            object.put("name", vacantData.getName());
            object.put("avatar", vacantData.getAvatar());
            object.put("avatarBorder", vacantData.getAvatarBorder());
            object.put("level", vacantData.getLevel());
            object.put("societyName", vacantData.getSocietyName());
        } else {
            Player bePlayer = SessionUtils.getPlayer(session);
            Normal normal = bePlayer.getNormal();
            object.put("name", bePlayer.getRole().getName());
            object.put("avatar", normal.getAvatar());
            object.put("avatarBorder", normal.getAvatarBorder());
            object.put("level", normal.getLevel());
            object.put("societyName", normal.getSocietyName());
        }
        SingleValue result = new SingleValue();
        Packet.assignResult(packet, result);
        result.setVal(object);
        player.getSession().write(result);
    }

    /**
     *
     * @param role
     */
    protected void load0(Role role) {
        // 角色已经被禁用无法进入游戏
        if (!role.isEnabled()) {
            Session session = SessionContext.getSession();
            Packet contextPacket
                    = (Packet) session.getAttribute(SessionConstants.ATTR_CONTEXT_PACKET);
            PacketError error
                    = PacketError.createResult(contextPacket, PacketError.Condition.not_enabled_role);
            error.setText("Not enabled role");
            session.write(error);
            return;
        }

        for (RoleListener roleListener : roleListeners) {
            roleListener.roleLoaded(role);
        }

        // 更新最后登录时间
        roleReposy.updateLastLoginedTime(role.getRid());
        role.setLastLoginedTime(System.currentTimeMillis());
    }

    private void loadDatas() {
        List<ExpLevel> expLevelConfig
                = JSON.parseArray(ComponentUtils.readDataFile("exp_level.json"), ExpLevel.class);
        this.expLevels.addAll(expLevelConfig);

        // load vip config
        JSONArray jsonArray = JSON.parseArray(ComponentUtils.readDataFile("vip.json"));
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            vips.add(new Vip(json));
        }

        // load "vip_recharging.json" config
        vipRechargingDobjs.addAll(JSON.parseArray(
                ComponentUtils.readDataFile("vip_recharging.json"), VipRechargingDobj.class));

        // load buy vigor config
        List<Integer> buyVigorConfig
                = JSON.parseArray(ComponentUtils.readDataFile("buy_vigor.json"), Integer.class);
        this.buyVigors.addAll(buyVigorConfig);

        // load largess_vigor
        List<LargessVigor> largessVigorConfig
                = JSON.parseArray(ComponentUtils.readDataFile("largess_vigor.json"),
                        LargessVigor.class);
        this.largessVigors.addAll(largessVigorConfig);
    }

    /**
     *
     */
    public void removeSuccor(Normal normal) {
        long time = System.currentTimeMillis();
        int CD = Typhons.getInteger("typhon.spi.Warprovider.CD") * 1000 * 60;
        for (int i = normal.getSuccors().size() - 1; i >= 0; i--) {
            if (time - normal.getSuccors().get(i).getTime() >= CD) {
                normal.getSuccors().remove(i);
            }
        }
    }

    public int returnFriendsNumber() {
        return friendsNumber;
    }

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// import * as firebase from 'firebase-admin';
class Disconnected /** implements firebase.database.OnDisconnect */ {
    cancel(onComplete) {
        return Promise.resolve();
    }
    remove(onComplete) {
        return Promise.resolve();
    }
    set(value, onComplete) {
        return Promise.resolve();
    }
    setWithPriority(value, priority, onComplete) {
        return Promise.resolve();
    }
    update(values, onComplete) {
        return Promise.resolve();
    }
}
exports.default = Disconnected;
//# sourceMappingURL=Disconnected.js.map


text:
{% load l10n %}

                      Sent
                      User
                      Hidden User
                      Subject
                      Client
                      Hidden Client
                      Project
                      Issue Date
                      Hidden Issue Date
                      Amount
                      Hidden Amount
                      Add
                      View
                      Edit

                  {% for item in items %}

                      {% if item.last_payment_date or item.accepted_date %}{% endif %}
                      {% if item.user %}{{ item.user.get_full_name|default:'' }}	{% else %}	 {% endif %}
                      {{ item.user }}
                      {{ item.subject|default:'' }}
                      {% if item.client %}{{ item.client.name|default:'' }}	{% else %}	 {% endif %}
                      {{ item.client }}
                      {% if item.project %}{{ item.project.name|default:'' }}	{% else %}	{% endif %}
                      {{ item.issue_date|date:'Y-m-d'|default:'' }}
                      {{ item.issue_date|date:'U'|default:'' }}
                      {% if item.amount %}{{ company_currency_symbol }}{% endif %}{{ item.amount|default:'' }}
                      {{ item.amount|unlocalize|default:'' }}
                       View
                       Edit
                       Add Time

                  {% endfor %}