text:
module Cryptoexchange::Exchanges
  module Kairex
    module Services
      class Market < Cryptoexchange::Services::Market
        class << self
          def supports_individual_ticker_query?
            true
          end
        end

        def fetch(market_pair)
          output = super(ticker_url(market_pair))
          adapt(output, market_pair)
        end

        def ticker_url(market_pair)
          "#{Cryptoexchange::Exchanges::Kairex::Market::API_URL}/market/ticker?quote=#{market_pair.target}&base=#{market_pair.base}"
        end

        def adapt(output, market_pair)
          ticker = Cryptoexchange::Models::Ticker.new
          base = market_pair.base
          target = market_pair.target

          ticker.base      = base
          ticker.target    = target
          ticker.market    = Kairex::Market::NAME
          ticker.last      = NumericHelper.to_d(output['close'])
          ticker.change    = NumericHelper.to_d(output['changePercent'])
          ticker.high      = NumericHelper.to_d(output['high'])
          ticker.low       = NumericHelper.to_d(output['low'])
          ticker.volume    = NumericHelper.to_d(output['volume'])
          ticker.timestamp = nil
          ticker.payload   = output
          ticker
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 * SkyRover2 Multi-Quadcopter Client
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * This file has been created with reference to the
 *  > https://github.com/bitcraze/crazyflie-android-client/blob/master/src/se/bitcraze/crazyflielib/BleLink.java
 */

package net.smartrover.skyrover2.roverlib;

import net.smartrover.skyrover2.roverlib.crtp.CrtpPacket;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * @author OROCA SmartRover Team
 */
@SuppressLint("NewApi")
public class BleLink extends AbstractLink {

	private static final String TAG = "BleLink";

	// Set to -40 to connect only to close-by SkyRover2
	private static final int rssiThreshold = -100;

	BluetoothAdapter mBluetoothAdapter;
	private final static int REQUEST_ENABLE_BT = 1;
	private BluetoothDevice mDevice;
	private boolean mWriteWithAnswer;
	protected BluetoothGattCharacteristic mLedChar;
	protected BluetoothGatt mGatt;
	protected boolean mConnected;
	protected List<BluetoothGattCharacteristic> mLedsChars;
	protected BluetoothGattCharacteristic mCrtpChar;
	private static Activity mContext;
	protected static boolean mWritten = true;
	private Timer mScannTimer;

	protected enum State {IDLE, CONNECTING, CONNECTED};
	protected State state = State.IDLE;

	public BleLink(Activity ctx, boolean writeWithAnswer) {
		mContext = ctx;
		mWriteWithAnswer = writeWithAnswer;
	}

	private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status,
				int newState) {
			super.onConnectionStateChange(gatt, status, newState);
			if (newState ==BluetoothProfile.STATE_CONNECTED) {
				gatt.discoverServices();
				mGatt = gatt;
			} else {
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
				mConnected = false;
				state = State.IDLE;
				notifyConnectionLost();
			}
		}

		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			super.onServicesDiscovered(gatt, status);
			if (status != BluetoothGatt.GATT_SUCCESS) {
				gatt.disconnect();
			} else {
				BluetoothGattService cfService = gatt.getService(UUID.fromString("00000201-1c7f-4f9e-947b-43b7c00a9a08"));
				mCrtpChar = cfService.getCharacteristic(UUID.fromString("00000202-1c7f-4f9e-947b-43b7c00a9a08"));

				gatt.setCharacteristicNotification(mCrtpChar, true);

				BluetoothGattDescriptor descriptor = mCrtpChar.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805F9B34FB"));
				descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
				gatt.writeDescriptor(descriptor);

				Log.d(TAG, "Connected!");

				mConnected = true;
				mWritten = false;

				state = State.CONNECTED;
				notifyConnectionSetupFinished();
			}
		}

		@Override
		public void onCharacteristicWrite(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic, int status) {
			super.onCharacteristicWrite(gatt, characteristic, status);
			//Log.d(TAG, "On write called for char: " + characteristic.getUuid().toString());
			BleLink.mWritten  = true;
		}

		@Override
		public void onDescriptorWrite(BluetoothGatt gatt,
				BluetoothGattDescriptor descritor, int status) {
			super.onDescriptorWrite(gatt, descritor, status);
			Log.d(TAG, "On write called for descriptor: " + descritor.getUuid().toString());
			mWritten = true;
		}

		@Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
			super.onCharacteristicRead(gatt, characteristic, status);
			Log.d(TAG, "On read call for characteristic: " + characteristic.getUuid().toString());
        }

		@Override
		public void onCharacteristicChanged(BluetoothGatt gatt,
		        BluetoothGattCharacteristic characteristic) {
			//super.onCharacteristicChanged(gatt, characteristic);
			Log.d(TAG, "On changed call for characteristic: " + characteristic.getUuid().toString());
		}
	};

	private LeScanCallback mLeScanCallback = new LeScanCallback() {
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] anounce) {
			if (device != null && device.getName() != null) {
				Log.d(TAG, "Scanned device \"" + device.getName() + "\" RSSI: " + rssi);

				if (device.getName().equals("Crazyflie") && rssi>rssiThreshold) {
					mBluetoothAdapter.stopLeScan(this);
					if (mScannTimer != null) {
						mScannTimer.cancel();
						mScannTimer = null;
					}
					state = State.CONNECTING;
					mDevice = device;
					mContext.runOnUiThread(new Runnable() {
						@Override
                        public void run() {
							mDevice.connectGatt(BleLink.mContext, false, mGattCallback);
						}
					});
				}
			}
		}
	};

	@Override
	public void connect() {
		if (state != State.IDLE) {
			throw new IllegalArgumentException("Connection already started");
		}

		final BluetoothManager bluetoothManager =
		        (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();

		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
		    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		    mContext.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		    throw new IllegalArgumentException("Bluetooth needs to be started");
		}

		mBluetoothAdapter.stopLeScan(mLeScanCallback);
		mBluetoothAdapter.startLeScan(mLeScanCallback);
		if (mScannTimer != null) {
			mScannTimer.cancel();
		}
		mScannTimer = new Timer();
		mScannTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
				state = State.IDLE;
				notifyConnectionFailed();
			}
		}, 10000);

		state = State.CONNECTING;
		notifyConnectionInitiated();
	}

	@Override
	public void disconnect() {
		mContext.runOnUiThread(new Runnable() {
			public void run() {
				if(mConnected) {
					mGatt.disconnect();
					mGatt.close();
					mGatt = null;
					mConnected = false;
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					if (mScannTimer != null) {
						mScannTimer.cancel();
						mScannTimer = null;
					}
					state = State.IDLE;
					notifyDisconnected();
				}
			}
		});
	}

	@Override
	public boolean isConnected() {
		return state != State.IDLE;
	}

	int ctr = 0;
	@Override
	public void send(CrtpPacket packet) {

		// FIXME: Skipping half of the commander packets to avoid queuing up packets on slow BLE
		if ((mWriteWithAnswer == false) && ((ctr++)%2 == 0))
			return;

		class SendBlePacket implements Runnable {
			CrtpPacket pk;
			SendBlePacket(CrtpPacket pk) { this.pk = pk; }
			public void run() {
				if(mConnected && mWritten) {
					if (mWriteWithAnswer) {
						mCrtpChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
						mWritten = false;
					} else {
						mCrtpChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
						mWritten = true;
					}
					mCrtpChar.setValue(pk.toByteArray());
					mGatt.writeCharacteristic(mCrtpChar);
				}
	        }
		}
		mContext.runOnUiThread(new SendBlePacket(packet));
	}

}


text:
from django.contrib import admin

from frequencia.vinculos.models import Vinculo

from .models import User

class VinculosInline(admin.TabularInline):
    model = Vinculo

class UsuarioAdmin(admin.ModelAdmin):
    inlines = [
        VinculosInline,
    ]

admin.site.register(User, UsuarioAdmin)


text:
<!-- admin/index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>

    <title>Content Manager</title>
  </head>
  <body>
    <!-- Include the script that builds the page and powers Netlify CMS -->
    <script src="https://unpkg.com/netlify-cms@^2.0.0/dist/netlify-cms.js"></script>
  </body>
</html>


text:
@extends('badmin::layouts.master')
@section('title')Permissions @stop
@section('content')
@include('badmin::partials.nav-partial', array('active' => 'Permissions'))
@include('badmin::partials.delete-confirm')

      Name
      Description
      Permitted Operations

  @foreach ($permissions as $permission)

      {{ $permission->name }}
      {{ $permission->description }}

        @if ($permission->slug)
          @if ($permission->slug['create'])
            Create
          @endif
          @if ($permission->slug['view'])
            View
          @endif
          @if ($permission->slug['update'])
            Update
          @endif
          @if ($permission->slug['delete'])
            Delete
          @endif
        @endif

        id }}/edit" class="btn btn-xs btn-info pull-left" style="margin-right: 3px;">Edit
        {!! Form::open(['url' => '/admin/permission/' . $permission->id, 'method' => 'DELETE']) !!}
        {!! Form::button('Delete', ['class' => 'btn btn-xs btn-danger',
                                    'data-toggle' => 'modal',
                                    'data-target' => '#confirmDelete',
                                    'data-title' => 'Delete Permission',
                                    'data-message' => 'Are you sure you want to delete permission ' . $permission->name . '?'])!!}
        {!! Form::close() !!}

  @endforeach

Add Permission
@stop


text:
package org.apache.camel.component.ironmq.integrationtest;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.ironmq.IronMQConstants;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import static org.apache.camel.test.junit5.TestSupport.assertFileExists;
import static org.apache.camel.test.junit5.TestSupport.deleteDirectory;

@Disabled("Integration test that requires ironmq account.")
public class FileCopyExample extends CamelTestSupport {
    // replace with your proejctid
    private String projectId = "myIronMQproject";
    // replace with your token
    private String token = "myIronMQToken";

