text:
using System;
using System.Collections.Generic;
using System.Linq;
using Ozeki.Media.Codec;
using Ozeki.VoIP;
using Ozeki.VoIP.Media;
using Ozeki.VoIP.MessageSummary;
using Ozeki.VoIP.SDK;
using secret_sensa.Model.Data;
using TestSoftphone;
using System.ComponentModel;
using Ozeki.Network.Nat;
using System.Net;
using Ozeki.Common.Logger;
using secret_sensa.GUI.GUIModels;

namespace secret_sensa.Model
{
    public class SoftphoneEngine : IDisposable, INotifyPropertyChanged
    {
        #region Fields, Properties

        private IPhoneCall selectedCall;
        private IPhoneLine selectedLine;

        /// <summary>
        /// The basic softphone interface of the VoIP SIP SDK.
        /// </summary>
        private ISoftPhone softPhone;

        /// <summary>
        /// Gets the collection of the available local IP addresses.
        /// </summary>
        public List<IPAddress> LocalIPAddressList
        {
            get { return SoftPhoneFactory.GetAddressList(); }
        }

        /// <summary>
        /// Gets or sets the minimum port number for network communication. (requires restart)
        /// </summary>
        public int MinPort { get; set; }

        /// <summary>
        /// Gets or sets the minimum port number for network communication. (requires restart)
        /// </summary>
        public int MaxPort { get; set; }

        /// <summary>
        /// Gets or sets the local IP of the softphone.
        /// </summary>
        public IPAddress LocalIP { get; set; }

        /// <summary>
        /// Gets the list of the available phone lines.
        /// </summary>
        public ObservableList<IPhoneLine> PhoneLines { get; private set; }

        /// <summary>
        /// Gets or sets the currently selected phone line.
        /// </summary>
        public IPhoneLine SelectedLine
        {
            get { return selectedLine; }
            set
            {
                selectedLine = value;
                OnPropertyChanged("SelectedLine");
            }
        }

        /// <summary>
        /// Gets the list of the active phone calls.
        /// </summary>
        public ObservableList<IPhoneCall> PhoneCalls { get; private set; }

        /// <summary>
        /// Gets or sets the currently selected phone call.
        /// </summary>
        public IPhoneCall SelectedCall
        {
            get { return selectedCall; }
            set
            {
                selectedCall = value;
                MediaHandlers.DetachAudio();
                MediaHandlers.DetachVideo();

                if (selectedCall != null)
                {
                    MediaHandlers.AttachAudio(selectedCall);
                    MediaHandlers.AttachVideo(selectedCall);
                }

                OnPropertyChanged("SelectedCall");
            }
        }

        /// <summary>
        /// Gets the list of the previous phone calls.
        /// </summary>
        public CallHistory CallHistory { get; private set; }

        /// <summary>
        /// Gets a collection of call types.
        /// </summary>
        public List<CallType> CallTypes { get; private set; }

        /// <summary>
        /// Gets the media system (microhone, speaker etc.)
        /// </summary>
        public MediaHandlers MediaHandlers { get; private set; }

        /// <summary>
        /// Gets the collection of the sent and received instant messages.
        /// </summary>
        public ObservableList<string> InstantMessages { get; set; }

        public AccountModel AccountModel { get; private set; }

        #endregion

        #region Events

        /// <summary>
        /// Occurs when the state of a phone line has changed.
        /// </summary>
        public event EventHandler<GEventArgs<IPhoneLine>> PhoneLineStateChanged;

        /// <summary>
        /// Occurs when an incoming call received.
        /// </summary>
        public event EventHandler<GEventArgs<IPhoneCall>> IncomingCall;

        /// <summary>
        /// Occurs when the state of a phone line has changed.
        /// </summary>
        public event EventHandler<GEventArgs<IPhoneCall>> PhoneCallStateChanged;

        /// <summary>
        /// Occurs when an instant message received through a phone call.
        /// </summary>
        public event EventHandler<PhoneCallInstantMessageArgs> CallInstantMessageReceived;

        /// <summary>
        /// Occurs when a message summary indication received in a phone line.
        /// </summary>
        public event EventHandler<MessageSummaryArgs> MessageSummaryReceived;

        /// <summary>
        /// Occurs when the NAT discovery process has finished.
        /// </summary>
        public event EventHandler<GEventArgs<NatInfo>> NatDiscoveryFinished;

        #endregion

        #region Init, Dispose

        public SoftphoneEngine(bool IsToRegister=true)
        {
            // set license here

            PhoneLines = new ObservableList<IPhoneLine>();
            PhoneCalls = new ObservableList<IPhoneCall>();
            InstantMessages = new ObservableList<string>();
            CallHistory = new CallHistory();
            CallTypes = new List<CallType> {CallType.Audio, CallType.AudioVideo};
            AccountModel = new AccountModel()
            {
                DisplayName = Properties.Settings.Default.DisplayName,
                RegisterName = Properties.Settings.Default.RegisterName,
                Domain = Properties.Settings.Default.Domain,
                UserName = Properties.Settings.Default.UserName,
                OutboundProxy = Properties.Settings.Default.OutboundProxy,
                Password = Properties.Settings.Default.Password
            };

            // create softphone
            MinPort = 20000;
            MaxPort = 20500;
            //LocalIP = SoftPhoneFactory.GetLocalIP();
            InitSoftphone(false);

            // create media
            MediaHandlers = new MediaHandlers();
            MediaHandlers.Init();

            if (IsToRegister)
            {
                RegisterLine();
            }
        }

        /// <summary>
        /// Initializes the base softphone engine.
        /// </summary>
        internal void InitSoftphone(bool useFixIP)
        {
            Logger.Open(LogLevel.Trace); // open logger
            // if the softphone is already created, then close it
            if (softPhone != null)
            {
                // unregister the phone lines, because if the local IP address changed, the existing registrations will not work
                foreach (var line in PhoneLines)
                {
                    if (line.LineState == PhoneLineState.RegistrationSucceeded || line.LineState == PhoneLineState.NoRegNeeded)
                        softPhone.UnregisterPhoneLine(line);
                }

                softPhone.IncomingCall -= (SoftPhone_IncomingCall);
                softPhone.Close();
            }

            // create new softphone
            if (LocalIP == null || !useFixIP)
                //softPhone = SoftPhoneFactory.CreateSoftPhone(MinPort, MaxPort, 5060, "c:\\log.txt");
                softPhone = SoftPhoneFactory.CreateSoftPhone(MinPort, MaxPort, 5060, "c:\\YEK\\log.txt");
            else
                //softPhone = SoftPhoneFactory.CreateSoftPhone(LocalIP, MinPort, MaxPort, 5060, "c:\\log.txt");
                softPhone = SoftPhoneFactory.CreateSoftPhone(LocalIP, MinPort, MaxPort, 5060, "c:\\YEK\\log.txt");

            softPhone.IncomingCall += (SoftPhone_IncomingCall);
        }

        /// <summary>
        /// Disposes the softphone engine. Hangs up calls, unregisters phone lines and disposes the media handlers.
        /// </summary>
        public void Dispose()
        {
            PhoneCalls.Clear();

            // unregister phone lines
            foreach (IPhoneLine line in PhoneLines)
            {
                if (line.LineState == PhoneLineState.RegistrationSucceeded || line.LineState == PhoneLineState.NoRegNeeded)
                    softPhone.UnregisterPhoneLine(line);

                UnsubscribeFromLineEvents(line);
                line.Dispose();
            }
            PhoneLines.Clear();

            // dispose media
            MediaHandlers.Dispose();

            // close softphone
            softPhone.Close();
        }

        #endregion

        #region Invocators

        private void OnIncomingCall(IPhoneCall call)
        {
            var handler = IncomingCall;
            if (handler != null)
                handler(this, new GEventArgs<IPhoneCall>(call));
        }

        private void OnPhoneCallStateChanged(IPhoneCall call)
        {
            var handler = PhoneCallStateChanged;
            if (handler != null)
                handler(this, new GEventArgs<IPhoneCall>(call));
        }

        private void OnCallInstantMessageReceived(PhoneCallInstantMessageArgs args)
        {
            var handler = CallInstantMessageReceived;
            if (handler != null)
                handler(this, args);
        }

        private void OnPhoneLineStateChanged(IPhoneLine line)
        {
            var handler = PhoneLineStateChanged;
            if (handler != null)
                handler(this, new GEventArgs<IPhoneLine>(line));
        }

        private void OnMessageSummaryReceived(MessageSummaryArgs args)
        {
            var handler = MessageSummaryReceived;
            if (handler != null)
                handler(this, args);
        }

        private void OnNatDiscoveryFinished(NatInfo args)
        {
            var handler = NatDiscoveryFinished;
            if (handler != null)
                handler(this, new GEventArgs<NatInfo>(args));
        }

        #endregion

        #region PhoneLine Methods

        private bool Validate(string value)
        {
            if (value == null || string.IsNullOrEmpty(value.Trim()))
            {
                return false;
            }
            return true;
        }

        public void RegisterLine()
        {
            if (!Validate(AccountModel.UserName))
            {
                throw new ArgumentOutOfRangeException("User name cannot be empty!");
            }

            if (!Validate(AccountModel.RegisterName))
            {
                throw new ArgumentOutOfRangeException("Register name cannot be empty!");
            }

            if (!Validate(AccountModel.Domain))
            {
                throw new ArgumentOutOfRangeException("Domain cannot be empty!");
            }

            var line = AddPhoneLine(AccountModel.SIPAccount, AccountModel.TransportType, AccountModel.NatConfig, AccountModel.SRTPMode);

            if (SelectedLine == null)
                SelectedLine = line;

            RegisterPhoneLine();
        }

        /// <summary>
        /// Creates a phone line and adds it to the collection.
        /// </summary>
        public IPhoneLine AddPhoneLine(SIPAccount account, Ozeki.Network.TransportType transportType, NatConfiguration natConfig, SRTPMode srtpMode)
        {
            IPhoneLine line = softPhone.CreatePhoneLine(account, natConfig, transportType, srtpMode);
            SubscribeToLineEvents(line);

            // add to collection
            PhoneLines.Add(line);

            return line;
        }

        /// <summary>
        /// Disposes the selected phone line and removes it from the collection.
        /// </summary>
        public void RemovePhoneLine()
        {
            if (SelectedLine == null)
                return;

            ClosePhoneLine(SelectedLine);
            PhoneLines.Remove(SelectedLine);
        }

        /// <summary>
        /// Closes the calls on the phone line and unregisters the SIP account.
        /// </summary>
        private void ClosePhoneLine(IPhoneLine line)
        {
            if (line == null)
                return;

            foreach (var call in line.PhoneCalls)
                call.HangUp();

            softPhone.UnregisterPhoneLine(SelectedLine);
        }

        /// <summary>
        /// Registers the selected phone line to the PBX.
        /// </summary>
        public void RegisterPhoneLine()
        {
            if (SelectedLine == null)
                return;

            softPhone.RegisterPhoneLine(SelectedLine);
        }

        /// <summary>
        /// Unregisters the selected phone line from the PBX.
        /// </summary>
        public void UnregisterPhoneLine()
        {
            if (SelectedLine == null)
                return;

            softPhone.UnregisterPhoneLine(SelectedLine);
        }

        /// <summary>
        /// Line event subscriptions.
        /// </summary>
        private void SubscribeToLineEvents(IPhoneLine line)
        {
            if (line == null)
                return;

            line.PhoneLineStateChanged += Line_PhoneLineStateChanged;
            line.OutofDialogInstantMessageReceived += (Line_OutofDialogInstantMessageReceived);
            line.MessageSummaryReceived += (Line_MessageSummaryReceived);
        }

        /// <summary>
        /// Line event unsubscriptions.
        /// </summary>
        private void UnsubscribeFromLineEvents(IPhoneLine line)
        {
            if (line == null)
                return;

            line.PhoneLineStateChanged -= Line_PhoneLineStateChanged;
            line.OutofDialogInstantMessageReceived -= (Line_OutofDialogInstantMessageReceived);
            line.MessageSummaryReceived -= (Line_MessageSummaryReceived);
        }

        #endregion

        #region PhoneLine EventHandlers

        /// <summary>
        /// This will be called when the state of a phone line has changed.
        /// </summary>
        private void Line_PhoneLineStateChanged(object sender, VoIPEventArgs<PhoneLineState> e)
        {
            IPhoneLine line = sender as IPhoneLine;
            if (line == null)
                return;

            PhoneLineState state = e.Item;

            // registration succeeded, subscribe for MWI
            if (state == PhoneLineState.RegistrationSucceeded)
            {
                line.SubscribeToMWI();
            }

            OnPhoneLineStateChanged(line);
            OnPropertyChanged("SelectedLine.RegisteredInfo");
        }

        /// <summary>
        /// This will be called when an instant message received through a phone line.
        /// </summary>
        private void Line_OutofDialogInstantMessageReceived(object sender, VoIPEventArgs<MessageDataPackage> e)
        {
            IPhoneLine line = sender as IPhoneLine;
            if (line == null)
                return;

            MessageDataPackage data = e.Item;
            AddInstantMessage(data.Originator, data.Data);
        }

        /// <summary>
        /// Adds an instant message to the history.
        /// </summary>
        public void AddInstantMessage(string sender, string data)
        {
            InstantMessages.Add(string.Format("{0}: {1}", sender, data));
        }

        internal void ClearInstantMessages()
        {
            InstantMessages.Clear();
        }

        /// <summary>
        /// This will be called when a message summary received.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Line_MessageSummaryReceived(object sender, VoIPEventArgs<VoIPMessageSummary> e)
        {
            IPhoneLine line = sender as IPhoneLine;
            if (line == null)
                return;

            OnMessageSummaryReceived(new MessageSummaryArgs(line, e.Item));
        }

        #endregion

        #region PhoneCall Methods

        /// <summary>
        /// Starts dialling a number on the selected phone line.
        /// </summary>
        public void Dial(string dialNumber, CallType callType)
        {
            if (string.IsNullOrEmpty(dialNumber))
                return;

            IPhoneCall call = softPhone.CreateCallObject(SelectedLine, dialNumber, callType);
            StartCall(call);
        }

        /// <summary>
        /// Starts dialling a number on the selected phone line.
        /// </summary>
        public void DialIP(string address, CallType callType)
        {
            if (string.IsNullOrEmpty(address))
                return;

            IPhoneCall call = softPhone.CreateDirectIPCallObject(SelectedLine, callType, address);
            StartCall(call);
        }

        private void StartCall(IPhoneCall call)
        {
            if (call == null)
                return;

            SubscribeToCallEvents(call);
            call.Start();

            PhoneCalls.Add(call);

            if (SelectedCall == null)
                SelectedCall = call;
        }

        /// <summary>
        /// Accepts the selected incoming call.
        /// </summary>
        public void AnswerCall()
        {
            if (SelectedCall == null)
                return;

            SelectedCall.Accept(CallType.AudioVideo);
        }

        /// <summary>
        /// Rejects the selected incoming call.
        /// </summary>
        public void RejectCall()
        {
            if (SelectedCall == null)
                return;

            SelectedCall.Reject();
        }

        /// <summary>
        /// Hangs up the selected call.
        /// </summary>
        internal void HangUpCall()
        {
            if (SelectedCall == null)
                return;

            SelectedCall.HangUp();
        }

        /// <summary>
        /// Puts on hold selected call.
        /// </summary>
        public void HoldCall()
        {
            if (SelectedCall == null)
                return;

            SelectedCall.HoldCall();
        }

        /// <summary>
        /// Takes the selected call off hold.
        /// </summary>
        public void UnholdCall()
        {
            if (SelectedCall == null)
                return;

            SelectedCall.UnholdCall();
        }

        /// <summary>
        /// Forwards the selected incoming call.
        /// </summary>
        internal void ForwardCall(string target)
        {
            if (SelectedCall == null)
                return;

            if (!SelectedCall.IsIncoming)
                return;

            SelectedCall.ForwardCall(target);
        }

        /// <summary>
        /// Routes the selected call to a third party.
        /// </summary>
        public void BlindTransfer(string target)
        {
            if (string.IsNullOrEmpty(target))
                return;

            if (SelectedCall == null)
                return;

            SelectedCall.BlindTransfer(target);
        }

        /// <summary>
        /// Routes the selected call to another.
        /// </summary>
        public void AttendedTransfer(IPhoneCall targetCall)
        {
            if (SelectedCall == null)
                return;

            if (targetCall == null)
                return;

            SelectedCall.AttendedTransfer(targetCall);
        }

        /// <summary>
        /// Sends a message to the other party.
        /// </summary>
        public void SendInstantMessage(string message)
        {
            if (SelectedCall == null)
                return;

            SelectedCall.SendInstantMessage(MimeType.Text_Plain, message);
        }

        /// <summary>
        /// Modifies the media channels of the selected phone call.
        /// </summary>
        public void ModifyCallType(CallType callType)
        {
            if (SelectedCall == null)
                return;

            SelectedCall.ModifyCallType(callType);
        }

        #endregion

        #region PhoneCall EventHandlers

        /// <summary>
        /// This will be called when an incoming call received.
        /// </summary>
        private void SoftPhone_IncomingCall(object sender, VoIPEventArgs<IPhoneCall> e)
        {
            IPhoneCall call = e.Item;
            SubscribeToCallEvents(call);

            // automatically rejected for some reason
            if (call.CallState == CallState.Error)
            {
                CallHistory.Add(call);
                return;
            }

            // add to call container
            PhoneCalls.Add(call);

            // if no call is in progress, select the incoming call as current call and attach the audio to hear the ringtone
            if (SelectedCall == null)
            {
                SelectedCall = call;
                MediaHandlers.AttachAudio(call);
            }

            // raise IncomingCall event
            OnIncomingCall(call);
        }

        /// <summary>
        /// This will be called when the state of a call has changed.
        /// </summary>
        private void Call_CallStateChanged(object sender, VoIPEventArgs<CallState> e)
        {
            IPhoneCall call = sender as IPhoneCall;
            if (call == null)
                return;

            CallState state = e.Item;

            OnPhoneCallStateChanged(call);
            CheckStopRingback();
            CheckStopRingtone();

            // start ringtones
            if (state.IsRinging())
            {
                if (call.IsIncoming)
                    MediaHandlers.StartRingtone();
                else
                    MediaHandlers.StartRingback();

                return;
            }

            // call has been answered
            if (state == CallState.Answered)
            {
                return;
            }

            // attach media to the selected call when the remote party sends media data
            if (state.IsRemoteMediaCommunication())
            {
                if (SelectedCall.Equals(call))
                {
                    MediaHandlers.AttachAudio(call);
                    MediaHandlers.AttachAudio(call);
                }
                return;
            }

            // detach media from the selected call in hold state or when the call has ended
            if (state == CallState.LocalHeld || state == CallState.InactiveHeld || state.IsCallEnded())
            {
                if (SelectedCall.Equals(call))
                {
                    MediaHandlers.DetachAudio();
                    MediaHandlers.DetachVideo();
                }
            }

            // call has ended, clean up
            if (state.IsCallEnded())
            {
                DisposeCall(call);

                CallHistory.Add(call);
                PhoneCalls.Remove(call);
                return;
            }
        }

        private void CheckStopRingback()
        {
            bool stopRinging = true;
            foreach (var phoneCall in PhoneCalls)
            {
                if (!phoneCall.IsIncoming && phoneCall.CallState.IsRinging())
                {
                    stopRinging = false;
                    break;
                }
            }

            if (stopRinging)
                MediaHandlers.StopRingback();
        }

        private void CheckStopRingtone()
        {
            bool stopRinging = true;
            foreach (var phoneCall in PhoneCalls)
            {
                if (phoneCall.IsIncoming && phoneCall.CallState.IsRinging())
                {
                    stopRinging = false;
                    break;
                }
            }

            if (stopRinging)
                MediaHandlers.StopRingtone();
        }