    private final String ironMQEndpoint = "ironmq:testqueue?projectId=" + projectId + "&token=" + token
                                          + "&ironMQCloud=https://mq-aws-eu-west-1-1.iron.io&preserveHeaders=true";

    @BeforeEach
    public void clean() {
        template.sendBodyAndHeader(ironMQEndpoint, "fo", IronMQConstants.OPERATION, IronMQConstants.CLEARQUEUE);
        deleteDirectory("target/out");
    }

    @Test
    public void testCopyFileOverIronMQ() throws Exception {
        getMockEndpoint("mock:result").expectedMessageCount(1);
        assertMockEndpointsSatisfied();
        assertFileExists("target/out/test.txt");
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                //copies test.txt from test/data to ironmq
                from("file:src/test/data?noop=true").convertBodyTo(String.class).log("sending : ${body}").to(ironMQEndpoint);
                //Receives test.txt from ironmq and writes it to target/out
                from(ironMQEndpoint).log("got message : ${body}").to("file:target/out").to("mock:result");
            }
        };
    }
}


text:
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */

/*
A simple node.js application intended to read data from Digital pins on the Intel based development boards such as the Intel(R) Galileo and Edison with Arduino breakout board.

MRAA - Low Level Skeleton Library for Communication on GNU/Linux platforms
Library in C/C++ to interface with Galileo & other Intel platforms, in a structured and sane API with port nanmes/numbering that match boards & with bindings to javascript & python.

Steps for installing MRAA & UPM Library on Intel IoT Platform with IoTDevKit Linux* image
Using a ssh client:
1. echo "src maa-upm http://iotdk.intel.com/repos/1.1/intelgalactic" > /etc/opkg/intel-iotdk.conf
2. opkg update
3. opkg upgrade

Article: https://software.intel.com/en-us/html5/articles/intel-xdk-iot-edition-nodejs-templates
*/

var mraa = require('mraa'); //require mraa
console.log('MRAA Version: ' + mraa.getVersion()); //write the mraa version to the console

var myDigitalPin6 = new mraa.Gpio(6); //setup digital read on Digital pin #6 (D6)
myDigitalPin6.dir(mraa.DIR_IN); //set the gpio direction to input

periodicActivity(); //call the periodicActivity function

function periodicActivity() //
{
  var myDigitalValue =  myDigitalPin6.read(); //read the digital value of the pin
  console.log('Gpio is ' + myDigitalValue); //write the read value out to the console
  setTimeout(periodicActivity,1000); //call the indicated function after 1 second (1000 milliseconds)
}


text:
layout: post
title: 'Lucid Fail : driver wireless broadcom tidak otomatis terinstall (emachine)'
date: 2010-05-02 02:47:57.000000000 +07:00
type: post
published: true
status: publish
categories:
- linux-opensource
- uncategorized
tags:
- broadcom
- fail
- linux
- lucid
- ubuntu
- wireless
meta:
  _edit_last: '7761285'
  geo_latitude: '-8.588990'
  geo_longitude: '116.130400'
  geo_accuracy: '206'
  geo_address: mataram
  geo_public: '1'
author:
  login: pdft
  email: padfoot.tgz@gmail.com
  display_name: piko
  first_name: herpiko
  last_name: dwi aguno
---

29 april dirilis, langsung donglot, install, sempurna. lalu saya coba install di sebuah emachine punya teman (cepul). sempurna, kecuali satu. driver wireless tidak bisa. padahal ini kan broadcom! jah! :(

mau donglot driver? bagaimana konek inet kalau waerles ndak bisa? (selain dengan UTP LAN dan akses broadband).

saya yakin drivernya ada di dalam CD live lucid, hanya saja tidak terinstall dengan otomatis. jika anda mengalamai masalah ini, jangan khawatir. :)

asumsi saya, lucid sudah terinstall, fresh. masukan CD-nya, kemudian buka synaptic, buka setingan bagian repositori. lalu centangkan repo dari CD instalasi, hilangkan centang dari server repo lain. OK. kemudian reload.

system > administration > hardware driver. seharusnya di jendela ini, drivernya terdeteksi, biasanya dua. pilih yang STA. active. driver akan diunduh dari CD.

beres deh. :D

btw, saat saya buka help ubuntu, slogannya masih 'linux for human being'. padahal kan sudah diganti ke 'lightware'. :)


text:
from time import time, sleep
from ev3dev.auto import *
from statistics import median
import requests
import json
import socket
import fcntl
import struct

# motors
motor_r = LargeMotor(OUTPUT_D)
motor_l = LargeMotor(OUTPUT_A)
motor_m = MediumMotor(OUTPUT_B)

# sensors
color = ColorSensor()
touch = TouchSensor()
gyro = GyroSensor()
us = UltrasonicSensor()
ir = InfraredSensor()

# follow border setting
black_color_pct = 5
white_color_pct = 84 #80
mid_point = (black_color_pct + white_color_pct)/2

color_kp = 0.45

#explore_node_speed = -25
move_on_edge_speed = -33
cross_line_speed = -22
rotate_over_node_speed = -22

rotate_speed = -30
nbr_cols_sampled = 7

gathering_max_distance = 330 # mm
collision_avoidance_distance = 45 # mm

max_cross_time = 1.5

#eyes_rotation_degree = 140
#rotation_degree_same_direction = 140
#rotation_degree_diff_direction = 20

eyes_speed = 40

# syncronized clock time unit in seconds
#sync_clock_time = 11   # for unoriented ring protocol
sync_clock_time = 16    # for oriented ring protocol

# for unoriented ring protocol
server_ip = '10.235.76.1'
server_address = 'http://{}:5000/'.format(server_ip)
port = 3

# for oriented ring protocol
serverMACAddress = '00:17:EC:F6:06:4B' # bluetooth mac address of malicious robot
port = 3
server_socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
buffer_size = 32

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15].encode())
    )[20:24])

agent_ip = get_ip_address('bnep0')

def start():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('0.0.0.0', 31337))
    s.listen(1)
    s.accept()
    s.close()
    Sound.tone(1200, 300)

def set_node_info_m(turned = 0):
    print('\nset {}'.format(turned))

    par = {'turned': turned}
    node_info_str = requests.get(server_address+'set/{}'.format(agent_ip), params = par).text
    node_info_json = json.loads(node_info_str)
    return(node_info_json['blocked'])

def set_node_info(state, turned = 0, stopped = 0):
    print('\nset {}, {}, {}'.format(turned, state, stopped))

    par = {'turned': turned, 'state': state, 'stopped': stopped }
    node_info_str = requests.get(server_address+'set/{}'.format(agent_ip), params = par).text
    node_info_json = json.loads(node_info_str)
    return(node_info_json['blocked'])

def get_node_info():
    print('\nget')
    node_info_str = requests.get(server_address+'get/{}'.format(agent_ip)).text
    node_info_json = json.loads(node_info_str)

    neighbors_states = node_info_json['agents']
    blocked_last_move = node_info_json['blocked']

    print('neighbors states {}'.format(neighbors_states)+'\nblocked {}'.format(blocked_last_move) )

    return(neighbors_states, blocked_last_move)

def get_state_robots(neighbors_states, robot_state):
    done_neighbors = [state for state in neighbors_states if state == robot_state]
    return len(done_neighbors)

def look():
    if us.connected:
        return us.value()

    if ir.connected:
        #return ir.value()
        # fake value, infrared is never used in protocol
        # use it only for robot that will became leader
        # because for this robot eyes are useless
        return 999

def can_I_move(clockwise_direction):
    print('query server to know if M is over next node')
    direction = int(clockwise_direction) # 1 if clockwise_direction is true, 0 otherwise
    # send to server the current direction, in byte
    server_socket.send( direction.to_bytes(1, byteorder='big') )
    # wait the response
    resp = server_socket.recv(buffer_size) # 00 or 01 in byte
    int_resp = int.from_bytes(resp, byteorder='big')
    return bool(int_resp)

def start_motor(motor, speed):
    #print('motor starts')
    motor.speed_regulation_enabled = 'off'
    motor.run_direct(duty_cycle_sp = speed)

def start_motors(speed):
    start_motor(motor_r, speed)
    start_motor(motor_l, speed)

def is_color_white(color_sampled):
    error_threshold = 10
    avg_color_sampled = sum(color_sampled)//nbr_cols_sampled
    return (white_color_pct - avg_color_sampled) <= error_threshold

# return true if color sampled is white or yellow
def is_not_color_black(color_sampled):
    error_threshold = 10
    # average value
    #avg_color_sampled = sum(color_sampled)//nbr_cols_sampled
    # median value
    avg_color_sampled = median(color_sampled)
    # it works because yellow color pct are greater than white color pct
    # and both are greater than black color pct
    return avg_color_sampled >= (white_color_pct - error_threshold)

def stop_motors():
    motor_r.stop()
    motor_l.stop()

def wait_clock(begin_time, nbr_clocks=1):

    last_time = begin_time
    while True:
        new_time = int(time())

        diff_time = new_time - begin_time

        if ( diff_time >= nbr_clocks*sync_clock_time ):
            print('\t\t' + str(diff_time) + ' seconds')
            print ("\t------------- clock time expired -------------\n")
            return new_time

        if ( (diff_time % 2) == 0 and last_time != new_time ):
            print('\t\t' + str(diff_time) + ' seconds')

        last_time = new_time

def is_special_node():
    color.mode = 'COL-COLOR'
    color_value = color.value()
    print('color is ' + str(color_value))
    return color_value == 4 # 4 is yellow color, see ev3dev doc