        /// <summary>
        /// This will be called when an error occurred during the call.
        /// </summary>
        private void Call_CallErrorOccured(object sender, VoIPEventArgs<CallError> e)
        {
            IPhoneCall call = sender as IPhoneCall;
            if (sender == null)
                return;

            MediaHandlers.DetachAudio();
            MediaHandlers.DetachVideo();
            DisposeCall(call);

            OnPhoneCallStateChanged(call);
        }

        /// <summary>
        /// This will be called when an instant message received through a call.
        /// </summary>
        private void Call_InstantMessageDataReceived(object sender, VoIPEventArgs<MessageDataPackage> e)
        {
            IPhoneCall call = sender as IPhoneCall;
            if (call == null)
                return;

            MessageDataPackage data = e.Item;
            OnCallInstantMessageReceived(new PhoneCallInstantMessageArgs(call, data));
        }

        private void DisposeCall(IPhoneCall call)
        {
            UnsubscribeFromCallEvents(call);

            if (call.Equals(SelectedCall))
                SelectedCall = null;
        }

        /// <summary>
        /// Call event subscriptions.
        /// </summary>
        private void SubscribeToCallEvents(IPhoneCall call)
        {
            if (call == null)
                return;

            call.CallStateChanged += (Call_CallStateChanged);
            call.CallErrorOccured += (Call_CallErrorOccured);
            call.DtmfReceived += (Call_DtmfReceived);
            call.DtmfStarted += (Call_DtmfStarted);
            call.InstantMessageDataReceived += (Call_InstantMessageDataReceived);
        }

        /// <summary>
        /// Call event unsubscriptions.
        /// </summary>
        private void UnsubscribeFromCallEvents(IPhoneCall call)
        {
            if (call == null)
                return;

            call.CallStateChanged -= (Call_CallStateChanged);
            call.CallErrorOccured -= (Call_CallErrorOccured);
            call.DtmfReceived -= (Call_DtmfReceived);
            call.DtmfStarted -= (Call_DtmfStarted);
            call.InstantMessageDataReceived -= (Call_InstantMessageDataReceived);
        }

        #endregion

        #region Codecs

        /// <summary>
        /// Gets the supported codecs.
        /// </summary>
        public IEnumerable<CodecInfo> AudioCodecs
        {
            get { return softPhone.Codecs.Where(c => c.MediaType == CodecMediaType.Audio); }
        }

        /// <summary>
        /// Gets the supported codecs.
        /// </summary>
        public IEnumerable<CodecInfo> VideoCodecs
        {
            get { return softPhone.Codecs.Where(c => c.MediaType == CodecMediaType.Video); }
        }

        /// <summary>
        /// Enables a codec.
        /// </summary>
        /// <param name="payloadType">The payload type of the codec.</param>
        internal void EnableCodec(int payloadType)
        {
            softPhone.EnableCodec(payloadType);
        }

        /// <summary>
        /// Disables a codec.
        /// </summary>
        /// <param name="payloadType">The payload type of the codec.</param>
        internal void DisableCodec(int payloadType)
        {
            softPhone.DisableCodec(payloadType);
        }

        /// <summary>
        /// Sets the quality of the sent video data.
        /// </summary>
        internal void SetVideoEncoderQuality(VideoQuality videoQuality)
        {
            softPhone.VideoEncoderQuality = videoQuality;
        }

        #endregion

        #region DTMF

        /// <summary>
        /// Starts the DTMF signalling.
        /// </summary>
        public void StartDtmfSignal(int signal)
        {
            StartDtmfSignal((DtmfNamedEvents)signal);
        }

        /// <summary>
        /// Starts the DTMF signalling.
        /// </summary>
        public void StartDtmfSignal(DtmfNamedEvents signal)
        {
            MediaHandlers.StartDtmf(signal);

            if (SelectedCall == null)
                return;

            SelectedCall.StartDTMFSignal(signal);
        }

        /// <summary>
        /// Stops the DTMF singalling.
        /// </summary>
        internal void StopDtmfSignal(int signal)
        {
            StopDtmfSignal((DtmfNamedEvents)signal);
        }

        /// <summary>
        /// Stops the DTMF singalling.
        /// </summary>
        internal void StopDtmfSignal(DtmfNamedEvents signal)
        {
            MediaHandlers.StopDtmf(signal);

            if (SelectedCall == null)
                return;

            SelectedCall.StopDTMFSignal(signal);
        }

        /// <summary>
        /// This will be called when the other party started DTMF signaling.
        /// </summary>
        private void Call_DtmfStarted(object sender, VoIPEventArgs<DtmfInfo> e)
        {
            int signal = e.Item.Signal.Signal;
            MediaHandlers.StartDtmf(signal);
        }

        /// <summary>
        /// This will be called when the other party stopped DTMF signaling.
        /// </summary>
        private void Call_DtmfReceived(object sender, VoIPEventArgs<DtmfInfo> e)
        {
            DtmfSignal signal = e.Item.Signal;
            MediaHandlers.StopDtmf(signal.Signal);
        }

        #endregion

        #region NAT Discovery

        public void BeginNatDiscovery()
        {
            // determine which local address used for NAT discovery
            string localAddress = string.Empty;
            if (LocalIP == null)
            {
                var localIP = SoftPhoneFactory.GetLocalIP();
                if (localIP != null)
                    localAddress = localIP.ToString();
            }
            else
                localAddress = LocalIP.ToString();

            // begin NAT discovery
            softPhone.BeginNatDiscovery(localAddress, "stun.ozekiphone.com", Callback);
        }

        private void Callback(NatInfo info)
        {
            OnNatDiscoveryFinished(info);
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}


text:
var wows = require('vows');
var assert = require('assert');
var XMLSerializer = require('xmldom').XMLSerializer;
var DOMParser = require('xmldom').DOMParser;
var DomJS = require("dom-js").DomJS;
try{
	var Libxml = require('libxmljs');
}catch(e){
}

function xmldom(data){
	console.time('xmldom');
	var doc = new DOMParser().parseFromString(data);
	console.timeEnd('xmldom');
	doc.toString = function(){
		return new XMLSerializer().serializeToString(doc);
	}
	return doc;
}
function libxml(data){
	if(Libxml){
		console.time('libxml');
		var doc = Libxml.parseXmlString(data);
		console.timeEnd('libxml');
		var ToString=doc.toString ;
		doc.toString = function(){
			return ToString.apply(this,arguments).replace(/^\s+|\s+$/g,'');
		}
		return doc;
	}else{
		console.warn('libxml is not installed')
	}
}

function domjs(data){
	console.time('dom-js');
	var doc;
	new DomJS().parse(data, function(err, dom) {
	    doc = dom;
	});
	console.timeEnd('dom-js');

	doc.toString = function(){
		return doc.toXml();
	}
	return doc
}
function addAttributes(el){
	var c =parseInt(Math.random()*10);
	while(c--){
		el.setAttribute('dynamic-attr'+c,c+new Array(c).join('.'));
	}
	var child = el.firstChild;
	while(child){
		if(child.nodeType == 1){
			addAttributes(child)
		}else if(child.nodeType == 4){//cdata
			el.insertBefore(el.ownerDocument.createTextNode(child.data),child);
			el.removeChild(child);
		}
		child = child.nextSibling;
	}
}
// Create a Test Suite
wows.describe('XML Node Parse').addBatch({
    "big file parse":function(){
		var fs = require('fs');
		var path = require('path')
		var data = fs.readFileSync(path.resolve(__dirname,'./test.xml'), 'ascii');
		//data = "<?xml version=\"1.0\"?><xml><child> ![CDATA[v]] d &</child>\n</xml>"

		var doc1 = xmldom(data);
		var doc2 = domjs(data);
		var doc3 = libxml(data);

		addAttributes(doc1.documentElement);

		data = doc1.toString();

		var doc1 = xmldom(data);
		var doc2 = domjs(data);
		var doc3 = libxml(data);

		xmldomresult = (domjs(doc1+'')+'').replace(/^<\?.*?\?>\s*|<!\[CDATA\[\]\]>/g,'')
		domjsresult = (doc2+'').replace(/^<\?.*?\?>\s*|<!\[CDATA\[\]\]>/g,'')

		//console.log(xmldomresult,domjsresult)

		//assert.equal(xmldomresult,domjsresult);
		//,xmldomresult,domjsresult)
		if(xmldomresult !== domjsresult){
			for(var i=0;i<xmldomresult.length;i++){
				if(xmldomresult.charAt(i)!=domjsresult.charAt(i)){
					console.log(xmldomresult.charAt(i))
					var begin = i-50;
					var len = 100;
					xmldomresult = xmldomresult.substr(begin,len)
					domjsresult = domjsresult.substr(begin,len)
					//console.log(xmldomresult.length,domjsresult.length)
					console.log('pos'+i,'\n',xmldomresult,'\n\n\n\n',domjsresult)
					console.assert(xmldomresult == domjsresult)
					break;
				}
			}

		}
		//console.assert(xmldomresult == domjsresult,xmldomresult.length,i)
    }
}).run(); // Run it

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Cache\Traits;

use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;

/**
 * @author Rob Frawley 2nd <rmf@src.run>
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
trait MemcachedTrait
{
    private static $defaultClientOptions = array(
        'persistent_id' => null,
        'username' => null,
        'password' => null,
        'serializer' => 'php',
    );

    private $client;
    private $lazyClient;

    public static function isSupported()
    {
        return extension_loaded('memcached') && version_compare(phpversion('memcached'), '2.2.0', '>=');
    }

    private function init(\Memcached $client, $namespace, $defaultLifetime)
    {
        if (!static::isSupported()) {
            throw new CacheException('Memcached >= 2.2.0 is required');
        }
        if ('Memcached' === get_class($client)) {
            $opt = $client->getOption(\Memcached::OPT_SERIALIZER);
            if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
                throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
            }
            $this->maxIdLength -= strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
            $this->client = $client;
        } else {
            $this->lazyClient = $client;
        }

        parent::__construct($namespace, $defaultLifetime);
        $this->enableVersioning();
    }

    /**
     * Creates a Memcached instance.
     *
     * By default, the binary protocol, no block, and libketama compatible options are enabled.
     *
     * Examples for servers:
     * - 'memcached://user:pass@localhost?weight=33'
     * - array(array('localhost', 11211, 33))
     *
     * @param array[]|string|string[] An array of servers, a DSN, or an array of DSNs
     * @param array                   An array of options
     *
     * @return \Memcached
     *
     * @throws \ErrorException When invalid options or servers are provided
     */
    public static function createConnection($servers, array $options = array())
    {
        if (is_string($servers)) {
            $servers = array($servers);
        } elseif (!is_array($servers)) {
            throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, %s given.', gettype($servers)));
        }
        if (!static::isSupported()) {
            throw new CacheException('Memcached >= 2.2.0 is required');
        }
        set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
        try {
            $options += static::$defaultClientOptions;
            $client = new \Memcached($options['persistent_id']);
            $username = $options['username'];
            $password = $options['password'];
            unset($options['persistent_id'], $options['username'], $options['password']);
            $options = array_change_key_case($options, CASE_UPPER);

            // set client's options
            $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
            $client->setOption(\Memcached::OPT_NO_BLOCK, true);
            if (!array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
                $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
            }
            foreach ($options as $name => $value) {
                if (is_int($name)) {
                    continue;
                }
                if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
                    $value = constant('Memcached::'.$name.'_'.strtoupper($value));
                }
                $opt = constant('Memcached::OPT_'.$name);

                unset($options[$name]);
                $options[$opt] = $value;
            }
            $client->setOptions($options);

            // parse any DSN in $servers
            foreach ($servers as $i => $dsn) {
                if (is_array($dsn)) {
                    continue;
                }
                if (0 !== strpos($dsn, 'memcached://')) {
                    throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s does not start with "memcached://"', $dsn));
                }
                $params = preg_replace_callback('#^memcached://(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
                    if (!empty($m[1])) {
                        list($username, $password) = explode(':', $m[1], 2) + array(1 => null);
                    }

                    return 'file://';
                }, $dsn);
                if (false === $params = parse_url($params)) {
                    throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
                }
                if (!isset($params['host']) && !isset($params['path'])) {
                    throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
                }
                if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
                    $params['weight'] = $m[1];
                    $params['path'] = substr($params['path'], 0, -strlen($m[0]));
                }
                $params += array(
                    'host' => isset($params['host']) ? $params['host'] : $params['path'],
                    'port' => isset($params['host']) ? 11211 : null,
                    'weight' => 0,
                );
                if (isset($params['query'])) {
                    parse_str($params['query'], $query);
                    $params += $query;
                }