def rotate_counterclockwise(degree):
    # reset gyroscope
    gyro.mode = 'GYRO-RATE'
    gyro.mode = 'GYRO-ANG'

    start_motor(motor_r, rotate_speed)
    while True:
        if (gyro.value() <= -degree):
            stop_motors()
            break

def init_eyes_motor(speed):
    motor_m.reset()
    motor_m.speed_regulation_enabled = 'off'
    motor_m.duty_cycle_sp = speed

# use this function when ultra sound sensor us is in mode US-DIST-CM
# in this mode last digit is decimal, in practice the unit is mm, not cm
# blocking call!
def is_there_close_robot(rotation_degree, distance = gathering_max_distance):
    #init_eyes_motor(eyes_speed)

    close_robot_detected = False

    #us.mode = 'US-SI-CM'
    #sleep(0.3)
    us_value = look()
    sleep(0.2)

    print('ultrasound value is ' + str(us_value) + ' mm')
    if us_value <= distance:
        print('robot detected')
        close_robot_detected = True

    elif(rotation_degree != -1):
        # move eyes clockwise
        motor_m.run_to_abs_pos(position_sp = rotation_degree)
        # this time must be >= the time to perform a rotation
        # and then to look up, because it could take a while to focus the distance
        sleep(1.3)
        #print('real eyes rotation: ' + str(motor_m.position))

        us_value = look()
        sleep(0.2)

        print('ultrasound value is ' + str(us_value) + ' mm')
        if us_value <= distance:
            print('robot detected')
            close_robot_detected = True

        # move eyes counterclockwise to reset them in their original position
        motor_m.run_to_abs_pos(position_sp = 0)
        sleep(1)
        #print('real eyes rotation: ' + str(motor_m.position))

    return close_robot_detected

def left_correction():
    print('left correction')
    start_motor(motor_r, -15)
    start_motor(motor_l, 10)
    sleep(0.6)
    stop_motors()

def right_correction():
    print('right correction')
    start_motor(motor_r, 10)
    start_motor(motor_l, -15)
    sleep(0.6)
    stop_motors()

'''
Moving functions
'''
def follow_border(color_value, speed, line_ext):
    # with positive degree robot goes to right
    error = color_value - mid_point
    correction = color_kp*error

    right_speed = speed - correction
    left_speed = speed + correction

    if (not line_ext):
        right_speed = speed + correction
        left_speed = speed - correction

    motor_r.duty_cycle_sp = right_speed
    motor_l.duty_cycle_sp = left_speed

    return error

def cross_marker():
    print('cross marker area')
    start_time = time()

    color.mode = 'COL-COLOR'
    start_motors(cross_line_speed)

    while True:
        if time() - start_time >= max_cross_time:
            print('max cross time reached\nstop')
            break

        if color.value() == 1: # black color
            print('marker crossed\nstop')
            stop_motors()
            break

def rotate_over_node(collision_distance=-1, time_to_settle=3, time_out=None):
    start_time = int(time())
    print('rotate over node')
    color.mode = 'COL-REFLECT'
    start_motors(rotate_over_node_speed)
    col_count = 0
    last_cols_sampled = [0]*nbr_cols_sampled

    if collision_distance != -1:
        print('move eyes.')
        motor_m.run_to_abs_pos(position_sp=30)
        sleep(0.5)
        #print('current eyes position = ' + str(motor_m.position))

    while True:
        elapsed_time = int(time()) - start_time

        color_sampled = color.value()
        color_error = follow_border(color_sampled, rotate_over_node_speed, False)
        last_cols_sampled[col_count] = color_sampled
        col_count = (col_count+1) % nbr_cols_sampled

        if ( (time_out != None) and (elapsed_time >= time_out) ):
            stop_motors()
            return False

        # stop when we found next marker
        if ( (elapsed_time >= time_to_settle) and is_not_color_black(last_cols_sampled)):
            stop_motors()
            left_correction()
            if collision_distance != -1:
                motor_m.run_to_abs_pos(position_sp=0)
                sleep(0.5)
            return False

        if collision_distance != -1:
            us_value = look()
            print(us_value)
            if ( us_value <= collision_distance ):
                stop_motors()
                print('a stopped robot has been detected at ' + str(us_value) + ' mm \nstop')
                # close eyes and reset them to their start position
                motor_m.run_to_abs_pos(position_sp=0)
                sleep(0.5) # time to move eyes
                #set_us_off()
                return True

def move_on_edge(collision_distance=collision_avoidance_distance, time_to_settle=4, time_out=None):
    start_time = int(time())
    print('move on edge')
    color.mode = 'COL-REFLECT'
    start_motors(move_on_edge_speed)
    col_count = 0
    last_cols_sampled = [0]*nbr_cols_sampled

    if collision_distance != -1:
        # robot must look in front of him, so that, when it is close to node,
        # it can detect if there is a stopped robot
        #init_eyes_motor(eyes_speed)
        #print('current eyes position = ' + str(motor_m.position))
        motor_m.run_to_abs_pos(position_sp=87)
        sleep(0.5)
        #print('current eyes position = ' + str(motor_m.position))

    while True:
        elapsed_time = int(time()) - start_time

        color_sampled = color.value()
        color_error = follow_border(color_sampled, move_on_edge_speed, True)
        last_cols_sampled[col_count] = color_sampled
        col_count = (col_count+1) % nbr_cols_sampled

        # stop when we found next marker
        # at the beginning robot slides
        # and so for a small elapsed time is not safe to check if it is outside of the black line
        if ( (elapsed_time >= time_to_settle) and is_not_color_black(last_cols_sampled) ):
            stop_motors()
            print('robot has reached the node')
            if collision_distance != -1:
                motor_m.run_to_abs_pos(position_sp=0)
                sleep(0.7)
            #set_us_off()
            return False

        if collision_distance != -1:
            us_value = look()
            if ( us_value <= collision_distance ):
                stop_motors()
                print('a stopped robot has been detected at ' + str(us_value) + ' mm \nstop')
                # close eyes and reset them to their start position
                motor_m.run_to_abs_pos(position_sp=0)
                sleep(0.7) # time to move eyes
                #set_us_off()
                return True

        if ( (time_out != None) and (elapsed_time >= time_out) ):
            stop_motors()
            return False

def follower_init():
    print('became follower\n')
    cross_marker()
    rotate_over_node()
    cross_marker()
    move_on_edge()

def is_leader_moving():
    print('check if leader is moving')
    max_nbr_checks = 2

    check_done = 0
    motor_m.run_to_abs_pos(position_sp = 90)
    while check_done < max_nbr_checks:
        check_done += 1
        print('check nbr ' + str(check_done))
        # wait to complete eyes movement
        # but also to allow leader to increase the distance, if it is moving
        sleep(1.5)
        robot_detected = is_there_close_robot(-1, distance = collision_avoidance_distance)

        if not robot_detected:
            print('leader goes on, follow it')
            motor_m.run_to_abs_pos(position_sp = 0)
            # if leader is moving the first follower exits the while after one check
            # then it starts move
            # a possible second follower exits after two checks
            return True

    # two checks have been performed but the front robot is still stopped
    motor_m.run_to_abs_pos(position_sp = 0)
    sleep(0.8) # while eyes moving
    print('leader is stopped')
    return False

def enter_node_CW():
    print('enters the node')
    # check if another robot is already arrived in CW direction
    motor_m.run_to_abs_pos(position_sp = 40)
    sleep(2)
    robot_detected = is_there_close_robot(-1, distance = 120)

    # if no, move in the middle of the node arc
    if not robot_detected:
        cross_marker()
        rotate_over_node(time_out=4)

    #motor_m.run_to_abs_pos(position_sp = 0)
    #sleep(0.5)


text:
categories: []
comments: true
layout: post
published: true
status: publish
tags: []
title: "something more"
type: post
---

I heard this lyric from the song of Beyonce, cool. read it, u ' ll know.

Your
love goes beyond what i can say.
Love
, Beyoncei.
meanwhile, below is an article from Laure Bush to Merkel,http://www.whitehouse.org/news/2005/101005.aspmy question is that u believe it or u smart enough to figure it out.
I hate to say, but enjoying blog is also the same way to improve your english.


text:
import { WHITE, BLACK, PAWN } from './brands'
import { oppositeColor } from './util'

export const Promotion = {

	square(position) {
		const color = oppositeColor(position.activeColor);
		for (var pawn of position.pieces({ brand: PAWN, color })) {
			const square = position.pieceCoords(pawn);
			if (square.y === Promotion.rank(color)) {
				return square;
			}
		}
		return null;
	},

	rank(color) {switch (color) {
		case WHITE: return 0;
		case BLACK: return 7;
	}},

};


text:
package pico.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

/**
 * Created by tungtt on 12/20/13.
 */
public class NioServer implements Runnable {
    // The host:port combination to listen on
    private InetAddress hostAddress;
    private int port;

    // The channel on which we'll accept connections
    private ServerSocketChannel serverChannel;

    // The selector we'll be monitoring
    private Selector selector;