                $servers[$i] = array($params['host'], $params['port'], $params['weight']);
            }

            // set client's servers, taking care of persistent connections
            if (!$client->isPristine()) {
                $oldServers = array();
                foreach ($client->getServerList() as $server) {
                    $oldServers[] = array($server['host'], $server['port']);
                }

                $newServers = array();
                foreach ($servers as $server) {
                    if (1 < count($server)) {
                        $server = array_values($server);
                        unset($server[2]);
                        $server[1] = (int) $server[1];
                    }
                    $newServers[] = $server;
                }

                if ($oldServers !== $newServers) {
                    // before resetting, ensure $servers is valid
                    $client->addServers($servers);
                    $client->resetServerList();
                }
            }
            $client->addServers($servers);

            if (null !== $username || null !== $password) {
                if (!method_exists($client, 'setSaslAuthData')) {
                    trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.');
                }
                $client->setSaslAuthData($username, $password);
            }

            return $client;
        } finally {
            restore_error_handler();
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function doSave(array $values, $lifetime)
    {
        if ($lifetime && $lifetime > 30 * 86400) {
            $lifetime += time();
        }

        return $this->checkResultCode($this->getClient()->setMulti($values, $lifetime));
    }

    /**
     * {@inheritdoc}
     */
    protected function doFetch(array $ids)
    {
        $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
        try {
            return $this->checkResultCode($this->getClient()->getMulti($ids));
        } catch (\Error $e) {
            throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
        } finally {
            ini_set('unserialize_callback_func', $unserializeCallbackHandler);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function doHave($id)
    {
        return false !== $this->getClient()->get($id) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
    }

    /**
     * {@inheritdoc}
     */
    protected function doDelete(array $ids)
    {
        $ok = true;
        foreach ($this->checkResultCode($this->getClient()->deleteMulti($ids)) as $result) {
            if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) {
                $ok = false;
            }
        }

        return $ok;
    }

    /**
     * {@inheritdoc}
     */
    protected function doClear($namespace)
    {
        return false;
    }

    private function checkResultCode($result)
    {
        $code = $this->client->getResultCode();

        if (\Memcached::RES_SUCCESS === $code || \Memcached::RES_NOTFOUND === $code) {
            return $result;
        }

        throw new CacheException(sprintf('MemcachedAdapter client error: %s.', strtolower($this->client->getResultMessage())));
    }

    /**
     * @return \Memcached
     */
    private function getClient()
    {
        if ($this->client) {
            return $this->client;
        }

        $opt = $this->lazyClient->getOption(\Memcached::OPT_SERIALIZER);
        if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
            throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
        }
        if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) {
            throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
        }

        return $this->client = $this->lazyClient;
    }
}


text:
done-criteria
=============

[![Build
Status](https://secure.travis-ci.org/atsuya/done-criteria.png)](http://travis-ci.org/atsuya/done-criteria)

Easy to use ``async.whilst`` like utility.

install
========
```
$ npm install done-criteria
```

examples
========

unnamed
-------

```
var DoneCriteria = require('../lib/done-criteria')
  , exit = false;

var doneCriteria = new DoneCriteria(['unko', 'geri'], function(error) {
  console.log('all done!');
  exit = true;
});

setTimeout(function() { doneCriteria.done('unko'); }, 1000);
setTimeout(function() { doneCriteria.done('geri'); }, 2000);

var loop = function() {
  if (exit) {
    process.exit(0);
  } else {
    console.log('not done yet...');
    setTimeout(loop, 500);
  }
};
loop();
```

This code results in:

```
$ node examples/unnamed.js
not done yet...
not done yet...
not done yet...
not done yet...
all done!
```

named
-----

```
var DoneCriteria = require('../lib/done-criteria')
  , exit = false;

var doneCriteria = new DoneCriteria(
    {
        'eat': [
            ['get ingredients', 'cook']
          , function(name) { console.log('%s is done', name); }
        ]
      , 'clean up': [
            ['put dishes into sink', 'wash them']
          , function(name) { console.log('%s is done', name); }
        ]
    }
  , function(error) {
      console.log('all done!');
      exit = true;
    }
);

setTimeout(function() { doneCriteria.done('eat', 'cook'); }, 200);
setTimeout(function() { doneCriteria.done('eat', 'get ingredients'); }, 600);

setTimeout(function() { doneCriteria.done('clean up', 'put dishes into sink'); }, 400);
setTimeout(function() { doneCriteria.done('clean up', 'wash them'); }, 1000);

var loop = function() {
  if (exit) {
    process.exit(0);
  } else {
    console.log('not done yet...');
    setTimeout(loop, 500);
  }
};
loop();
```

This code will result in:

```
$ node examples/named.js
not done yet...
not done yet...
eat is done
clean up is done
all done!
```

count
-----

```
var DoneCriteria = require('../lib/done-criteria')
  , exit = false;

var doneCriteria = new DoneCriteria(3, function(error) {
  console.log('all done!');
  exit = true;
});

setTimeout(function() { doneCriteria.done(); }, 200);
setTimeout(function() { doneCriteria.done(); }, 400);
setTimeout(function() { doneCriteria.done(); }, 600);

var loop = function() {
  if (exit) {
    process.exit(0);
  } else {
    console.log('not done yet...');
    setTimeout(loop, 500);
  }
};
loop();
```

This code will result in:

```
$ node examples/count.js
not done yet...
not done yet...
all done!
```

License
========

MIT


text:
package com.bt.pi.core.application.health.entity;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class HeartbeatEntityCollectionTest {
    @Test
    public void shouldGetType() throws Exception {
        // setup
        HeartbeatEntityCollection heartbeatEntityCollection = new HeartbeatEntityCollection();

        // act
        String result = heartbeatEntityCollection.getType();

        // assert
        assertThat(result, equalTo("HeartbeatEntityCollection"));
    }
}


text:
CKEDITOR.plugins.setLang( 'blockquote', 'ca', {
	toolbar: 'Bloc de cita'
} );


text:
package org.para.distributed.util;

import java.util.Collections;
import java.util.List;

import org.para.distributed.dto.WorkerNode;

public class SortStrategy {

	/**
	 * 对候选节点资源进行排序
	 *
	 * @param list
	 */
	public synchronized static void sortCandidateList(List<WorkerNode> list) {
		// logger.info("结点资源按照CPU、内存参数进行排序");
		Collections.sort(list, new SortCPUAndMemroyComparator());
	}
}


text:
using namespace floor_nav;
using namespace task_manager_lib;

class TaskServer : public TaskServerBase {
    protected:
    public:
        TaskServer(TaskEnvironmentPtr _env) : TaskServerBase(_env,true) {
            start();
        }

};

int main(int argc, char *argv[])
{
    ros::init(argc,argv,"task_server");//init ros
    ros::NodeHandle nh("~");
    TaskEnvironmentPtr env(new SimTasksEnv(nh));
    TaskServer ts(env);
    ros::spin();
    return 0;
}


text:
@charset "UTF-8";
/*
    Document   : dashboard
    Created on : 03-11-2011, 02:07:01 AM
    Author     : gustavo@lacosox.org (Gustavo Lacoste)
    Description:
        Purpose of the stylesheet follows.
*/

/*
   TODO customize this sample style
   Syntax recommendation http://www.w3.org/TR/REC-CSS2/
*/

.formStyleGeoSearch{
    width: 100%;
    padding: 3px;
    background-color: #F2F2F2;
    padding: 10px;
}

.formStyleGeoSearch a{
    color: #1F749C;
    font-weight: bold;
}

.formStyleGeoSearch form input[type=text]{
    background: url("../images/gfx/input_search.png")  no-repeat scroll #FFF;
    border: 1px solid #CCCCCC;
    color: #333333;
    font-size: 14px;
    height: 22px;
    padding: 3px 0 1px 5px;
    width: 625px;
}

.formStyleGeoSearch #local_direccion{
    width: 534px !important;
}

.formStyleGeoSearch form label{
    color: #C41200;
    font-weight: bold;
}

.formStyleGeoSearch td, .formStyleGeoSearch th
{
  text-align: left;
  vertical-align: top;
  padding: 7px;
}
.formStyleGeoSearch #mapa_error_posicion_container{
    margin: 10px;
    display: none;
}
.formStyleGeoSearch #map_canvas{
    height:370px;
    background-color: black;
}
.formStyleGeoSearch #local_msg_pos_maker{
    margin: 10px;
}