    // The buffer into which we'll read data when it's available
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);

    private EchoWorker worker;

    public NioServer(InetAddress hostAddress, int port, EchoWorker worker) throws IOException {
        this.hostAddress = hostAddress;
        this.port = port;
        this.selector = this.initSelector();
        this.worker = worker;
    }

    public static void main(String[] args) {
        try {
            EchoWorker worker = new EchoWorker();
            new Thread(worker).start();
            new Thread(new NioServer(null, 9090, worker)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            try {
                // Wait for an event one of the registered channels
                this.selector.select();

                // Iterate over the set of keys for which events are available
                Iterator selectedKeys = this.selector.selectedKeys().iterator();
                while (selectedKeys.hasNext()) {
                    SelectionKey key = (SelectionKey) selectedKeys.next();
                    selectedKeys.remove();

                    if (!key.isValid()) {
                        continue;
                    }

                    // Check what event is available and deal with it
                    if (key.isAcceptable()) {
                        this.accept(key);
                    } else if (key.isReadable()) {
                        this.read(key);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Selector initSelector() throws IOException {
        // Create a new selector
        Selector socketSelector = SelectorProvider.provider().openSelector();

        // Create a new non-blocking server socket channel
        this.serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);

        // Bind the server socket to the specified address and port
        InetSocketAddress isa = new InetSocketAddress(this.hostAddress, this.port);
        serverChannel.socket().bind(isa);

        // Register the server socket channel, indicating an interest in
        // accepting new connections
        serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);

        return socketSelector;
    }

    private void accept(SelectionKey key) throws IOException {
        // For an accept to be pending the channel must be a server socket channel.
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

        // Accept the connection and make it non-blocking
        SocketChannel socketChannel = serverSocketChannel.accept();
        Socket socket = socketChannel.socket();
        socketChannel.configureBlocking(false);

        // Register the new SocketChannel with our Selector, indicating
        // we'd like to be notified when there's data waiting to be read
        socketChannel.register(this.selector, SelectionKey.OP_READ);
    }

    private void read(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();

        // Clear out our read buffer so it's ready for new data
        this.readBuffer.clear();

        // Attempt to read off the channel
        int numRead;
        try {
            numRead = socketChannel.read(this.readBuffer);
        } catch (IOException e) {
            // The remote forcibly closed the connection, cancel
            // the selection key and close the channel.
            key.cancel();
            socketChannel.close();
            return;
        }

        if (numRead == -1) {
            // Remote entity shut the socket down cleanly. Do the
            // same from our end and cancel the channel.
            key.channel().close();
            key.cancel();
            return;
        }

        // Hand the data off to our worker thread
        this.worker.processData(this, socketChannel, this.readBuffer.array(), numRead);
    }
}


text:
"""Returns task instances given the task name."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import configure_finetuning
from finetune.classification import classification_tasks
from finetune.qa import qa_tasks
from finetune.tagging import tagging_tasks
from model import tokenization

def get_tasks(config: configure_finetuning.FinetuningConfig):
  tokenizer = tokenization.FullTokenizer(vocab_file=config.vocab_file,
                                         do_lower_case=config.do_lower_case)
  return [get_task(config, task_name, tokenizer)
          for task_name in config.task_names]

def get_task(config: configure_finetuning.FinetuningConfig, task_name,
             tokenizer):
  """Get an instance of a task based on its name."""
  if task_name == "cola":
    return classification_tasks.CoLA(config, tokenizer)
  elif task_name == "mrpc":
    return classification_tasks.MRPC(config, tokenizer)
  elif task_name == "mnli":
    return classification_tasks.MNLI(config, tokenizer)
  elif task_name == "sst":
    return classification_tasks.SST(config, tokenizer)
  elif task_name == "rte":
    return classification_tasks.RTE(config, tokenizer)
  elif task_name == "qnli":
    return classification_tasks.QNLI(config, tokenizer)
  elif task_name == "qqp":
    return classification_tasks.QQP(config, tokenizer)
  elif task_name == "sts":
    return classification_tasks.STS(config, tokenizer)
  elif task_name == "squad":
    return qa_tasks.SQuAD(config, tokenizer)
  elif task_name == "squadv1":
    return qa_tasks.SQuADv1(config, tokenizer)
  elif task_name == "newsqa":
    return qa_tasks.NewsQA(config, tokenizer)
  elif task_name == "naturalqs":
    return qa_tasks.NaturalQuestions(config, tokenizer)
  elif task_name == "triviaqa":
    return qa_tasks.TriviaQA(config, tokenizer)
  elif task_name == "searchqa":
    return qa_tasks.SearchQA(config, tokenizer)
  elif task_name == "chunk":
    return tagging_tasks.Chunking(config, tokenizer)
  else:
    raise ValueError("Unknown task " + task_name)


text:
import { Component, ViewEncapsulation } from '@angular/core';
import { AppState } from './app.service';

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [ './app.style.css' ],
  template: `<router-outlet></router-outlet>`
})
export class App {
  angularclassLogo = 'assets/img/angularclass-avatar.png';
  name = 'Angular 2 Webpack Starter';
  url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState) {

  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}


text:
using AlephNote.Log;
using MSHC.WPF.MVVM;
using System;
using System.Windows;

namespace AlephNote.WPF.Converter
{
	class LogToFontStyle : OneWayConverter<LogEventType, FontStyle>
	{
		protected override FontStyle Convert(LogEventType value, object parameter)
		{
			switch (value)
			{
				case LogEventType.Trace:       return FontStyles.Italic;
				case LogEventType.Debug:       return FontStyles.Italic;
				case LogEventType.Information: return FontStyles.Normal;
				case LogEventType.Warning:     return FontStyles.Normal;
				case LogEventType.Error:       return FontStyles.Normal;

				default:
					throw new ArgumentOutOfRangeException(nameof(value));
			}
		}
	}
}


text:
<?php

namespace Oro\Bundle\EmailBundle\Form\Type;

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

class EmailType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('gridName', 'hidden', array('required' => false))
            ->add('from', 'oro_email_email_address', array('required' => true))
            ->add('to', 'oro_email_email_address', array('required' => true, 'multiple' => true))
            ->add('subject', 'text', array('required' => true))
            ->add('body', 'textarea', array('required' => false));
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class'           => 'Oro\Bundle\EmailBundle\Form\Model\Email',
                'intention'            => 'email',
                'csrf_protection'      => true,
                'cascade_validation'   => true,
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'oro_email_email';
    }
}


text:
package de.andrew.demoZITF.myDataModels;

/**
 * Created by Andrew on 4/14/16.
 */

import java.util.ArrayList;
import java.util.List;

public class Group {

    public String string;
    public final List<String> children = new ArrayList<String>();

    public Group(String string) {
        this.string = string;
    }

}


text:
from django.db import models
from django.contrib.auth.models import User

class SmartModel(models.Model):
    """
    Useful abstract base class that adds the concept of something being active,
    having a user that created or modified the item and creation and modification
    dates.
    """
    is_active = models.BooleanField(default=True)

    created_by = models.ForeignKey(User, related_name="%(class)s_creations")
    created_on = models.DateTimeField(auto_now_add=True)

    modified_by = models.ForeignKey(User, related_name="%(class)s_modifications")
    modified_on = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class ActiveManager(models.Manager):
    """
    A manager that only selects items which are still active.
    """
    def get_query_set(self):
        """
        Where the magic happens, we automatically throw on an extra is_active = True to every filter
        """
        return super(ActiveManager, self).get_query_set().filter(is_active=True)


text:
'use strict';

module.exports = function(grunt) {

  var _ = grunt.util._;
  var path = require('path');

  grunt.registerMultiTask('html_include', 'The best Grunt plugin ever.', function() {

    var options = this.options({
      workingDir: 'src'
    });

    var includeRegExp = new RegExp('@@include\\(\\s*["\'](.*?)["\'](,\\s*({[\\s\\S]*?})){0,1}\\s*\\)');

    function replace(contents, localVars){
      localVars = localVars || {};
      var varNames = Object.keys(localVars);
      var varRegExps = {};

      varNames.forEach(function(varName) {

        varRegExps[varName] = varRegExps[varName] || new RegExp('@@' + varName + '@@', 'g');

        contents = contents.replace(varRegExps[varName], localVars[varName]);
      });

      return contents;
    }

    function include(contents, cssFileKey, isRecursion){
      var matches = includeRegExp.exec(contents);

      function createReplaceFn (replacement) {
        return function () {
          return replacement;
        };
      }

      while(matches){
        var match = matches[0];
        var includePath = matches[1];
        var localVars = matches[3] ? JSON.parse(matches[3]) : {};

        var realPath = path.resolve(path.join(options.workingDir, includePath)) + '.html';

        if(!grunt.file.isFile(realPath)){
          realPath = path.resolve('components/' + includePath) + '.html';
          try{
            if(!isRecursion){
              componentCSSContents[cssFileKey].push(grunt.file.read(path.resolve('components/' + includePath) + '.css'));
            }
          }catch(e){
          }
        }

        var includeContents = grunt.file.read(realPath);
        includeContents = replace(includeContents, localVars);

        includeContents = include(includeContents, cssFileKey, true);

        contents = contents.replace(match, createReplaceFn(includeContents));

        matches = includeRegExp.exec(contents);
      }

      return contents;
    }

    var componentCSSContents = {};

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {

      f.src.forEach(function(src){
        if(!grunt.file.isFile(src)){
          return;
        }

        componentCSSContents[src] = [];

        var contents = grunt.file.read(src);

        contents = include(contents, src, false);

        var destfile = f.dest + src.split(options.workingDir)[1];

        grunt.file.write(destfile, contents);
        grunt.file.write('css/' + src.split(options.workingDir)[1].split('.html')[0] + '.components.css', componentCSSContents[src].join('\n'));
      });

    });
  });

};


text:
package com.nightlynexus.hockey.util;

import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

public final class ViewUtils {

    public static void doOnGlobalLayout(final View view, final Runnable runnable) {
        view.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                runnable.run();
            }
        });
    }

    public static void setViewBackground(final View view, final Drawable drawable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(drawable);
        } else {
            view.setBackgroundDrawable(drawable);
        }
    }

    public static void setImageAlpha(ImageView imageView, int alpha) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            imageView.setImageAlpha(alpha);
        } else {
            imageView.setAlpha(alpha);
        }
    }

    // ripple for >=L, else default to StateListDrawable
    public static Drawable getPressedColorSelector(final int colorValue) {
        return getPressedColorSelector(colorValue, new ColorDrawable(colorValue));
    }

    // Drawable is mask for >=L, else is the pressed Drawable
    public static Drawable getPressedColorSelector(int colorValue, Drawable mask) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new RippleDrawable(new ColorStateList(new int[][] { {} },
                    new int[] {colorValue}), null, mask);
        } else {
            final StateListDrawable sld = new StateListDrawable();
            sld.addState(new int[] { android.R.attr.state_pressed }, mask);
            sld.setColorFilter(colorValue, PorterDuff.Mode.SRC_IN);
            return sld;
        }
    }
}


text:
<!doctype html>

	<meta charset="utf-8">

	<link rel="stylesheet" href="../../../../docs/style.css">

timelinefx:timelinefx.tlCollisionResult.RayIntersection

Property RayIntersection:tlVector2

Get the intersection point of the raycast
If a ray cast has been performed and the ray successfully connected, then this will return the point of intersection as a tlVector2.


text:
#include "OgitorsPrerequisites.h"
#include "BaseEditor.h"
#include "OgitorsRoot.h"
#include "SceneManagerEditor.h"
#include "tinyxml.h"

using namespace Ogitors;

Ogre::String   OgitorsUtils::mExePath = "";
unsigned int   OgitorsUtils::mVertexBufferSize = 0;
unsigned int   OgitorsUtils::mIndexBufferSize = 0;
Ogre::Vector3 *OgitorsUtils::mVertexBuffer = 0;
unsigned long *OgitorsUtils::mIndexBuffer = 0;

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
#endif

//-----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetMacBundlePath()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
    char path[1024];
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    assert(mainBundle);

    CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
    assert(mainBundleURL);

    CFStringRef cfStringRef = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
    assert(cfStringRef);

    CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);

    CFRelease(mainBundleURL);
    CFRelease(cfStringRef);

    return Ogre::String(path);
#else
    return "";
#endif
}
//-----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetEditorResourcesPath()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
	  return QualifyPath(GetMacBundlePath() + "/Contents/Resources/Media/EditorResources");
#else
	  return QualifyPath("../Media/EditorResources");
#endif
}
//-----------------------------------------------------------------------------------------
void OgitorsUtils::ParseStringVector(Ogre::String &str, Ogre::StringVector &list)
{
    list.clear();
    Ogre::StringUtil::trim(str,true,true);
    if(str == "")
        return;

    int pos = str.find(";");
    while(pos != -1)
    {
        list.push_back(str.substr(0,pos));
        str.erase(0,pos + 1);
        pos = str.find(";");
    }

    if(str != "")
        list.push_back(str);
}
//-----------------------------------------------------------------------------------------
void OgitorsUtils::ParseUTFStringVector(Ogre::UTFString &str, UTFStringVector &list)
{
    list.clear();
    if(str == "")
        return;

    int pos = str.find(";");
    while(pos != -1)
    {
        list.push_back(str.substr(0,pos));
        str.erase(0,pos + 1);
        pos = str.find(";");
    }

    if(str != "")
        list.push_back(str);
}
//-----------------------------------------------------------------------------------------
void OgitorsUtils::CleanPath(Ogre::String &path)
{
    std::replace( path.begin(), path.end(), '\\', '/' );

    int pos = 0;
    pos = path.find("//",0);
    while(pos != -1)
    {
        path.erase(pos,1);
        pos = path.find("//",0);
    }

    pos = path.find("/./",0);
    while(pos != -1)
    {
        path.erase(pos,2);
        pos = path.find("/./",0);
    }
}
//-----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::ExtractFileName(const Ogre::String &path)
{
    int pos1 = -1, pos2 = -1;
    Ogre::String strName = path;
    pos1 = path.find_last_of("\\");
    pos2 = path.find_last_of("/");

    int pos = std::max(pos1,pos2);

    if(pos != -1)
    {
        strName = path.substr(pos + 1,path.size() - (pos + 1));
    }

    return strName;
}
//-----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::ExtractFilePath(const Ogre::String &path)
{
    int pos1 = -1, pos2 = -1;
    Ogre::String strName = "";
    pos1 = path.find_last_of("\\");
    pos2 = path.find_last_of("/");

    int pos = std::max(pos1,pos2);

    if(pos != -1)
    {
        strName = path.substr(0,pos + 1);
    }

    return strName;
}
//-----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::QualifyPath(const Ogre::String &dirname)
{
    Ogre::String path = dirname;
    if(path.substr(0,1) == ".") path = mExePath + "/" + path;

    std::replace(path.begin(),path.end(),'\\','/');

    // Remember if there is a leading '/'
    bool leadingSlash = false;
    if(path.substr(0,1) == "/")
        leadingSlash = true;

    Ogre::StringVector list;
    int pos = path.find("/");
    while(pos != -1)
    {
        if(pos > 0 && path.substr(0,pos) != ".")  // Ignore zero strings and same directory pointers
            list.push_back(path.substr(0,pos));
        path.erase(0,pos + 1);
        pos = path.find("/");
    }

    if(path != "")
        list.push_back(path);

    unsigned int pos2 = 0;
    while(list.size() > pos2)
    {
        if(list[pos2] == "..")
        {
              list.erase(list.begin() + pos2 - 1,list.begin() + pos2 + 1);
            pos2--;
        }
        else
            pos2++;
    }

    if(list.size() == 0)
        return "";

    path = list[0];

    for(unsigned int i = 1;i < list.size();i++)
    {
        path += "/" + list[i];
    }

    if(leadingSlash)
        path = "/" + path;

    return path;
}
//-----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetRelativePath(const Ogre::String pathFrom,const Ogre::String pathTo)
{
    Ogre::String sFrom = QualifyPath(pathFrom);
    Ogre::String sTo = QualifyPath(pathTo);

    Ogre::String sFromFirst = sFrom.substr(0,1);
    Ogre::String sToFirst = sTo.substr(0,1);
    Ogre::StringUtil::toLowerCase(sFromFirst);
    Ogre::StringUtil::toLowerCase(sToFirst);

    if( sFromFirst != sToFirst) return sTo;

    Ogre::StringVector listfrom;
    int pos = sFrom.find("/");
    while(pos != -1)
    {
        listfrom.push_back(sFrom.substr(0,pos));
        sFrom.erase(0,pos + 1);
        pos = sFrom.find("/");
    }

    if(sFrom != "")
        listfrom.push_back(sFrom);

    Ogre::StringVector listto;
    pos = sTo.find("/");
    while(pos != -1)
    {
        listto.push_back(sTo.substr(0,pos));
        sTo.erase(0,pos + 1);
        pos = sTo.find("/");
    }

    if(sTo != "")
        listto.push_back(sTo);

    unsigned int length = std::min(listfrom.size(), listto.size());

    unsigned int i;
    for(i = 0;i < length;i++)
    {
        Ogre::String valFrom = listfrom[i];
        Ogre::String valTo = listto[i];
        Ogre::StringUtil::toLowerCase(valFrom);
        Ogre::StringUtil::toLowerCase(valTo);
        if(valTo != valFrom)
            break;
    }

    listfrom.erase(listfrom.begin(),listfrom.begin() + i);
    listto.erase(listto.begin(),listto.begin() + i);

    if(listfrom.size() == 0 && listto.size() == 0)
        return "./";

    Ogre::String strRet = "";
    for(i = 0;i < listfrom.size();i++)
        strRet += "../";

    if(strRet.length() == 0)
        strRet = "./";

    for(i = 0;i < listto.size();i++)
        strRet += listto[i] + "/";

    if(listto.size())
    {
        strRet.erase(strRet.size() - 1,1);
    }
    return strRet;
}
//-----------------------------------------------------------------------------------------
void OgitorsUtils::GetMeshData(const Ogre::MeshPtr mesh, size_t &vertex_count, size_t &index_count,
                               const Ogre::Vector3 &position, const Ogre::Quaternion &orient, const Ogre::Vector3 &scale)
{
    bool added_shared = false;
    size_t current_offset = 0;
    size_t shared_offset = 0;
    size_t next_offset = 0;
    size_t index_offset = 0;

    vertex_count = index_count = 0;

    // Calculate how many vertices and indices we're going to need
    for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
    {
        Ogre::SubMesh* submesh = mesh->getSubMesh( i );

        // We only need to add the shared vertices once
        if(submesh->useSharedVertices)
        {
            if( !added_shared )
            {
                vertex_count += mesh->sharedVertexData->vertexCount;
                added_shared = true;
            }
        }
        else
        {
            vertex_count += submesh->vertexData->vertexCount;
        }

        // Add the indices
        index_count += submesh->indexData->indexCount;
    }

    if(vertex_count > mVertexBufferSize)
    {
        OGRE_FREE(mVertexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
        mVertexBuffer = OGRE_ALLOC_T(Ogre::Vector3,vertex_count, Ogre::MEMCATEGORY_GEOMETRY);
        mVertexBufferSize = vertex_count;
    }

    if(index_count > mIndexBufferSize)
    {
        OGRE_FREE(mIndexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
        mIndexBuffer = OGRE_ALLOC_T(unsigned long,index_count, Ogre::MEMCATEGORY_GEOMETRY);
        mIndexBufferSize = index_count;
    }

    added_shared = false;

    // Run through the submeshes again, adding the data into the arrays
    for ( unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
    {
        Ogre::SubMesh* submesh = mesh->getSubMesh(i);

        Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData;

        if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared))
        {
            if(submesh->useSharedVertices)
            {
              added_shared = true;
              shared_offset = current_offset;
            }

            const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION);

            Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource());

            unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));

            // There is _no_ baseVertexPointerToElement() which takes an Ogre::Real or a double
            //  as second argument. So make it float, to avoid trouble when Ogre::Real will
            //  be comiled/typedefed as double:
            //      Ogre::Real* pReal;
            float* pReal;

            for( size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize())
            {
                posElem->baseVertexPointerToElement(vertex, &pReal);

                Ogre::Vector3 pt(pReal[0], pReal[1], pReal[2]);

                mVertexBuffer[current_offset + j] = (orient * (pt * scale)) + position;
            }

            vbuf->unlock();
            next_offset += vertex_data->vertexCount;
        }

        Ogre::IndexData* index_data = submesh->indexData;
        size_t numTris = index_data->indexCount / 3;
        Ogre::HardwareIndexBufferSharedPtr ibuf = index_data->indexBuffer;

        bool use32bitindexes = (ibuf->getType() == Ogre::HardwareIndexBuffer::IT_32BIT);

        unsigned long*  pLong = static_cast<unsigned long*>(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));
        unsigned short* pShort = reinterpret_cast<unsigned short*>(pLong);

        size_t offset = (submesh->useSharedVertices)? shared_offset : current_offset;

        if ( use32bitindexes )
        {
            for ( size_t k = 0; k < numTris*3; ++k)
            {
                mIndexBuffer[index_offset++] = pLong[k] + static_cast<unsigned long>(offset);
            }
        }
        else
        {
            for ( size_t k = 0; k < numTris*3; ++k)
            {
                mIndexBuffer[index_offset++] = static_cast<unsigned long>(pShort[k]) + static_cast<unsigned long>(offset);
            }
        }

        ibuf->unlock();
        current_offset = next_offset;
    }
    index_count = index_offset;
}
//-----------------------------------------------------------------------------------------
void OgitorsUtils::GetMeshDataEx(const Ogre::Entity *entity, size_t &vertex_count, size_t &index_count,
                               const Ogre::Vector3 &position, const Ogre::Quaternion &orient, const Ogre::Vector3 &scale)
{
    bool added_shared = false;
    size_t current_offset = 0;
    size_t shared_offset = 0;
    size_t next_offset = 0;
    size_t index_offset = 0;

    vertex_count = index_count = 0;

    Ogre::MeshPtr mesh = entity->getMesh();

    // Calculate how many vertices and indices we're going to need
    for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
    {
        Ogre::SubMesh* submesh = mesh->getSubMesh( i );

        // We only need to add the shared vertices once
        if(submesh->useSharedVertices)
        {
            if( !added_shared )
            {
                vertex_count += mesh->sharedVertexData->vertexCount;
                added_shared = true;
            }
        }
        else
        {
            vertex_count += submesh->vertexData->vertexCount;
        }

        // Add the indices
        index_count += submesh->indexData->indexCount;
    }

    if(vertex_count > mVertexBufferSize)
    {
        OGRE_FREE(mVertexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
        mVertexBuffer = OGRE_ALLOC_T(Ogre::Vector3,vertex_count, Ogre::MEMCATEGORY_GEOMETRY);
        mVertexBufferSize = vertex_count;
    }

    if(index_count > mIndexBufferSize)
    {
        OGRE_FREE(mIndexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
        mIndexBuffer = OGRE_ALLOC_T(unsigned long,index_count, Ogre::MEMCATEGORY_GEOMETRY);
        mIndexBufferSize = index_count;
    }

    added_shared = false;

    // Run through the submeshes again, adding the data into the arrays
    for ( unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
    {
        if(!entity->getSubEntity(i)->isVisible())
            continue;

        Ogre::SubMesh* submesh = mesh->getSubMesh(i);

        Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData;

        if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared))
        {
            if(submesh->useSharedVertices)
            {
              added_shared = true;
              shared_offset = current_offset;
            }

            const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION);

            Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource());

            unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));

            // There is _no_ baseVertexPointerToElement() which takes an Ogre::Real or a double
            //  as second argument. So make it float, to avoid trouble when Ogre::Real will
            //  be comiled/typedefed as double:
            //      Ogre::Real* pReal;
            float* pReal;

            for( size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize())
            {
                posElem->baseVertexPointerToElement(vertex, &pReal);

                Ogre::Vector3 pt(pReal[0], pReal[1], pReal[2]);

                mVertexBuffer[current_offset + j] = (orient * (pt * scale)) + position;
            }

            vbuf->unlock();
            next_offset += vertex_data->vertexCount;
        }

        Ogre::IndexData* index_data = submesh->indexData;
        size_t numTris = index_data->indexCount / 3;
        Ogre::HardwareIndexBufferSharedPtr ibuf = index_data->indexBuffer;

        bool use32bitindexes = (ibuf->getType() == Ogre::HardwareIndexBuffer::IT_32BIT);

        unsigned long*  pLong = static_cast<unsigned long*>(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));
        unsigned short* pShort = reinterpret_cast<unsigned short*>(pLong);

        size_t offset = (submesh->useSharedVertices)? shared_offset : current_offset;

        if ( use32bitindexes )
        {
            for ( size_t k = 0; k < numTris*3; ++k)
            {
                mIndexBuffer[index_offset++] = pLong[k] + static_cast<unsigned long>(offset);
            }
        }
        else
        {
            for ( size_t k = 0; k < numTris*3; ++k)
            {
                mIndexBuffer[index_offset++] = static_cast<unsigned long>(pShort[k]) + static_cast<unsigned long>(offset);
            }
        }

        ibuf->unlock();
        current_offset = next_offset;
    }
    index_count = index_offset;
}
//-----------------------------------------------------------------------------------------
bool OgitorsUtils::PickEntity(Ogre::Ray &ray, Ogre::Entity **result, Ogre::Vector3 &hitpoint, const Ogre::String& excludeobject, Ogre::Real max_distance)
{
    Ogre::RaySceneQuery *mRaySceneQuery = OgitorsRoot::getSingletonPtr()->GetSceneManagerEditor()->getRayQuery();
    mRaySceneQuery->setRay(ray);
    mRaySceneQuery->setQueryMask(QUERYFLAG_MOVABLE);
    mRaySceneQuery->setSortByDistance(true);

    unsigned int mVisibilityMask = OgitorsRoot::getSingletonPtr()->GetSceneManager()->getVisibilityMask();

    if (mRaySceneQuery->execute().size() <= 0) return (false);

    // at this point we have raycast to a series of different objects bounding boxes.
    // we need to test these different objects to see which is the first polygon hit.
    // there are some minor optimizations (distance based) that mean we wont have to
    // check all of the objects most of the time, but the worst case scenario is that
    // we need to test every triangle of every object.
    Ogre::Real closest_distance = max_distance;
    Ogre::Vector3 closest_result;
    Ogre::RaySceneQueryResult &query_result = mRaySceneQuery->getLastResults();

    for (size_t qr_idx = 0; qr_idx < query_result.size(); qr_idx++)
    {
        // stop checking if we have found a raycast hit that is closer
        // than all remaining entities
        if ((closest_distance >= 0.0f) && (closest_distance < query_result[qr_idx].distance))
            break;

        // only check this result if its a hit against an entity
        if ((query_result[qr_idx].movable != NULL) && (query_result[qr_idx].movable->getMovableType().compare("Entity") == 0))
        {
            // get the entity to check
            Ogre::Entity *pentity = static_cast<Ogre::Entity*>(query_result[qr_idx].movable);

            if(!(pentity->getVisibilityFlags() & mVisibilityMask))
                continue;

            if(!pentity->getVisible() || (pentity->getName() == excludeobject))
                continue;

            // mesh data to retrieve
            size_t vertex_count;
            size_t index_count;

            // get the mesh information
            GetMeshData(pentity->getMesh(), vertex_count, index_count,
                        pentity->getParentNode()->_getDerivedPosition(),
                        pentity->getParentNode()->_getDerivedOrientation(),
                        pentity->getParentNode()->_getDerivedScale());

            // test for hitting individual triangles on the mesh
            bool new_closest_found = false;
            for (int i = 0; i < static_cast<int>(index_count); i += 3)
            {
                assert(mIndexBuffer[i] < vertex_count);
                assert(mIndexBuffer[i + 1] < vertex_count);
                assert(mIndexBuffer[i + 2] < vertex_count);
                // check for a hit against this triangle
                std::pair<bool, Ogre::Real> hit = Ogre::Math::intersects(ray, mVertexBuffer[mIndexBuffer[i]],
                         mVertexBuffer[mIndexBuffer[i+1]], mVertexBuffer[mIndexBuffer[i+2]], true, false);

                // if it was a hit check if its the closest
                if (hit.first)
                {
                    if ((closest_distance < 0.0f) || (hit.second < closest_distance))
                    {
                        // this is the closest so far, save it off
                        closest_distance = hit.second;
                        new_closest_found = true;
                    }
                }
            }

            // if we found a new closest raycast for this object, update the
            // closest_result before moving on to the next object.
            if (new_closest_found)
            {
                closest_result = ray.getPoint(closest_distance);
                (*result) = pentity;
            }
        }
    }

    // return the result
    if (closest_distance != max_distance)
    {
        hitpoint = closest_result;
        return (true);
    }
    else
    {
        // raycast failed
        return (false);
    }
}
//-----------------------------------------------------------------------------------------
bool OgitorsUtils::PickEntity(Ogre::Ray &ray, Ogre::Entity **result, Ogre::Vector3 &hitpoint, const Ogre::StringVector& excludeobjects, Ogre::Real max_distance)
{
    Ogre::RaySceneQuery *mRaySceneQuery = OgitorsRoot::getSingletonPtr()->GetSceneManagerEditor()->getRayQuery();
    mRaySceneQuery->setRay(ray);
    mRaySceneQuery->setQueryMask(QUERYFLAG_MOVABLE);
    mRaySceneQuery->setSortByDistance(true);

    unsigned int mVisibilityMask = OgitorsRoot::getSingletonPtr()->GetSceneManager()->getVisibilityMask();

    if (mRaySceneQuery->execute().size() <= 0) return (false);

    // at this point we have raycast to a series of different objects bounding boxes.
    // we need to test these different objects to see which is the first polygon hit.
    // there are some minor optimizations (distance based) that mean we wont have to
    // check all of the objects most of the time, but the worst case scenario is that
    // we need to test every triangle of every object.
    Ogre::Real closest_distance = max_distance;
    Ogre::Vector3 closest_result;
    Ogre::RaySceneQueryResult &query_result = mRaySceneQuery->getLastResults();

    for (size_t qr_idx = 0; qr_idx < query_result.size(); qr_idx++)
    {
        // stop checking if we have found a raycast hit that is closer
        // than all remaining entities
        if ((closest_distance >= 0.0f) && (closest_distance < query_result[qr_idx].distance))
        {
            break;
        }

        // only check this result if its a hit against an entity
        if ((query_result[qr_idx].movable != NULL) && (query_result[qr_idx].movable->getMovableType().compare("Entity") == 0))
        {
            // get the entity to check
            Ogre::Entity *pentity = static_cast<Ogre::Entity*>(query_result[qr_idx].movable);

            if(!(pentity->getVisibilityFlags() & mVisibilityMask))
                continue;

            if(!pentity->getVisible())
                continue;

            Ogre::String pname = pentity->getName();

            bool foundinlist = false;
            for(unsigned int lit = 0;lit < excludeobjects.size();lit++)
            {
                if(excludeobjects[lit] == pname)
                {
                    foundinlist = true;
                    break;
                }
            }

            if(foundinlist)
                continue;

            // mesh data to retrieve
            size_t vertex_count;
            size_t index_count;

            // get the mesh information
            GetMeshData(pentity->getMesh(), vertex_count, index_count,
                        pentity->getParentNode()->_getDerivedPosition(),
                        pentity->getParentNode()->_getDerivedOrientation(),
                        pentity->getParentNode()->_getDerivedScale());

            // test for hitting individual triangles on the mesh
            bool new_closest_found = false;
            for (int i = 0; i < static_cast<int>(index_count); i += 3)
            {
                // check for a hit against this triangle
                std::pair<bool, Ogre::Real> hit = Ogre::Math::intersects(ray, mVertexBuffer[mIndexBuffer[i]],
                         mVertexBuffer[mIndexBuffer[i+1]], mVertexBuffer[mIndexBuffer[i+2]], true, false);

                // if it was a hit check if its the closest
                if (hit.first)
                {
                    if ((closest_distance < 0.0f) || (hit.second < closest_distance))
                    {
                        // this is the closest so far, save it off
                        closest_distance = hit.second;
                        new_closest_found = true;
                    }
                }
            }

            // if we found a new closest raycast for this object, update the
            // closest_result before moving on to the next object.
            if (new_closest_found)
            {
                closest_result = ray.getPoint(closest_distance);
                (*result) = pentity;
            }
        }
    }

    // return the result
    if (closest_distance != max_distance)
    {
        hitpoint = closest_result;
        return (true);
    }
    else
    {
        // raycast failed
        return (false);
    }
}
//-----------------------------------------------------------------------------------------
int OgitorsUtils::PickSubMesh(Ogre::Ray& ray, Ogre::Entity* pEntity)
{
    // at this point we have raycast to a series of different objects bounding boxes.
    // we need to test these different objects to see which is the first polygon hit.
    // there are some minor optimizations (distance based) that mean we wont have to
    // check all of the objects most of the time, but the worst case scenario is that
    // we need to test every triangle of every object.
    Ogre::Real closest_distance = -1.0f;
    int closest_index = -1;
    Ogre::Vector3 closest_result;
    int closest_submesh = -1;

    // mesh data to retrieve
    size_t vertex_count;
    size_t index_count;

    // get the mesh information
    GetMeshData(pEntity->getMesh(), vertex_count, index_count,
                pEntity->getParentNode()->_getDerivedPosition(),
                pEntity->getParentNode()->_getDerivedOrientation(),
                pEntity->getParentNode()->_getDerivedScale());

    // test for hitting individual triangles on the mesh
    for (int i = 0; i < static_cast<int>(index_count); i += 3)
    {
        // check for a hit against this triangle
        std::pair<bool, Ogre::Real> hit = Ogre::Math::intersects(ray, mVertexBuffer[mIndexBuffer[i]],
                 mVertexBuffer[mIndexBuffer[i+1]], mVertexBuffer[mIndexBuffer[i+2]], true, false);

        // if it was a hit check if its the closest
        if (hit.first)
        {
            if ((closest_distance < 0.0f) || (hit.second < closest_distance))
            {
                // this is the closest so far, save it off
                closest_distance = hit.second;
                closest_index = i;
            }
        }
    }

    if(closest_index > -1)
    {
        int index_pos = 0;
        for (unsigned short sm = 0; sm < pEntity->getMesh()->getNumSubMeshes(); ++sm)
        {
            index_pos += pEntity->getMesh()->getSubMesh( sm )->indexData->indexCount;
            if(closest_index < index_pos)
                return sm;
        }
    }
    return -1;
}
//-----------------------------------------------------------------------------------------
bool OgitorsUtils::WorldIntersect(Ogre::Ray &ray, Ogre::Vector3 &hitposition)
{
    Ogre::RaySceneQuery *mRaySceneQuery = OgitorsRoot::getSingletonPtr()->GetSceneManagerEditor()->getRayQuery();
    mRaySceneQuery->setRay(ray);
    mRaySceneQuery->setQueryTypeMask(Ogre::SceneManager::WORLD_GEOMETRY_TYPE_MASK);
    mRaySceneQuery->setWorldFragmentType(Ogre::SceneQuery::WFT_SINGLE_INTERSECTION);
    Ogre::RaySceneQueryResult& qryResult = mRaySceneQuery->execute();
    Ogre::RaySceneQueryResult::iterator i = qryResult.begin();
    if (i != qryResult.end() && i->worldFragment)
    {
        hitposition = i->worldFragment->singleIntersection;
        return true;
    }
    return false;
}
//----------------------------------------------------------------------------------------
void OgitorsUtils::SphereQuery(CBaseEditor *object, Ogre::Real radius, ObjectVector &results)
{
    results.clear();

    if(!object)
        return;

    Ogre::Sphere sphere(object->getDerivedPosition(), radius);
    Ogre::SphereSceneQuery *mSphereQuery = OgitorsRoot::getSingletonPtr()->GetSceneManagerEditor()->getSphereQuery();
    mSphereQuery->setSphere(sphere);
    mSphereQuery->setQueryMask(QUERYFLAG_MOVABLE);

    unsigned int mVisibilityMask = OgitorsRoot::getSingletonPtr()->GetSceneManager()->getVisibilityMask();

    Ogre::SceneQueryResult& qryResult = mSphereQuery->execute();
    Ogre::SceneQueryResultMovableList::iterator it;
    Ogre::SceneQueryResultMovableList::iterator it_end = qryResult.movables.end();

    for(it = qryResult.movables.begin();it != it_end;it++)
    {
        Ogre::MovableObject *entity = (*it);

        if (entity->getMovableType().compare("Entity") == 0)
        {
            // get the entity to check
            Ogre::Entity *pentity = static_cast<Ogre::Entity*>(entity);

            if(!pentity->getVisible() || !(pentity->getVisibilityFlags() & mVisibilityMask))
                continue;

            CBaseEditor *fobject = OgitorsRoot::getSingletonPtr()->FindObject(pentity->getName());

            if(fobject != 0 && fobject != object)
                results.push_back(fobject);
        }
    }
}
//----------------------------------------------------------------------------------------
void OgitorsUtils::SphereQuery(const Ogre::Vector3& pos, Ogre::Real radius, ObjectVector &results)
{
    results.clear();

    Ogre::SphereSceneQuery *mSphereQuery = OgitorsRoot::getSingletonPtr()->GetSceneManagerEditor()->getSphereQuery();
    Ogre::Sphere sphere(pos, radius);
    mSphereQuery->setSphere(sphere);
    mSphereQuery->setQueryMask(QUERYFLAG_MOVABLE);

    unsigned int mVisibilityMask = OgitorsRoot::getSingletonPtr()->GetSceneManager()->getVisibilityMask();

    Ogre::SceneQueryResult& qryResult = mSphereQuery->execute();
    Ogre::SceneQueryResultMovableList::iterator it;
    Ogre::SceneQueryResultMovableList::iterator it_end = qryResult.movables.end();

    for(it = qryResult.movables.begin();it != it_end;it++)
    {
        Ogre::MovableObject *entity = (*it);

        if (entity->getMovableType().compare("Entity") == 0)
        {
            // get the entity to check
            Ogre::Entity *pentity = static_cast<Ogre::Entity*>(entity);

            if(!pentity->getVisible() || !(pentity->getVisibilityFlags() & mVisibilityMask))
                continue;

            CBaseEditor *fobject = OgitorsRoot::getSingletonPtr()->FindObject(pentity->getName());

            if(fobject)
                results.push_back(fobject);
        }
    }
}
//----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetValueString(OgitorsPropertyValue& value)
{
    switch(value.propType)
    {
    case PROP_SHORT:
        return Ogre::StringConverter::toString(Ogre::any_cast<short>(value.val));
    case PROP_UNSIGNED_SHORT:
        return Ogre::StringConverter::toString(Ogre::any_cast<unsigned short>(value.val));
    case PROP_INT:
        return Ogre::StringConverter::toString(Ogre::any_cast<int>(value.val));
    case PROP_UNSIGNED_INT:
        return Ogre::StringConverter::toString(Ogre::any_cast<unsigned int>(value.val));
    case PROP_LONG:
        return Ogre::StringConverter::toString(Ogre::any_cast<long>(value.val));
    case PROP_UNSIGNED_LONG:
        return Ogre::StringConverter::toString(Ogre::any_cast<unsigned long>(value.val));
    case PROP_REAL:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Real>(value.val));
    case PROP_STRING:
        return Ogre::any_cast<Ogre::String>(value.val);
    case PROP_VECTOR2:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Vector2>(value.val));
    case PROP_VECTOR3:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Vector3>(value.val));
    case PROP_VECTOR4:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Vector4>(value.val));
    case PROP_COLOUR:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::ColourValue>(value.val));
    case PROP_BOOL:
        return Ogre::StringConverter::toString(Ogre::any_cast<bool>(value.val));
    case PROP_QUATERNION:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Quaternion>(value.val));
    case PROP_MATRIX3:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Matrix3>(value.val));
    case PROP_MATRIX4:
        return Ogre::StringConverter::toString(Ogre::any_cast<Ogre::Matrix4>(value.val));
    };
    return "";
}
//----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetCustomPropertySaveString(OgitorsCustomPropertySet *set, int indentation)
{
    Ogre::String buffer = "";

    if(!set)
        return "";

    Ogre::String indentStr = "";

    for(int k = 0; k < indentation;k++)
        indentStr += " ";

    buffer += indentStr + "<CUSTOMPROPERTIES>\n";
    OgitorsPropertyVector vec = set->getPropertyVector();

    for(unsigned int i = 0;i < vec.size();i++)
    {
        OgitorsPropertyBase *property = vec[i];
        const OgitorsPropertyDef *def = property->getDefinition();
        OgitorsPropertyValue value;
        value.propType = property->getType();
        value.val = property->getValue();

        buffer += indentStr + "  <PROPERTY id=\"" + property->getName() + "\"";
        buffer += " type=\"" + Ogre::StringConverter::toString(value.propType) + "\"";
        buffer += " value=\"" + GetValueString(value) + "\"";

        switch(value.propType)
        {
        case PROP_VECTOR2:
            {
                if(def->fieldName(0) != "X" || def->fieldName(1) != "Y")
                    buffer += " fields=\"" + def->fieldName(0) + ";" + def->fieldName(1) + "\"";
                break;
            }
        case PROP_VECTOR3:
            {
                if(def->fieldName(0) != "X" || def->fieldName(1) != "Y" || def->fieldName(2) != "Z")
                    buffer += " fields=\"" + def->fieldName(0) + ";" + def->fieldName(1) + ";" + def->fieldName(2) + "\"";
                break;
            }
        case PROP_VECTOR4:
            {
                if(def->fieldName(0) != "X" || def->fieldName(1) != "Y" || def->fieldName(2) != "Z" || def->fieldName(0) != "W")
                    buffer += " fields=\"" + def->fieldName(0) + ";" + def->fieldName(1) + ";" + def->fieldName(2) + ";" + def->fieldName(3) + "\"";
                break;
            }
        }

        buffer += " autooptiontype=\"" + Ogre::StringConverter::toString(def->getAutoOptionType()) + "\"";

        const PropertyOptionsVector *opt = def->getOptions();

        if(def->getAutoOptionType() == AUTO_OPTIONS_NONE && opt != NULL)
        {
            buffer += " options=\"";
            for(unsigned int o = 0;o < (*opt).size();o++)
            {
                value.val = (*opt)[o].mValue;
                buffer += (*opt)[o].mKey + ";";
                buffer += GetValueString(value) + ";";
            }
            buffer += "\"";
        }

        buffer += "></PROPERTY>\n";
    }

    buffer += indentStr + "</CUSTOMPROPERTIES>\n";
    return buffer;
}
//----------------------------------------------------------------------------------------
void OgitorsUtils::ReadCustomPropertySet(TiXmlElement *element, OgitorsCustomPropertySet *set)
{
    Ogre::String elementName;

    TiXmlElement *properties = element->FirstChildElement();
    if(!properties)
        return;

    OgitorsPropertyDef *def;
    do
    {
        elementName = properties->Value();
        if(elementName != "PROPERTY")
            continue;

        Ogre::String attID = ValidAttr(properties->Attribute("id"),"");
        int attType = Ogre::StringConverter::parseInt(ValidAttr(properties->Attribute("type"),""));
        Ogre::String attValue = ValidAttr(properties->Attribute("value"),"");
        Ogre::String attFields = ValidAttr(properties->Attribute("fields"),"");
        Ogre::String attOptions = ValidAttr(properties->Attribute("options"),"");
        AutoOptionType attAutoOptionType = (AutoOptionType)Ogre::StringConverter::parseInt(ValidAttr(properties->Attribute("autooptiontype"),"0"));
        Ogre::StringVector svec;

        OgitorsUtils::ParseStringVector(attFields, svec);

        def = set->addProperty(attID, OgitorsPropertyValue::createFromString((OgitorsPropertyType)attType, attValue));
        for(unsigned int i = 0;i < svec.size();i++)
            def->setFieldName(i, svec[i]);

        def->setAutoOptionType(attAutoOptionType);

        if(attAutoOptionType == AUTO_OPTIONS_NONE)
        {
            OgitorsUtils::ParseStringVector(attOptions, svec);
            if(svec.size() > 1)
            {
                PropertyOptionsVector *options = new PropertyOptionsVector();
                for(unsigned int o = 0;o < (svec.size() - 1);o += 2)
                {
                    OgitorsPropertyValue propVal = OgitorsPropertyValue::createFromString(def->getType(), svec[o + 1]);
                    options->push_back(PropertyOption(svec[o], propVal.val));
                }
                def->setOptions(options);
            }
        }
        else if(attAutoOptionType == AUTO_OPTIONS_MATERIAL)
            def->setOptions(OgitorsRoot::GetMaterialNames());
        else if(attAutoOptionType == AUTO_OPTIONS_MESH)
            def->setOptions(OgitorsRoot::GetModelNames());

    } while(properties = properties->NextSiblingElement());
}
//----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetUserDataSaveString(OgitorsCustomPropertySet *set, int indentation)
{
    Ogre::String buffer = "";

    if(!set)
        return "";

    Ogre::String indentStr = "";
    OgitorsPropertyVector vec = set->getPropertyVector();
    if(vec.size() < 1)
        return "";

    for(int k = 0; k < indentation;k++)
        indentStr += " ";

    buffer += indentStr + "<userData>\n";

    for(unsigned int i = 0;i < vec.size();i++)
    {
        OgitorsPropertyBase *property = vec[i];
        const OgitorsPropertyDef *def = property->getDefinition();
        OgitorsPropertyValue value;
        value.propType = property->getType();
        value.val = property->getValue();

        buffer += indentStr + "  <property type=\"" + Ogre::StringConverter::toString(value.propType) + "\"";
        buffer += " name=\"" + property->getName() + "\"";
        buffer += " data=\"" + GetValueString(value) + "\"></property>\n";
    }

    buffer += indentStr + "</userData>\n";
    return buffer;
}
//----------------------------------------------------------------------------------------
Ogre::String OgitorsUtils::GetObjectSaveStringV2(CBaseEditor *object, int indentation, bool useobjid, bool addparent)
{
    Ogre::String outStr;
    Ogre::String indentStr = "";

    for(int k = 0; k < indentation;k++)
        indentStr += " ";

    outStr = indentStr + "<OBJECT";
    if(useobjid)
    {
        outStr += " object_id=\"" + Ogre::StringConverter::toString(object->getObjectID()) + "\"";
    }
    outStr += " name=\"" + object->getName() + "\"";
    outStr += " typename=\"" + object->getTypeName() + "\"";
    /// If Object's parent name is "" then the parent is mRootEditor
    if(object->getParent()->getName() != "" && addparent)
    {
        outStr += " parentnode=\"" + object->getParent()->getName() + "\"";
    }
    outStr += ">\n";

    OgitorsPropertyValueMap theList;
    OgitorsPropertyValueMap::iterator ni;

    object->getPropertyMap(theList);

    theList.erase(theList.find("name"));
    theList.erase(theList.find("typename"));
    theList.erase(theList.find("object_id"));

    ni = theList.begin();
    while(ni != theList.end())
    {
        outStr += indentStr + "  <PROPERTY id=\"" + ni->first + "\"";
        outStr += " type=\"" + Ogre::StringConverter::toString(ni->second.propType) + "\"";
        outStr += " value=\"" + GetValueString(ni->second) + "\"></PROPERTY>\n";
        ni++;
    }
    outStr += GetCustomPropertySaveString(object->getCustomProperties(), indentation + 2).c_str();
    outStr += indentStr + "</OBJECT>\n";
    return outStr;
}
//----------------------------------------------------------------------------------------


text:
<?xml version="1.0" encoding="UTF-8"?>
<document xmlns="http://maven.apache.org/XDOC/2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">
  <properties>
    <title>Propertycopy Task</title>
    <author email="mattinger@yahoo.com">Matthew Inger</author>
  </properties>

      Copies the value of a named property to another property. This
      is useful when you need to plug in the value of another property
      in order to get a property name and then want to get the value
      of that property name.

    <subsection name="Parameters">

        Attribute
        Description
        Required

        property
        The name of the property to set.
        Yes.

        override

          If the property is already set, should we change it's
          value? Can be "true" or "false".

        No. Defaults to "false".

        name Deprecated
        The name of the property to set.

          No. Use the "property" attribute instead.

        from

          The name of the property you wish to copy the value from.

        Yes.

        silent

          Do you want to suppress the error if the "from" property
          does not exist, and just not set the property "name"?

        No, default is "false".

    </subsection>
    <subsection name="Example">
      <source><![CDATA[<property name="org" value="MyOrg"/>
<property name="org.MyOrg.DisplayName" value="My Organization"/>
<propertycopy name="displayName" from="org.${org}.DisplayName"/>]]></source>

      Sets displayName to "My Organization".

    </subsection>

</document>


text:
class MainTurnPhase :
	public ITurnPhase
{
public:
	MainTurnPhase();
	virtual ~MainTurnPhase();

	virtual void Tick(Player player) = 0;
};