.negro{
    background-color: #000;
    display: none;
}


text:
module VagrantPlugins
  module DevCommands
    module HelpPrinter
      # Prints help for a command alias
      class CommandAlias
        I18N_KEY = 'vagrant_devcommands.internal.help'
        UTIL     = VagrantPlugins::DevCommands::Util
        MESSAGES = VagrantPlugins::DevCommands::Messages

        def initialize(env)
          @env = env
        end

        def output(command_alias)
          header(command_alias)
          body(command_alias.help)
        end

        private

        def body(help)
          return message(:command_alias_no_help, pre_ln: true) if help.nil?

          info(help.strip, pre_ln: true)
        end

        def header(command_alias)
          usage =
            if command_alias.usage.nil?
              I18n.t("#{I18N_KEY}.usage_default", what: command_alias.name)
            else
              format(command_alias.usage, command_alias: command_alias.name)
            end

          alias_for = [command_alias.command, command_alias.argv].join(' ')

          info(I18n.t("#{I18N_KEY}.usage", what: usage))
          info(I18n.t("#{I18N_KEY}.alias_for", what: alias_for), pre_ln: true)
        end

        def info(msg, pre_ln: false)
          @env.ui.info '' if pre_ln
          @env.ui.info msg
        end

        def message(msg, pre_ln: false)
          if pre_ln
            MESSAGES.pre_ln(msg, &@env.ui.method(:info))
          else
            MESSAGES.public_send(msg, &@env.ui.method(:info))
          end
        end
      end
    end
  end
end


text:
<?php

namespace ChartDown\Chart\ExpressionType;

/**
* Accent Expression
*/
class Accent implements ExpressionTypeInterface
{
    public function getSymbol()
    {
        return '^';
    }

    public function getPosition()
    {
        return 'chord';
    }

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

    public function getRegex()
    {
        return '\^';
    }
}


text:
var undef;
var slideCSS = '';
var snum = 0;
var smax = 1;
var incpos = 0;
var number = undef;
var s5mode = true;
var defaultView = 'slideshow';
var controlVis = 'visible';

var s5NotesWindow;
var s5NotesWindowLoaded = false;
var previousSlide = 0;
var presentationStart = new Date();
var slideStart = new Date();

var countdown = {
	timer: 0,
	state: 'pause',
	start: new Date(),
	end: 0,
	remaining: 0
};

var isIE = navigator.appName == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') < 1 ? 1 : 0;
var isOp = navigator.userAgent.indexOf('Opera') > -1 ? 1 : 0;
var isGe = navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('Safari') < 1 ? 1 : 0;

function hasClass(object, className) {
	if (!object.className) return false;
	return (object.className.search('(^|\\s)' + className + '(\\s|$)') != -1);
}

function hasValue(object, value) {
	if (!object) return false;
	return (object.search('(^|\\s)' + value + '(\\s|$)') != -1);
}

function removeClass(object,className) {
	if (!object || !hasClass(object,className)) return;
	object.className = object.className.replace(new RegExp('(^|\\s)'+className+'(\\s|$)'), RegExp.$1+RegExp.$2);
}

function addClass(object,className) {
	if (!object || hasClass(object, className)) return;
	if (object.className) {
		object.className += ' '+className;
	} else {
		object.className = className;
	}
}

function GetElementsWithClassName(elementName,className) {
	var allElements = document.getElementsByTagName(elementName);
	var elemColl = new Array();
	for (var i = 0; i< allElements.length; i++) {
		if (hasClass(allElements[i], className)) {
			elemColl[elemColl.length] = allElements[i];
		}
	}
	return elemColl;
}

function isParentOrSelf(element, id) {
	if (element == null || element.nodeName=='BODY') return false;
	else if (element.id == id) return true;
	else return isParentOrSelf(element.parentNode, id);
}

function nodeValue(node) {
	var result = "";
	if (node.nodeType == 1) {
		var children = node.childNodes;
		for (var i = 0; i < children.length; ++i) {
			result += nodeValue(children[i]);
		}
	}
	else if (node.nodeType == 3) {
		result = node.nodeValue;
	}
	return(result);
}

function slideLabel() {
	var slideColl = GetElementsWithClassName('*','slide');
	var list = document.getElementById('jumplist');
	smax = slideColl.length;
	for (var n = 0; n < smax; n++) {
		var obj = slideColl[n];

		var did = 'slide' + n.toString();
		obj.setAttribute('id',did);

//		if (isOp) continue;   // Opera fix (hallvord)

		var otext = '';
		var menu = obj.firstChild;
		if (!menu) continue; // to cope with empty slides
		while (menu && menu.nodeType == 3) {
			menu = menu.nextSibling;
		}
	 	if (!menu) continue; // to cope with slides with only text nodes

		var menunodes = menu.childNodes;
		for (var o = 0; o < menunodes.length; o++) {
			otext += nodeValue(menunodes[o]);
		}
		list.options[list.length] = new Option(n + ' : '  + otext, n);
	}
}

function currentSlide() {
	var cs;
	if (document.getElementById) {
		cs = document.getElementById('currentSlide');
	} else {
		cs = document.currentSlide;
	}
	cs.innerHTML = '' +
		'' + snum + '<\/span> ' +
		'\/<\/span> ' +
		'' + (smax-1) + '<\/span>' +
		'<\/a>'
		;
	if (snum == 0) {
		cs.style.visibility = 'hidden';
	} else {
		cs.style.visibility = 'visible';
	}
}

function go(step) {
	if (document.getElementById('slideProj').disabled || step == 0) return;
	var jl = document.getElementById('jumplist');
	var cid = 'slide' + snum;
	var ce = document.getElementById(cid);
	if (incrementals[snum].length > 0) {
		for (var i = 0; i < incrementals[snum].length; i++) {
			removeClass(incrementals[snum][i], 'current');
			removeClass(incrementals[snum][i], 'incremental');
		}
	}
	if (step != 'j') {
		snum += step;
		lmax = smax - 1;
		if (snum > lmax) snum = lmax;
		if (snum < 0) snum = 0;
	} else
		snum = parseInt(jl.value);
	var nid = 'slide' + snum;
	var ne = document.getElementById(nid);
	if (!ne) {
		ne = document.getElementById('slide0');
		snum = 0;
	}
	if (step < 0) {incpos = incrementals[snum].length} else {incpos = 0;}
	if (incrementals[snum].length > 0 && incpos == 0) {
		for (var i = 0; i < incrementals[snum].length; i++) {
			if (hasClass(incrementals[snum][i], 'current'))
				incpos = i + 1;
			else
				addClass(incrementals[snum][i], 'incremental');
		}
	}
	if (incrementals[snum].length > 0 && incpos > 0)
		addClass(incrementals[snum][incpos - 1], 'current');
	if (isOp) { //hallvord
		location.hash = nid;
	} else {
		ce.style.visibility = 'hidden';
		ne.style.visibility = 'visible';
	} // /hallvord
	jl.selectedIndex = snum;
	currentSlide();
	loadNote();
	permaLink();
	number = undef;
}

function goTo(target) {
	if (target >= smax || target == snum) return;
	go(target - snum);
}

function subgo(step) {
	if (step > 0) {
		removeClass(incrementals[snum][incpos - 1],'current');
		removeClass(incrementals[snum][incpos], 'incremental');
		addClass(incrementals[snum][incpos],'current');
		incpos++;
	} else {
		incpos--;
		removeClass(incrementals[snum][incpos],'current');
		addClass(incrementals[snum][incpos], 'incremental');
		addClass(incrementals[snum][incpos - 1],'current');
	}
	loadNote();
}

function toggle() {
	var slideColl = GetElementsWithClassName('*','slide');
	var slides = document.getElementById('slideProj');
	var outline = document.getElementById('outlineStyle');
	if (!slides.disabled) {
		slides.disabled = true;
		outline.disabled = false;
		s5mode = false;
		fontSize('1em');
		for (var n = 0; n < smax; n++) {
			var slide = slideColl[n];
			slide.style.visibility = 'visible';
		}
	} else {
		slides.disabled = false;
		outline.disabled = true;
		s5mode = true;
		fontScale();
		for (var n = 0; n < smax; n++) {
			var slide = slideColl[n];
			slide.style.visibility = 'hidden';
		}
		slideColl[snum].style.visibility = 'visible';
	}
}

function showHide(action) {
	var obj = GetElementsWithClassName('*','hideme')[0];
	switch (action) {
	case 's': obj.style.visibility = 'visible'; break;
	case 'h': obj.style.visibility = 'hidden'; break;
	case 'k':
		if (obj.style.visibility != 'visible') {
			obj.style.visibility = 'visible';
		} else {
			obj.style.visibility = 'hidden';
		}
	break;
	}
}

// 'keys' code adapted from MozPoint (http://mozpoint.mozdev.org/)
function keys(key) {
	if (!key) {
		key = event;
		key.which = key.keyCode;
	}
	if (key.which == 84) {
		toggle();
		return;
	}
	if (s5mode) {
		switch (key.which) {
			case 10: // return
			case 13: // enter
				if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return;
				if (key.target && isParentOrSelf(key.target, 'controls')) return;
				if(number != undef) {
					goTo(number);
					break;
				}
			case 32: // spacebar
			case 34: // page down
			case 39: // rightkey
			case 40: // downkey
				if(number != undef) {
					go(number);
				} else if (!incrementals[snum] || incpos >= incrementals[snum].length) {
					go(1);
				} else {
					subgo(1);
				}
				break;
			case 33: // page up
			case 37: // leftkey
			case 38: // upkey
				if(number != undef) {
					go(-1 * number);
				} else if (!incrementals[snum] || incpos <= 0) {
					go(-1);
				} else {
					subgo(-1);
				}
				break;
			case 36: // home
				goTo(0);
				break;
			case 35: // end
				goTo(smax-1);
				break;
			case 67: // c
				showHide('k');
				break;
			case 78: // n
				createNotesWindow();
				break;
		}
		if (key.which < 48 || key.which > 57) {
			number = undef;
		} else {
			if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return;
			if (key.target && isParentOrSelf(key.target, 'controls')) return;
			number = (((number != undef) ? number : 0) * 10) + (key.which - 48);
		}
	}
	return false;
}

function clicker(e) {
	number = undef;
	var target;
	if (window.event) {
		target = window.event.srcElement;
		e = window.event;
	} else target = e.target;
	if (target.href != null || hasValue(target.rel, 'external') || isParentOrSelf(target, 'controls') || isParentOrSelf(target,'embed') || isParentOrSelf(target,'object')) return true;
	if (!e.which || e.which == 1) {
		if (!incrementals[snum] || incpos >= incrementals[snum].length) {
			go(1);
		} else {
			subgo(1);
		}
	}
}

function findSlide(hash) {
	var target = null;
	var slides = GetElementsWithClassName('*','slide');
	for (var i = 0; i < slides.length; i++) {
		var targetSlide = slides[i];
		if ( (targetSlide.name && targetSlide.name == hash)
		 || (targetSlide.id && targetSlide.id == hash) ) {
			target = targetSlide;
			break;
		}
	}
	while(target != null && target.nodeName != 'BODY') {
		if (hasClass(target, 'slide')) {
			return parseInt(target.id.slice(5));
		}
		target = target.parentNode;
	}
	return null;
}

function slideJump() {
	if (window.location.hash == null) return;
	var sregex = /^#slide(\d+)$/;
	var matches = sregex.exec(window.location.hash);
	var dest = null;
	if (matches != null) {
		dest = parseInt(matches[1]);
	} else {
		dest = findSlide(window.location.hash.slice(1));
	}
	if (dest != null)
		go(dest - snum);
}

function fixLinks() {
	var thisUri = window.location.href;
	thisUri = thisUri.slice(0, thisUri.length - window.location.hash.length);
	var aelements = document.getElementsByTagName('A');
	for (var i = 0; i < aelements.length; i++) {
		var a = aelements[i].href;
		var slideID = a.match('\#slide[0-9]{1,2}');
		if ((slideID) && (slideID[0].slice(0,1) == '#')) {
			var dest = findSlide(slideID[0].slice(1));
			if (dest != null) {
				if (aelements[i].addEventListener) {
					aelements[i].addEventListener("click", new Function("e",
						"if (document.getElementById('slideProj').disabled) return;" +
						"go("+dest+" - snum); " +
						"if (e.preventDefault) e.preventDefault();"), true);
				} else if (aelements[i].attachEvent) {
					aelements[i].attachEvent("onclick", new Function("",
						"if (document.getElementById('slideProj').disabled) return;" +
						"go("+dest+" - snum); " +
						"event.returnValue = false;"));
				}
			}
		}
	}
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName('a');
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute('href') && hasValue(anchor.rel, 'external')) {
			anchor.target = '_blank';
			addClass(anchor,'external');
		}
	}
}

function permaLink() {
	document.getElementById('plink').href = window.location.pathname + '#slide' + snum;
}

function createControls() {
	var controlsDiv = document.getElementById("controls");
	if (!controlsDiv) return;
	var hider = ' onmouseover="showHide(\'s\');" onmouseout="showHide(\'h\');"';
	var hideDiv, hideList = '';
	if (controlVis == 'hidden') {
		hideDiv = hider;
	} else {
		hideList = hider;
	}
	controlsDiv.innerHTML = '<form action="#" id="controlForm"' + hideDiv + '>' +
	'
' +
	'≡<\/a>' +
	'Ø<\/a>' +
	'«<\/a>' +
	'»<\/a>' +
	'
<select id="jumplist" onchange="go(\'j\');"><\/select><\/div>' +
	'<\/div><\/form>';
	if (controlVis == 'hidden') {
		var hidden = document.getElementById('navLinks');
	} else {
		var hidden = document.getElementById('jumplist');
	}
	addClass(hidden,'hideme');
}

function fontScale() {  // causes layout problems in FireFox that get fixed if browser's Reload is used; same may be true of other Gecko-based browsers
	if (!s5mode) return false;
	var vScale = 48;  // both yield 16 (the usual browser default) at 1024x768
	var hScale = 64;  // perhaps should auto-calculate based on theme's declared value?
	if (window.innerHeight) {
		var vSize = window.innerHeight;
		var hSize = window.innerWidth;
	} else if (document.documentElement.clientHeight) {
		var vSize = document.documentElement.clientHeight;
		var hSize = document.documentElement.clientWidth;
	} else if (document.body.clientHeight) {
		var vSize = document.body.clientHeight;
		var hSize = document.body.clientWidth;
	} else {
		var vSize = 700;  // assuming 1024x768, minus chrome and such
		var hSize = 1024; // these do not account for kiosk mode or Opera Show
	}
	var newSize = Math.min(Math.round(vSize/vScale),Math.round(hSize/hScale));
	fontSize(newSize + 'px');
	if (isGe) {  // hack to counter incremental reflow bugs
		var obj = document.getElementsByTagName('body')[0];
		obj.style.display = 'none';
		obj.style.display = 'block';
	}
}

function fontSize(value) {
	if (!(s5ss = document.getElementById('s5ss'))) {
		if (!document.createStyleSheet) {
			document.getElementsByTagName('head')[0].appendChild(s5ss = document.createElement('style'));
			s5ss.setAttribute('media','screen, projection');
			s5ss.setAttribute('id','s5ss');
		} else {
			document.createStyleSheet();
			document.s5ss = document.styleSheets[document.styleSheets.length - 1];
		}
	}
	if (!(document.s5ss && document.s5ss.addRule)) {
		while (s5ss.lastChild) s5ss.removeChild(s5ss.lastChild);
		s5ss.appendChild(document.createTextNode('html {font-size: ' + value + ' !important;}'));
	} else {
		document.s5ss.addRule('html','font-size: ' + value + ' !important;');
	}
}

function notOperaFix() {
	slideCSS = document.getElementById('slideProj').href;
	var slides = document.getElementById('slideProj');
	var outline = document.getElementById('outlineStyle');
	slides.setAttribute('media','screen');
	outline.disabled = true;
	if (isGe) {
		slides.setAttribute('href','null');   // Gecko fix
		slides.setAttribute('href',slideCSS); // Gecko fix
	}
	if (isIE && document.styleSheets && document.styleSheets[0]) {
		document.styleSheets[0].addRule('img', 'behavior: url(ui/default/iepngfix.htc)');
		document.styleSheets[0].addRule('div', 'behavior: url(ui/default/iepngfix.htc)');
		document.styleSheets[0].addRule('.slide', 'behavior: url(ui/default/iepngfix.htc)');
	}
}

function getIncrementals(obj) {
	var incrementals = new Array();
	if (!obj)
		return incrementals;
	var children = obj.childNodes;
	for (var i = 0; i < children.length; i++) {
		var child = children[i];
		if (hasClass(child, 'incremental')) {
			if (child.nodeName == 'OL' || child.nodeName == 'UL') {
				removeClass(child, 'incremental');
				for (var j = 0; j < child.childNodes.length; j++) {
					if (child.childNodes[j].nodeType == 1) {
						addClass(child.childNodes[j], 'incremental');
					}
				}
			} else {
				incrementals[incrementals.length] = child;
				removeClass(child,'incremental');
			}
		}
		if (hasClass(child, 'show-first')) {
			if (child.nodeName == 'OL' || child.nodeName == 'UL') {
				removeClass(child, 'show-first');
				if (child.childNodes[isGe].nodeType == 1) {
					removeClass(child.childNodes[isGe], 'incremental');
				}
			} else {
				incrementals[incrementals.length] = child;
			}
		}
		incrementals = incrementals.concat(getIncrementals(child));
	}
	return incrementals;
}

function createIncrementals() {
	var incrementals = new Array();
	for (var i = 0; i < smax; i++) {
		incrementals[i] = getIncrementals(document.getElementById('slide'+i));
	}
	return incrementals;
}

function defaultCheck() {
	var allMetas = document.getElementsByTagName('meta');
	for (var i = 0; i< allMetas.length; i++) {
		if (allMetas[i].name == 'defaultView') {
			defaultView = allMetas[i].content;
		}
		if (allMetas[i].name == 'controlVis') {
			controlVis = allMetas[i].content;
		}
	}
}

// Key trap fix, new function body for trap()
function trap(e) {
	if (!e) {
		e = event;
		e.which = e.keyCode;
	}
	try {
		modifierKey = e.ctrlKey || e.altKey || e.metaKey;
	}
	catch(e) {
		modifierKey = false;
	}
	return modifierKey || e.which == 0;
}

function noteLabel() { // Gives notes id's to match parent slides
	var notes = GetElementsWithClassName('div','notes');
	for (var i = 0; i < notes.length; i++) {
		var note = notes[i];
		var id = 'note' + note.parentNode.id.substring(5);
		note.setAttribute('id',id);
	}
	resetElapsedSlide();
	resetRemainingTime();
	window.setInterval('updateElaspedTime()', 1000);
}

function createNotesWindow() { // creates a window for our notes
	if (!s5NotesWindow || s5NotesWindow.closed) { // Create the window if it doesn't exist
		s5NotesWindowLoaded = false;
		// Note: Safari has a tendency to ignore window options preferring to default to the settings of the parent window, grr.
		s5NotesWindow = window.open('ui/s5-notes.html', 's5NotesWindow', 'top=0,left=0');
	}
	if (s5NotesWindowLoaded) { // Load the current note if the Note HTML has loaded
		loadNote();
	} else { // Keep trying...
		window.setTimeout('createNotesWindow()', 50);
	}
}

function loadNote() {
// Loads a note into the note window
	var notes = nextNotes = 'There are no notes for this slide.';
	if (document.getElementById('note' + snum)) {
		notes = document.getElementById('note' + snum).innerHTML;
	}
	if (document.getElementById('note' + (snum + 1))) {
		nextNotes = document.getElementById('note' + (snum + 1)).innerHTML;
	}

	var jl = document.getElementById('jumplist');
	var slideTitle = jl.options[jl.selectedIndex].text.replace(/^\d+\s+:\s+/, '') + ((jl.selectedIndex) ? ' (' + jl.selectedIndex + '/' + (smax - 1) + ')' : '');
	if (incrementals[snum].length > 0) {
//		alert('howdy');
		slideTitle += ' [' + incpos + '/' + incrementals[snum].length + ']';
	}
	if (jl.selectedIndex < smax - 1) {
		var nextTitle = jl.options[jl.selectedIndex + 1].text.replace(/^\d+\s+:\s+/, '') + ((jl.selectedIndex + 1) ? ' (' + (jl.selectedIndex + 1) + '/' + (smax - 1) + ')' : '');
	} else {
		var nextTitle = '[end of slide show]';
	}

	if (s5NotesWindow && !s5NotesWindow.closed && s5NotesWindow.document) {
		s5NotesWindow.document.getElementById('slide').innerHTML = slideTitle;
		s5NotesWindow.document.getElementById('notes').innerHTML = notes;
		s5NotesWindow.document.getElementById('next').innerHTML = nextTitle;
		s5NotesWindow.document.getElementById('nextnotes').innerHTML = nextNotes;
	}
	resetElapsedSlide();
}

function minimizeTimer(id) {
	var obj = s5NotesWindow.document.getElementById(id);
	if (hasClass(obj,'collapsed')) {
		removeClass(obj,'collapsed');
	} else {
		addClass(obj,'collapsed');
	}
}

function resetElapsedTime() {
	presentationStart = new Date();
	slideStart = new Date();
	updateElaspedTime();
}

function resetElapsedSlide() {
	if (snum != previousSlide) {
		slideStart = new Date();
		previousSlide = snum;
		updateElaspedTime();
	}
}

function updateElaspedTime() {
	if (!s5NotesWindowLoaded || !s5NotesWindow || s5NotesWindow.closed) return;
	var now = new Date();
	var ep = s5NotesWindow.document.getElementById('elapsed-presentation');
	var es = s5NotesWindow.document.getElementById('elapsed-slide');
	ep.innerHTML = formatTime(now.valueOf() - presentationStart.valueOf());
	es.innerHTML = formatTime(now.valueOf() - slideStart.valueOf());
}

function resetRemainingTime() {
	if (!s5NotesWindowLoaded || !s5NotesWindow || s5NotesWindow.closed) return;
	var startField = s5NotesWindow.document.getElementById('startFrom');
	startFrom = readTime(startField.value);
	countdown.remaining = startFrom * 60000;  // convert to msecs
	countdown.start = new Date().valueOf();
	countdown.end = countdown.start + countdown.remaining;
	var tl = s5NotesWindow.document.getElementById('timeLeft');
	var timeLeft = formatTime(countdown.remaining);
	tl.innerHTML = timeLeft;
}

function updateRemainingTime() {
	if (!s5NotesWindowLoaded || !s5NotesWindow || s5NotesWindow.closed) return;
	var tl = s5NotesWindow.document.getElementById('timeLeft');
	var now = new Date();
	if (countdown.state == 'run') {
		countdown.remaining = countdown.end - now;
	}
	tl.style.color = '';
	tl.style.backgroundColor = '';
	if (countdown.remaining >= 0) {
		var timeLeft = formatTime(countdown.remaining);
		removeClass(tl,'overtime');
		if (countdown.remaining < 300000) {
			tl.style.color = 'rgb(' + (255-Math.round(countdown.remaining/2000)) + ',0,0)';
			tl.style.backgroundColor = 'rgb(255,255,' + (Math.round(countdown.remaining/2000)) + ')';
		}
	} else {
		var timeLeft = '-' + formatTime(-countdown.remaining);
		addClass(tl,'overtime');
	}
	tl.innerHTML = timeLeft;
}

function toggleRemainingTime() {
	if (countdown.state == 'pause') countdown.state = 'run'; else countdown.state = 'pause';
	if (countdown.state == 'pause') {
		window.clearInterval(countdown.timer);
	}
	if (countdown.state == 'run') {
		countdown.start = new Date().valueOf();
		countdown.end = countdown.start + countdown.remaining;
		countdown.timer = window.setInterval('updateRemainingTime()', 1000);
	}
}

function alterRemainingTime(amt) {
	var change = amt * 60000;  // convert to msecs
	countdown.end += change;
	countdown.remaining += change;
	updateRemainingTime();
}

function formatTime(msecs)  {
	var time = new Date(msecs);

	var hrs = time.getUTCHours() + ((time.getUTCDate() -1) * 24); // I doubt anyone will spend more than 24 hours on a presentation or single slide but just in case...
	hrs = (hrs < 10) ? '0'+hrs : hrs;
	if (hrs == 'NaN' || isNaN(hrs)) hrs = '--';

	var min = time.getUTCMinutes();
	min = (min < 10) ? '0'+min : min;
	if (min == 'NaN' || isNaN(min)) min = '--';

	var sec = time.getUTCSeconds();
	sec = (sec < 10) ? '0'+sec : sec;
	if (sec == 'NaN' || isNaN(sec)) sec = '--';

	return hrs + ':' + min + ':' + sec;
}

function readTime(val) {
	var sregex = /:/;
	var matches = sregex.exec(val);
	if (matches == null) {
		return val;
	} else {
		var times = val.split(':');
		var hours = parseInt(times[0]);
		var mins = parseInt(times[1]);
		var total = (hours * 60) + mins;
		return total;
	}
}

function windowChange() {
	fontScale();
}

function startup() {
	defaultCheck();
	createControls();  // hallvord
	slideLabel();
	incrementals = createIncrementals();
	noteLabel(); // [SI:060104] must follow slideLabel()
	loadNote();
	fixLinks();
	externalLinks();
	fontScale();
	if (!isOp) notOperaFix();
	slideJump();
	if (defaultView == 'outline') {
		toggle();
	}
	document.onkeyup = keys;
	document.onkeypress = trap;
	document.onclick = clicker;
}

window.onload = startup;
window.onresize = function(){setTimeout('windowChange()',5);}


text:
// Generated by gtkmmproc -- DO NOT MODIFY!

#include <gdkmm/rectangle.h>
#include <gdkmm/private/rectangle_p.h>

// -*- c++ -*-
/* $Id: rectangle.ccg,v 1.1 2003/01/21 13:38:38 murrayc Exp $ */

/*
 *
 * Copyright 1998-2002 The gtkmm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

namespace Gdk
{

Rectangle::Rectangle(int x, int y, int width, int height)
{
  gobject_.x = x;
  gobject_.y = y;
  gobject_.width  = width;
  gobject_.height = height;
}

// gdk_rectangle_union() and gdk_rectangle_intersect() work fine even if
// the destination points to one of the input rectangles.  The join() and
// intersect() implementations rely on this ability.

Rectangle& Rectangle::join(const Rectangle& src2)
{
  gdk_rectangle_union(
      &gobject_, const_cast<GdkRectangle*>(&src2.gobject_), &gobject_);
  return *this;
}

Rectangle& Rectangle::intersect(const Rectangle& src2)
{
  gdk_rectangle_intersect(
      &gobject_, const_cast<GdkRectangle*>(&src2.gobject_), &gobject_);
  return *this;
}

Rectangle& Rectangle::intersect(const Rectangle& src2, bool& rectangles_intersect)
{
  rectangles_intersect = gdk_rectangle_intersect(
      &gobject_, const_cast<GdkRectangle*>(&src2.gobject_), &gobject_);
  return *this;
}

bool Rectangle::has_zero_area() const
{
  return (gobject_.width == 0 || gobject_.height == 0);
}

} // namespace Gdk

namespace
{
} // anonymous namespace

namespace Glib
{

Gdk::Rectangle& wrap(GdkRectangle* object)
{
  return *reinterpret_cast<Gdk::Rectangle*>(object);
}

const Gdk::Rectangle& wrap(const GdkRectangle* object)
{
  return *reinterpret_cast<const Gdk::Rectangle*>(object);
}

} // namespace Glib

namespace Gdk
{

// static
GType Rectangle::get_type()
{
  return gdk_rectangle_get_type();
}

Rectangle::Rectangle()
{
  GLIBMM_INITIALIZE_STRUCT(gobject_, GdkRectangle);
}

Rectangle::Rectangle(const GdkRectangle* gobject)
{
  if(gobject)
    gobject_ = *gobject;
  else
    GLIBMM_INITIALIZE_STRUCT(gobject_, GdkRectangle);
}

 int Rectangle::get_x() const
{
  return gobj()->x;
}

 void Rectangle::set_x(const int& value)
{
  gobj()->x = value;
}

 int Rectangle::get_y() const
{
  return gobj()->y;
}

 void Rectangle::set_y(const int& value)
{
  gobj()->y = value;
}

 int Rectangle::get_width() const
{
  return gobj()->width;
}

 void Rectangle::set_width(const int& value)
{
  gobj()->width = value;
}

 int Rectangle::get_height() const
{
  return gobj()->height;
}

 void Rectangle::set_height(const int& value)
{
  gobj()->height = value;
}

} // namespace Gdk


text:
require 'hpricot'
require 'hashie/mash'

module WebParser
  module YandexExport
    # Казань
    KAZAN_REGION_URL = 'http://export.yandex.ru/bar/reginfo.xml?region=43'

    module_function

    def day_weather
      xml = Hpricot(open(KAZAN_REGION_URL, &:read))
      weather = xml/:weather
      date_info = (weather/:date).first
      day_parts = (weather/:day_part).map do |day_part|
        {
          type_id:              day_part[:typeid],
          type_name:            day_part[:type],
          type_name:            day_part[:type],
          text:                 (day_part/:weather_type).first.try(:innerText),
          code:                 (day_part/:weather_code).first.try(:innerText),
          images: {
            image_1: {
              url: (day_part/:image).first.try(:innerText),
              size: (day_part/:image).first.try(:[], :size),
            },
            # 22x22
            image_2: {
              url: (day_part/'image-v2').first.try(:innerText),
              size: (day_part/'image-v2').first.try(:[], :size),
            },
            # 48x48
            image_3: {
              url: (day_part/'image-v3').first.try(:innerText),
              size: (day_part/'image-v3').first.try(:[], :size),
            },
          },
          image_number:         (day_part/:image_number).first.try(:innerText),
          wind_speed:           (day_part/:wind_speed).first.try(:innerText),
          wind_direction_text:  (day_part/:wind_direction).first.try(:innerText),
          wind_direction_id:    (day_part/:wind_direction).first.try(:[], :id),
          dampness:             (day_part/:dampness).first.try(:innerText),
          pressure:             (day_part/:pressure).first.try(:innerText),
          observation:          (Time.parse((day_part/:observation).first.innerText) rescue nil),
          temperature:          (day_part/:temperature).first.try(:innerText),
          temperature_from:     (day_part/:temperature_from).first.try(:innerText),
          temperature_to:       (day_part/:temperature_to).first.try(:innerText),
        }
      end

      Hashie::Mash.new(
        date: Date.parse(date_info[:date]),
        day_parts: day_parts,
        tomorrow: (((weather/:tomorrow).first/:temperature).first.innerText rescue nil)
      )
    rescue => e
      puts 'Parse error'
      puts e.message
      puts e.backtrace
      {}
    end

    # Получаем данные о трафике на дорогах
    def traffic
      xml = Hpricot(open(KAZAN_REGION_URL, &:read))
      traffic = xml/:traffic
      timestamp = (traffic/:timestamp).first.innerText.to_i
      details = {
        length: (traffic/:length).first.try(:innerText),
        level: (traffic/:level).first.try(:innerText),
        icon: (traffic/:icon).first.try(:innerText),
        time: (traffic/:time).first.try(:innerText),
        hint: (traffic/:hint).each_with_object({}) do |hint_node, result|
          result[hint_node[:lang]] = hint_node.innerText
        end,
        tend: (traffic/:tend).first.try(:innerText)
      }
      Hashie::Mash.new(
        datetime: Time.at(timestamp),
        details: details,
        url: ((traffic/:url).first.try(:innerText) rescue nil)
      )
    rescue => e
      puts 'Parse error'
      puts e.message
      puts e.backtrace
      {}
    end
  end
end


text:
require 'spec_helper'

RSpec.describe Dnsimple::Options::Base do
  describe '#initialize' do
    it 'accepts a hash' do
      hash = { a: 1 }
      expect(described_class.new(hash).to_h).to eq(hash)
    end

    it 'accepts nil' do
      expect(described_class.new(nil).to_h).to eq({})
    end

    it 'duplicates given hash' do
      hash = { a: [1] }
      base = described_class.new(hash)
      base.to_h[:a] << 2

      expect(base.to_h).to eq(hash)
    end
  end
end


text:
package org.drools.guvnor.server.converters;

import org.drools.guvnor.client.rpc.ConversionResult;
import org.drools.repository.AssetItem;

/**
 * A converter from one format to another
 */
public abstract class AbstractConverter {

    private String targetFormat;

    public AbstractConverter() {
    }

    public AbstractConverter(String targetFormat) {
        this.targetFormat = targetFormat;
    }

    /**
     * Does this Converter handle the specified format
     *
     * @param targetFormat
     */
    public boolean isTargetFormatSupported(String targetFormat) {
        return this.targetFormat.equals( targetFormat );
    }

    public abstract ConversionResult convert(final AssetItem item);

}


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var _ = require('lodash');  /* jshint ignore:line */
var Holodeck = require('../../../../../holodeck');  /* jshint ignore:line */
var Request = require(
    '../../../../../../../lib/http/request');  /* jshint ignore:line */
var Response = require(
    '../../../../../../../lib/http/response');  /* jshint ignore:line */
var RestException = require(
    '../../../../../../../lib/base/RestException');  /* jshint ignore:line */
var Twilio = require('../../../../../../../lib');  /* jshint ignore:line */

var client;
var holodeck;

describe('Invite', function() {
  beforeEach(function() {
    holodeck = new Holodeck();
    client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
      httpClient: holodeck
    });
  });
  it('should generate valid fetch request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites('INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var solution = {
        serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        channelSid: 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        sid: 'INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
      };
      var url = _.template('https://chat.twilio.com/v2/Services/<%= serviceSid %>/Channels/<%= channelSid %>/Invites/<%= sid %>')(solution);

      holodeck.assertHasRequest(new Request({
        method: 'GET',
        url: url
      }));
    }
  );
  it('should generate valid fetch response',
    function() {
      var body = JSON.stringify({
          'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'created_by': 'created_by',
          'date_created': '2015-07-30T20:00:00Z',
          'date_updated': '2015-07-30T20:00:00Z',
          'identity': 'identity',
          'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'sid': 'INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
      });

      holodeck.mock(new Response(200, body));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites('INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid create request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var opts = {identity: 'identity'};
      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites.create(opts);
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var solution = {
        serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        channelSid: 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
      };
      var url = _.template('https://chat.twilio.com/v2/Services/<%= serviceSid %>/Channels/<%= channelSid %>/Invites')(solution);

      var values = {Identity: 'identity', };
      holodeck.assertHasRequest(new Request({
          method: 'POST',
          url: url,
          data: values
      }));
    }
  );
  it('should generate valid create response',
    function() {
      var body = JSON.stringify({
          'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'created_by': 'created_by',
          'date_created': '2015-07-30T20:00:00Z',
          'date_updated': '2015-07-30T20:00:00Z',
          'identity': 'identity',
          'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'sid': 'INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
          'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
      });

      holodeck.mock(new Response(201, body));

      var opts = {identity: 'identity'};
      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites.create(opts);
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should treat the first each arg as a callback',
    function(done) {
      var body = JSON.stringify({
          'invites': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'created_by': 'created_by',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'identity': 'identity',
                  'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'sid': 'INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0',
              'key': 'invites',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0'
          }
      });
      holodeck.mock(new Response(200, body));
      client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                           .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                           .invites.each(() => done());
    }
  );
  it('should treat the second arg as a callback',
    function(done) {
      var body = JSON.stringify({
          'invites': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'created_by': 'created_by',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'identity': 'identity',
                  'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'sid': 'INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0',
              'key': 'invites',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0'
          }
      });
      holodeck.mock(new Response(200, body));
      client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                           .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                           .invites.each({pageSize: 20}, () => done());
      holodeck.assertHasRequest(new Request({
          method: 'GET',
          url: 'https://chat.twilio.com/v2/Services/<%= serviceSid %>/Channels/<%= channelSid %>/Invites',
          params: {PageSize: 20},
      }));
    }
  );
  it('should find the callback in the opts object',
    function(done) {
      var body = JSON.stringify({
          'invites': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'created_by': 'created_by',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'identity': 'identity',
                  'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'sid': 'INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0',
              'key': 'invites',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0'
          }
      });
      holodeck.mock(new Response(200, body));
      client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                           .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                           .invites.each({callback: () => done()}, () => fail('wrong callback!'));
    }
  );
  it('should generate valid list request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites.list();
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var solution = {
        serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        channelSid: 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
      };
      var url = _.template('https://chat.twilio.com/v2/Services/<%= serviceSid %>/Channels/<%= channelSid %>/Invites')(solution);

      holodeck.assertHasRequest(new Request({
        method: 'GET',
        url: url
      }));
    }
  );
  it('should generate valid read_empty response',
    function() {
      var body = JSON.stringify({
          'invites': [],
          'meta': {
              'first_page_url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0',
              'key': 'invites',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0'
          }
      });

      holodeck.mock(new Response(200, body));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites.list();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid read_full response',
    function() {
      var body = JSON.stringify({
          'invites': [
              {
                  'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'created_by': 'created_by',
                  'date_created': '2015-07-30T20:00:00Z',
                  'date_updated': '2015-07-30T20:00:00Z',
                  'identity': 'identity',
                  'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'sid': 'INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
                  'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
              }
          ],
          'meta': {
              'first_page_url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0',
              'key': 'invites',
              'next_page_url': null,
              'page': 0,
              'page_size': 50,
              'previous_page_url': null,
              'url': 'https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0'
          }
      });

      holodeck.mock(new Response(200, body));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites.list();
      promise = promise.then(function(response) {
        expect(response).toBeDefined();
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
  it('should generate valid remove request',
    function() {
      holodeck.mock(new Response(500, '{}'));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites('INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
      promise = promise.then(function() {
        throw new Error('failed');
      }, function(error) {
        expect(error.constructor).toBe(RestException.prototype.constructor);
      });
      promise.done();

      var solution = {
        serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        channelSid: 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        sid: 'INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
      };
      var url = _.template('https://chat.twilio.com/v2/Services/<%= serviceSid %>/Channels/<%= channelSid %>/Invites/<%= sid %>')(solution);

      holodeck.assertHasRequest(new Request({
        method: 'DELETE',
        url: url
      }));
    }
  );
  it('should generate valid delete response',
    function() {
      var body = JSON.stringify(null);

      holodeck.mock(new Response(204, body));

      var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                                         .invites('INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
      promise = promise.then(function(response) {
        expect(response).toBe(true);
      }, function() {
        throw new Error('failed');
      });

      promise.done();
    }
  );
});


text:
export default interface TooltipOptions {
    event?: string;
    position?: string;
    showDelay?: number;
    hideDelay?: number;
}


text: Hello GodsSampleIM