text:
package org.apache.storm.topology;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.storm.Config;
import org.apache.storm.generated.GlobalStreamId;
import org.apache.storm.generated.Grouping;
import org.apache.storm.state.KeyValueState;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.windowing.TupleWindow;
import org.apache.storm.windowing.TupleWindowImpl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import static org.apache.storm.topology.StatefulWindowedBoltExecutor.TaskStream;
import static org.apache.storm.topology.StatefulWindowedBoltExecutor.WindowState;

/**
 * Unit tests for {@link StatefulWindowedBoltExecutor}
 */
public class StatefulWindowedBoltExecutorTest {
    StatefulWindowedBoltExecutor<KeyValueState<String, String>> executor;

    IStatefulWindowedBolt<KeyValueState<String, String>> mockBolt;
    OutputCollector mockOutputCollector;
    TopologyContext mockTopologyContext;
    Map<String, Object> mockStormConf = new HashMap<>();

    @Before
    public void setUp() throws Exception {
        mockBolt = Mockito.mock(IStatefulWindowedBolt.class);
        mockTopologyContext = Mockito.mock(TopologyContext.class);
        mockOutputCollector = Mockito.mock(OutputCollector.class);
        executor = new StatefulWindowedBoltExecutor<>(mockBolt);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testPrepare() throws Exception {
        executor.prepare(mockStormConf, mockTopologyContext, mockOutputCollector);
    }

    @Test
    public void testPrepareWithMsgid() throws Exception {
        mockStormConf.put(Config.TOPOLOGY_BOLTS_MESSAGE_ID_FIELD_NAME, "msgid");
        mockStormConf.put(Config.TOPOLOGY_BOLTS_WINDOW_LENGTH_COUNT, 5);
        mockStormConf.put(Config.TOPOLOGY_BOLTS_SLIDING_INTERVAL_COUNT, 5);
        executor.prepare(mockStormConf, mockTopologyContext, mockOutputCollector);
    }

    @Test
    public void testExecute() throws Exception {
        mockStormConf.put(Config.TOPOLOGY_BOLTS_MESSAGE_ID_FIELD_NAME, "msgid");
        mockStormConf.put(Config.TOPOLOGY_BOLTS_WINDOW_LENGTH_COUNT, 5);
        mockStormConf.put(Config.TOPOLOGY_BOLTS_SLIDING_INTERVAL_COUNT, 5);
        KeyValueState<TaskStream, WindowState> mockState;
        mockState = Mockito.mock(KeyValueState.class);
        executor.prepare(mockStormConf, mockTopologyContext, mockOutputCollector, mockState);
        executor.initState(null);
        List<Tuple> tuples = getMockTuples(5);
        for (Tuple tuple : tuples) {
            executor.execute(tuple);
        }
        Mockito.verify(mockBolt, Mockito.times(1)).execute(getTupleWindow(tuples));
        WindowState expectedState = new WindowState(Long.MIN_VALUE, 4);
        Mockito.verify(mockState, Mockito.times(1)).put(Mockito.any(TaskStream.class), Mockito.eq(expectedState));
    }

    @Test
    public void testRecovery() throws Exception {
        mockStormConf.put(Config.TOPOLOGY_BOLTS_MESSAGE_ID_FIELD_NAME, "msgid");
        mockStormConf.put(Config.TOPOLOGY_BOLTS_WINDOW_LENGTH_COUNT, 5);
        mockStormConf.put(Config.TOPOLOGY_BOLTS_SLIDING_INTERVAL_COUNT, 5);
        KeyValueState<TaskStream, WindowState> mockState;
        mockState = Mockito.mock(KeyValueState.class);
        Map<GlobalStreamId, Grouping> mockMap = Mockito.mock(Map.class);
        Mockito.when(mockTopologyContext.getThisSources()).thenReturn(mockMap);
        Mockito.when(mockTopologyContext.getComponentTasks(Mockito.anyString())).thenReturn(Collections.singletonList(1));
        Mockito.when(mockMap.keySet()).thenReturn(Collections.singleton(new GlobalStreamId("a", "s")));
        WindowState mockWindowState = new WindowState(4, 4);
        Mockito.when(mockState.get(Mockito.any(TaskStream.class))).thenReturn(mockWindowState);
        executor.prepare(mockStormConf, mockTopologyContext, mockOutputCollector, mockState);
        executor.initState(null);
        List<Tuple> tuples = getMockTuples(10);
        for (Tuple tuple : tuples) {
            executor.execute(tuple);
        }
        WindowState expectedState = new WindowState(4, 9);
        Mockito.verify(mockState, Mockito.times(1)).put(Mockito.any(TaskStream.class), Mockito.eq(expectedState));
    }

    private TupleWindow getTupleWindow(List<Tuple> tuples) {
        return new TupleWindowImpl(tuples, tuples, Collections.<Tuple>emptyList());
    }

    private List<Tuple> getMockTuples(int count) {
        List<Tuple> mockTuples = new ArrayList<>();
        for (long i = 0; i < count; i++) {
            Tuple mockTuple = Mockito.mock(Tuple.class);
            Mockito.when(mockTuple.getLongByField("msgid")).thenReturn(i);
            Mockito.when(mockTuple.getSourceTask()).thenReturn(1);
            Mockito.when(mockTuple.getSourceGlobalStreamId()).thenReturn(new GlobalStreamId("a", "s"));
            mockTuples.add(mockTuple);
        }
        return mockTuples;
    }
}


text:
#ifndef _SMT_QUICK_CHECKER_H_
#define _SMT_QUICK_CHECKER_H_

#include"ast.h"
#include"simplifier.h"
#include"obj_hashtable.h"

namespace smt {
    class context;

    /**
       \brief Simple object for finding quantifier instantiations that are falsified by the current model.

       \remark The code for selecting candidates is very naive.
    */
    class quick_checker {
        typedef obj_hashtable<enode> enode_set;

        /**
           \brief Functor for collecting candidates for quantifier instantiation.
        */
        class collector {
            context &            m_context;
            ast_manager &        m_manager;
            bool                 m_conservative;
            unsigned             m_num_vars;
            svector<bool>        m_already_found;     // mapping from var_idx -> bool
            vector<enode_set>    m_candidates;        // mapping from var_idx -> set of candidates
            vector<enode_set>    m_tmp_candidates;    // auxiliary mapping from var_idx -> set of candidates

            struct entry {
                expr *      m_expr;
                func_decl * m_parent;
                unsigned    m_parent_pos;
                entry(expr * n = 0, func_decl * d = 0, unsigned p = 0):m_expr(n), m_parent(d), m_parent_pos(p) {}
                unsigned hash() const { return m_parent ? mk_mix(m_expr->get_id(), m_parent->get_id(), m_parent_pos) : m_expr->get_id(); }
                bool operator==(entry const & e) const { return m_expr == e.m_expr && m_parent == e.m_parent && m_parent_pos == e.m_parent_pos; }
            };

            typedef hashtable<entry, obj_hash<entry>, default_eq<entry> > cache;
            cache                m_cache;

            void init(quantifier * q);
            bool check_arg(enode * n, func_decl * f, unsigned i);
            void collect_core(app * n, func_decl * p, unsigned i);
            void collect(expr * n, func_decl * f, unsigned idx);
            void save_result(vector<enode_vector> & candidates);

        public:
            collector(context & c);
            void operator()(quantifier * q, bool conservative, vector<enode_vector> & candidates);
        };

        typedef std::pair<expr *, bool> expr_bool_pair;
        typedef pair_hash<obj_ptr_hash<expr>, int_hash> expr_bool_pair_hash;
        typedef map<expr_bool_pair, bool, expr_bool_pair_hash, default_eq<expr_bool_pair> > check_cache;
        typedef obj_map<expr, expr *> canonize_cache;

        context &            m_context;
        ast_manager &        m_manager;
        simplifier &         m_simplifier;
        collector            m_collector;
        expr_ref_vector      m_new_exprs;
        vector<enode_vector> m_candidate_vectors;
        check_cache          m_check_cache;
        canonize_cache       m_canonize_cache;
        unsigned             m_num_bindings;
        ptr_vector<enode>    m_bindings;

        bool all_args(app * a, bool is_true);
        bool any_arg(app * a, bool is_true);
        bool check_core(expr * n, bool is_true);
        bool check(expr * n, bool is_true);
        bool check_quantifier(quantifier * n, bool is_true);
        expr * canonize(expr * n);
        bool process_candidates(quantifier * q, bool unsat);

    public:
        quick_checker(context & c);
        bool instantiate_unsat(quantifier * q);
        bool instantiate_not_sat(quantifier * q);
        bool instantiate_not_sat(quantifier * q, unsigned num_candidates, expr * const * candidates);
    };
};

#endif /* _SMT_QUICK_CHECKER_H_ */

redpajama_set_name: RedPajamaGithub


text:
package org.gearvrf.bulletphysics.util;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.AbstractList;
import java.util.RandomAccess;

/**
 *
 * @author jezek2
 */
public final class ObjectArrayList<T> extends AbstractList<T> implements RandomAccess, Externalizable {

	private T[] array;
	private int size;

	public ObjectArrayList() {
		this(16);
	}

	@SuppressWarnings("unchecked")
	public ObjectArrayList(int initialCapacity) {
		array = (T[])new Object[initialCapacity];
	}

	@Override
	public boolean add(T value) {
		if (size == array.length) {
			expand();
		}

		array[size++] = value;
		return true;
	}

	@Override
	public void add(int index, T value) {
		if (size == array.length) {
			expand();
		}

		int num = size - index;
		if (num > 0) {
			System.arraycopy(array, index, array, index+1, num);
		}

		array[index] = value;
		size++;
	}

	@Override
	public T remove(int index) {
		if (index < 0 || index >= size) throw new IndexOutOfBoundsException();
		T prev = array[index];
		System.arraycopy(array, index+1, array, index, size-index-1);
		array[size-1] = null;
		size--;
		return prev;
    }

	@SuppressWarnings("unchecked")
	private void expand() {
		T[] newArray = (T[])new Object[array.length << 1];
		System.arraycopy(array, 0, newArray, 0, array.length);
		array = newArray;
	}

	public void removeQuick(int index) {
		System.arraycopy(array, index+1, array, index, size - index - 1);
		array[size-1] = null;
		size--;
	}

	public T get(int index) {
		if (index >= size) throw new IndexOutOfBoundsException();
		return array[index];
	}

	public T getQuick(int index) {
		return array[index];
	}

	@Override
	public T set(int index, T value) {
		if (index >= size) throw new IndexOutOfBoundsException();
		T old = array[index];
		array[index] = value;
		return old;
	}

	public void setQuick(int index, T value) {
		array[index] = value;
	}

	public int size() {
		return size;
	}

	public int capacity() {
		return array.length;
	}

	@Override
	public void clear() {
		size = 0;
	}

	@Override
	public int indexOf(Object o) {
		int _size = size;
		T[] _array = array;
		for (int i=0; i<_size; i++) {
			if (o == null? _array[i] == null : o.equals(_array[i])) {
				return i;
			}
		}
		return -1;
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeInt(size);
		for (int i=0; i<size; i++) {
			out.writeObject(array[i]);
		}
	}

	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		size = in.readInt();
		int cap = 16;
		while (cap < size) cap <<= 1;
		array = (T[])new Object[cap];
		for (int i=0; i<size; i++) {
			array[i] = (T)in.readObject();
		}
	}

}


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef QWEBFRAMESLOTS_H
#define QWEBFRAMESLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>

#include <QtWebKitWidgets/QWebFrame>

#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"

class QWebFrameSlots: public QObject
{
  Q_OBJECT
  public:
  QWebFrameSlots( QObject *parent = 0 );
  ~QWebFrameSlots();
  public slots:
  void contentsSizeChanged( const QSize & size );
  void iconChanged();
  void initialLayoutCompleted();
  void javaScriptWindowObjectCleared();
  void loadFinished( bool ok );
  void loadStarted();
  void pageChanged();
  void titleChanged( const QString & title );
  void urlChanged( const QUrl & url );
};

#endif /* QWEBFRAMESLOTS_H */


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Zao.CrsPlat.DevExpressHelper.ZaoUtil
{
    /// <summary>
    /// 这个类提供了一些实用的方法来转换XML和对象。
    /// </summary>
    public static class ZaoXml {

        /// <summary>
        /// 将XML字符串转换到指定的对象。
        /// </summary>
        /// <param name="xml">XML字符串。</param>
        /// <param name="type">对象的类型。</param>
        /// <returns>从XML字符串反序列化的对象。</returns>
        public static object XmlToObject(string xml, Type type) {
            if (null == xml) {
                throw new ArgumentNullException("xml");
            }
            if (null == type) {
                throw new ArgumentNullException("type");
            }

            object obj = null;
            var serializer = new System.Xml.Serialization.XmlSerializer(type);
            var strReader = new StringReader(xml);
            XmlReader reader = new XmlTextReader(strReader);

            try {
                obj = serializer.Deserialize(reader);
            } catch (InvalidOperationException ie) {
                throw new InvalidOperationException("Can not convert xml to object", ie);
            }
            finally {
                reader.Close();
            }
            return obj;
        }

        /// <summary>
        /// 转换为XML字符串的对象。
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="toBeIndented"><c>true</c> 如果想要的XML字符串的目的,否则 <c>false</c>.</param>
        /// <returns>XML字符串。</returns>
        public static string ObjectToXml(object obj, bool toBeIndented) {
            if (null == obj) {
                throw new ArgumentNullException("obj");
            }
            var encoding = new UTF8Encoding(false);
            var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            var stream = new MemoryStream();
            var writer = new XmlTextWriter(stream, encoding);
            writer.Formatting = (toBeIndented ? Formatting.Indented : Formatting.None);

            try {
                serializer.Serialize(writer, obj);
            } catch (InvalidOperationException) {
                throw new InvalidOperationException("Can not convert object to xml.");
            }
            finally {
                writer.Close();
            }

            var xml = encoding.GetString(stream.ToArray());
            return xml;
        }
    }
}


text:
{-# LANGUAGE DeriveDataTypeable #-}
module Data.Input.Event where
import Data.Typeable
import Data.Char
import Linear

data Chatter a = Up a | Down a deriving (Show, Eq, Ord, Read, Typeable)

data MouseEvent = Button (Chatter Int)
  | Cursor (V2 Float)
  | Scroll (V2 Float)
  deriving (Show, Eq, Ord, Read, Typeable)

data Gamepad = Gamepad Int String deriving (Show, Eq, Ord, Read, Typeable)

data GamepadEvent = PadButton Gamepad (Chatter Int)
  | PadAxis Gamepad Int Float
  | PadConnection (Chatter Gamepad)
  deriving (Show, Eq, Ord, Read, Typeable)

data Key =
      KeyUnknown
    | KeySpace
    | KeyApostrophe
    | KeyComma
    | KeyMinus
    | KeyPeriod
    | KeySlash
    | Key0
    | Key1
    | Key2
    | Key3
    | Key4
    | Key5
    | Key6
    | Key7
    | Key8
    | Key9
    | KeySemicolon
    | KeyEqual
    | KeyA
    | KeyB
    | KeyC
    | KeyD
    | KeyE
    | KeyF
    | KeyG
    | KeyH
    | KeyI
    | KeyJ
    | KeyK
    | KeyL
    | KeyM
    | KeyN
    | KeyO
    | KeyP
    | KeyQ
    | KeyR
    | KeyS
    | KeyT
    | KeyU
    | KeyV
    | KeyW
    | KeyX
    | KeyY
    | KeyZ
    | KeyLeftBracket
    | KeyBackslash
    | KeyRightBracket
    | KeyGraveAccent
    | KeyWorld1
    | KeyWorld2
    | KeyEscape
    | KeyEnter
    | KeyTab
    | KeyBackspace
    | KeyInsert
    | KeyDelete
    | KeyRight
    | KeyLeft
    | KeyDown
    | KeyUp
    | KeyPageUp
    | KeyPageDown
    | KeyHome
    | KeyEnd
    | KeyCapsLock
    | KeyScrollLock
    | KeyNumLock
    | KeyPrintScreen
    | KeyPause
    | KeyF1
    | KeyF2
    | KeyF3
    | KeyF4
    | KeyF5
    | KeyF6
    | KeyF7
    | KeyF8
    | KeyF9
    | KeyF10
    | KeyF11
    | KeyF12
    | KeyF13
    | KeyF14
    | KeyF15
    | KeyF16
    | KeyF17
    | KeyF18
    | KeyF19
    | KeyF20
    | KeyF21
    | KeyF22
    | KeyF23
    | KeyF24
    | KeyF25
    | KeyPad0
    | KeyPad1
    | KeyPad2
    | KeyPad3
    | KeyPad4
    | KeyPad5
    | KeyPad6
    | KeyPad7
    | KeyPad8
    | KeyPad9
    | KeyPadDecimal
    | KeyPadDivide
    | KeyPadMultiply
    | KeyPadSubtract
    | KeyPadAdd
    | KeyPadEnter
    | KeyPadEqual
    | KeyLeftShift
    | KeyLeftControl
    | KeyLeftAlt
    | KeyLeftSuper
    | KeyRightShift
    | KeyRightControl
    | KeyRightAlt
    | KeyRightSuper
    | KeyMenu
    deriving (Enum, Eq, Ord, Read, Show, Typeable, Bounded)

charToKey :: Char -> Key
charToKey ch
    | isAlpha ch = toEnum $ fromEnum KeyA + fromEnum ch - fromEnum 'A'
    | isDigit ch = toEnum $ fromEnum Key0 + fromEnum ch - fromEnum '0'
charToKey '-' = KeyMinus
charToKey ',' = KeyComma
charToKey '.' = KeyPeriod
charToKey '/' = KeySlash
charToKey ' ' = KeySpace
charToKey '\'' = KeyApostrophe
charToKey '\\' = KeyBackslash
charToKey '=' = KeyEqual
charToKey ';' = KeySemicolon
charToKey '[' = KeyLeftBracket
charToKey ']' = KeyRightBracket
charToKey '`' = KeyGraveAccent
charToKey '\n' = KeyEnter
charToKey '\r' = KeyEnter
charToKey '\t' = KeyTab
charToKey _ = KeyUnknown


text:
using System;
using System.Collections.Generic;
using BackendlessAPI.Async;
using BackendlessAPI.Messaging;
using BackendlessAPI.Test.PersistenceService.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BackendlessAPI.Test.MessagingService.SyncTests
{
  [TestClass]
  public class PublishTest : TestsFrame
  {
    [TestMethod]
    public void TestBasicMessagePublish()
    {
      SetLatch();
      SetMessage();

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishWithOptions()
    {
      SetLatch();
      SetMessage();
      SetPublisher();

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );

      PublishOptions publishOptions = new PublishOptions();
      publishOptions.PublisherId = publisher;

      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL, publishOptions );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishWithHeaders()
    {
      SetLatch();
      SetMessage();
      SetHeaders();

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );

      PublishOptions publishOptions = new PublishOptions();
      publishOptions.Headers = headers;

      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL, publishOptions );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishWithHeadersAndSubtopics()
    {
      SetLatch();
      SetMessage();
      SetHeaders();

      string subtopic = "foo.bar";

      SubscriptionOptions subscriptionOptions = new SubscriptionOptions();
      subscriptionOptions.Subtopic = subtopic;

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );

      channel.AddMessageListener<Message>((resultMessage) =>
      {
        if (resultMessage.MessageId.Equals(messageStatus.MessageId))
        {
          Assert.AreEqual(message, resultMessage.Data, "Server returned a message with a wrong message data");

          foreach (var key in PublishTest.headers.Keys)
          {
            Assert.IsTrue(resultMessage.Headers.ContainsKey(key),
              "Server returned a message with wrong headers");
            Assert.IsTrue(resultMessage.Headers[key].Equals(PublishTest.headers[key]),
              "Server returned a message with wrong headers");
          }
        }
      });

      PublishOptions publishOptions = new PublishOptions();
      publishOptions.Headers = headers;
      publishOptions.Subtopic = subtopic;

      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL, publishOptions );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishPrimitiveValue()
    {
      SetLatch();
      SetMessage( 16 );

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishStringValue()
    {
      SetLatch();
      SetMessage( "foomessage" );

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishDateValue()
    {
      SetLatch();
      SetMessage( DateTime.Now );

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishBoolValue()
    {
      SetLatch();
      SetMessage( true );

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [Ignore]
    [TestMethod]
    public void TestMessagePublishPOJOValue()
    {
      SetLatch();

      var wpPerson = new WPPerson {Age = 22, Name = "Vasya"};
      SetMessage( wpPerson );

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [Ignore]
    [TestMethod]
    public void TestMessagePublishArrayOfPOJOValue()
    {
      SetLatch();

      var person123451 = new WPPerson {Age = 22, Name = "Vasya"};
      var androidPerson123452 = new WPPerson {Age = 35, Name = "Petya"};

      SetMessage( new[] {person123451, androidPerson123452} );

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagePublishSinglecast()
    {
      SetLatch();
      SetMessage();

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );

      DeliveryOptions deliveryOptions = new DeliveryOptions();
      deliveryOptions.PushSinglecast = new List<string> {deviceRegistrationId};
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL, null, deliveryOptions );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.PUBLISHED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    [TestMethod]
    public void TestMessagesScheduling()
    {
      SetLatch( 5 );
      SetMessage();

      String channelName = "channel" + GetRandomstringMessage();

      channel = Backendless.Messaging.Subscribe( channelName );

      DeliveryOptions deliveryOptions = new DeliveryOptions();
      deliveryOptions.RepeatEvery = 2;
      messageStatus = Backendless.Messaging.Publish( message, channelName, null, deliveryOptions );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.SCHEDULED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }

    private int counter;

    [TestMethod]
    public void TestMessagesScheduleCancel()
    {
      SetLatch( 11 );
      SetMessage();
      counter = 0;

      channel = Backendless.Messaging.Subscribe( TEST_CHANNEL );

        channel.AddMessageListener<Message>((message) =>
          {
            if( ++counter == 10 )
            {
              try
              {
                Assert.IsTrue(
                  Backendless.Messaging.Cancel( messageStatus.MessageId ),
                  "Server returned a wrong result status" );
              }
              catch( System.Exception t )
              {
                FailCountDownWith( t );
              }
              finally
              {
                latch.Signal();
              }
            }
          } );

      DeliveryOptions deliveryOptions = new DeliveryOptions();
      deliveryOptions.RepeatEvery = 2;
      messageStatus = Backendless.Messaging.Publish( message, TEST_CHANNEL, deliveryOptions );

      Assert.IsNotNull( messageStatus.MessageId, "Server didn't set a messageId for the message" );
      Assert.IsTrue( messageStatus.Status.Equals( PublishStatusEnum.SCHEDULED ),
                     "Message status was not set as published" );

      Await();
      CheckResult();
    }
  }
}


text:
#ifndef _STRUCT_TIMESPEC
#define _STRUCT_TIMESPEC	struct timespec
_STRUCT_TIMESPEC
{
	__darwin_time_t	tv_sec;
	long            tv_nsec;
};
#endif /* _STRUCT_TIMESPEC */


text:
int array_find(uint8_t byte, CData array, int ofs, int end)
{
    void * data = array->data + ofs;
    void * result = memchr(data, (int) byte, (size_t) (end - ofs));
    if (result == NULL)
    {
        return -1;
    }
    else
    {
        return (result - data);
    }
}

void array_realloc(int size, CData array)
{
    array->data = realloc(array->data, (size_t) size);
}

CData array_alloc(int size)
{
    return cdata_allocate((size_t) size, free);
}

uint8_t array_peek(int ofs, CData array)
{
    return ((uint8_t *) array->data)[ofs];
}

void array_poke(int ofs, uint8_t byte, CData array)
{
    ((uint8_t *) array->data)[ofs] = byte;
}

int array_peek_int(int ofs, CData array)
{
    return *((int *) (array->data + ofs));
}

void array_poke_int(int ofs, int val, CData array)
{
    *((int *) (array->data + ofs)) = val;
}

void array_copy(CData src, int src_ofs, CData dst, int dst_ofs, int count)
{
    // memmove rather than memcpy in case the areas overlap
    memmove(dst->data + dst_ofs, src->data + src_ofs, count);
}

void array_fill(int ofs, int count, uint8_t byte, CData array)
{
    memset(array->data + ofs, byte, count);
}

int array_compare(CData l, int lofs, CData r, int rofs, int count)
{
    return memcmp(l->data + lofs, r->data + rofs, count);
}


text:
Zendown
=======

###### *blurring the lines between source and output* ######

Zendown aims to be the purest and most naturally-usable Markdown editing environment, stripping away as much interface as possible without compromising the functionality required for all your Markdown-authoring needs!

## License ##

As usual with my work, this project is available under the BSD 3-Clause license. In short, you can do whatever you want with this code as long as:

* I am always recognised as the original author.
* I am not used to advertise any derivative works without prior permission.
* You include a copy of said license and attribution with any and all redistributions of this code, including derivative works.

For more details, read the included LICENSE.md file or read about it on [opensource.org](http://opensource.org/licenses/BSD-3-Clause).

[Top](#zendown)


text:
<?php

namespace MPScholten\GitHubApi\Api;

use Guzzle\Http\ClientInterface;
use Guzzle\Http\Message\RequestInterface;
use MPScholten\GitHubApi\ResponseDecoder;

class PaginationIterator implements \Iterator
{
    private $position = 0;
    private $storage = [];

    private $client;
    private $transformer;

    private $nextRequest;

    public function __construct(ClientInterface $client, RequestInterface $request, callable $transformer)
    {
        $this->client = $client;
        $this->transformer = $transformer;
        $this->nextRequest = $request;
    }

    public function current()
    {
        return $this->storage[$this->position];
    }

    public function next()
    {
        $this->position++;

        if (!isset($this->storage[$this->position])) {
            $this->loadNext();
        }
    }

    public function key()
    {
        return $this->position;
    }

    public function valid()
    {
        return isset($this->storage[$this->position]);
    }

    public function rewind()
    {
        $this->position = 0;

        if (count($this->storage) === 0) {
            $this->loadNext();
        }
    }

    public function loadNext()
    {
        if (!$this->nextRequest instanceof RequestInterface) {
            return;
        }

        $response = $this->nextRequest->send();
        foreach (call_user_func($this->transformer, ResponseDecoder::decode($response), $this->client) as $data) {
            $this->storage[] = $data;
        }

        $linkHeader = $response->getHeader('Link');

        if ($linkHeader) {
            $this->nextRequest = $this->client->get($response->getHeader('Link')->getLink('next')['url']);
        } else {
            $this->nextRequest = null;
        }
    }
}


text:
#pragma once

#include "game.h"

#include <QtSql>

/** Database class.
 * Wrapper class to manage the internal game database.
 * Also has a simple interface to find games by certain conditions.
 */
class Database
{
public:
    static Database& getInstance();
    static Database& getInstance(QString name);
    bool open();
    bool init();
    bool reset();

    bool addGame(QString gameName, QString gameDirectory, QString executablePath, QString arguments);
    void addGames(GameList games);
    bool removeGameById(unsigned int id);
    bool removeGameByName(QString name);
    Game getGameById(unsigned int id);
    Game getGameByName(QString name);
    std::pair<bool, Game> isExistant(unsigned int id);
    std::pair<bool, Game> isExistant(QString name);
    QList<Game> getGames();
    unsigned int getGameCount();

private:
    Database();
    Database(QString name);
    QSqlDatabase db;
    Database(Database const&) = delete;
    void operator=(Database const&) = delete;
};


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\RssFeed\Package;

use Chamilo\Core\Repository\Common\Action\ContentObjectInstaller;

class Installer extends ContentObjectInstaller
{
}


text:
Meteor.methods({
	groupsList: function(nameFilter, limit, sort) {

		check(nameFilter, Match.Optional(String));
		check(limit, Match.Optional(Number));
		check(sort, Match.Optional(String));

		if (!Meteor.userId()) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'groupsList' });
		}

		let options = {
			fields: { name: 1 },
			sort: { name: 1 }
		};

		//Verify the limit param is a number
		if (_.isNumber(limit)) {
			options.limit = limit;
		}

		//Verify there is a sort option and it's a string
		if (_.trim(sort)) {
			switch (sort) {
				case 'name':
					options.sort = { name: 1 };
					break;
				case 'msgs':
					options.sort = { msgs: -1 };
					break;
			}
		}

		//Determine if they are searching or not, base it upon the name field
		if (nameFilter) {
			return { groups: RocketChat.models.Rooms.findByTypeAndNameContainingUsername('p', new RegExp(s.trim(s.escapeRegExp(nameFilter)), 'i'), Meteor.user().username, options).fetch() };
		} else {
			let roomIds = _.pluck(RocketChat.models.Subscriptions.findByTypeAndUserId('p', Meteor.userId()).fetch(), 'rid');
			return { groups: RocketChat.models.Rooms.findByIds(roomIds, options).fetch() };
		}
	}
});


text:
package org.cloudfoundry.client.v3.isolationsegments;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.client.v3.PaginatedResponse;
import org.cloudfoundry.client.v3.organizations.OrganizationResource;
import org.immutables.value.Value;

/**
 * The response payload for the List Entitled Organizations operation
 */
@JsonDeserialize
@Value.Immutable
abstract class _ListIsolationSegmentEntitledOrganizationsResponse extends PaginatedResponse<OrganizationResource> {

}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/setting_content"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <FrameLayout
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <ImageView
        android:id="@+id/setting_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="invisible"/>

</LinearLayout>


text:
#include "qircserver.h"

QIrcServer::QIrcServer(QObject *parent): QObject(parent){
    this->logger = NULL;
    this->config = NULL;
    this->server = NULL;
    this->serverTimer = NULL;
}

QIrcServer::~QIrcServer(){
    if(this->serverTimer)
        this->serverTimer->stop();

    delete this->serverTimer;
    delete this->server;
    delete this->users;
    delete this->config;
    delete this->logger;
}

void QIrcServer::run(){
    try{
        //Vytvori instanci tridy logger a nastavi potrebne signaly
        this->initLogger();

        //Pokusi se nacist konfiguracni soubor
        this->initConfig();

        //Nacte databazi uzivatelu
        this->initUsers();

        //Nastavi parametry serveru a spusti jej
        this->initServer();

        //Spusti server timer
        this->initTimer();

    }
    catch(QIrcException* e){
        std::cerr << "[!] " << e->getMessage().toStdString() << std::endl;
        delete e;
    }
    catch(...){
        std::cerr << "[!] Cautched unexpected exception" << std::endl;
    }
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 *  Private methods
 * ----------------------------------------------------------------- */

void QIrcServer::initLogger(){
    this->logger = new QIrcLogger("server.log", true, this);

    connect(this, SIGNAL(sendMessage(QString)), this->logger, SLOT(receiveMessage(QString)));

    emit sendMessage("[*] Initializing server");
}

void QIrcServer::initConfig(){
    this->config = new QIrcIniFile(this);

    emit sendMessage("[*] Loading config..");

    this->config->loadFromFile("config.ini");

    this->validateConfig();

    emit sendMessage("[*] Config was successfully loaded");
}

void QIrcServer::initUsers(){
    QString userdb = this->config->getValue("Server", "userdb");

    this->users = new QIrcUserDB(userdb);

    emit sendMessage("[*] Loading users from " + userdb);

    this->users->load();

    emit sendMessage("[*] Successfully loaded " + QString::number(this->users->count()) + " users");
}

void QIrcServer::initServer(){
    this->server = new QTcpServer(this);

    connect(this->server, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));

    if(this->config->getValue("Server", "listen") == "any")
        this->serverAddress = QHostAddress(QHostAddress::Any);
    else
        this->serverAddress = QHostAddress(this->config->getValue("Server", "listen"));

    this->serverPort = this->config->getValue("Server", "port").toInt();

    this->server->setMaxPendingConnections(this->config->getValue("Server", "connections").toInt());
    this->server->setProxy(QNetworkProxy::NoProxy);

    if(!this->server->listen(this->serverAddress, this->serverPort))
        throw new QIrcException(SERVER_RUNTIME_CANNOT_BIND);
    else
        emit sendMessage("[*] Listening on: "+ this->serverAddress.toString() + ":" + QString::number(this->serverPort));

    // Global system room - there are connected all users
    this->rooms.insert("_system", QIrcRoom("_system"));

    this->connections = new QHash<QTcpSocket*, QIrcConnection>();
    this->connections->insert(0, QIrcConnection());
}

void QIrcServer::initTimer(){
    this->serverTimer = new QTimer(this);

    connect(this->serverTimer, SIGNAL(timeout()), this, SLOT(timerTick()));

    this->serverTimer->start(1000 * 30);

    emit sendMessage("[*] Starting server timer");
}

void QIrcServer::validateConfig(){
    if(!this->config)
        return;

    //Listen
    if(!this->config->isValue("Server", "listen"))
        this->config->setValue("Server", "listen", "any");
    else{
        if(this->config->getValue("Server", "listen") != "any"){
            QHostAddress address;

            if(!address.setAddress(this->config->getValue("Server", "listen")))
                throw new QIrcException(SERVER_INVALID_DIRECTIVE_LISTEN);
        }
    }

    //Port
    if(!this->config->isValue("Server", "port"))
        this->config->setValue("Server", "port", "6667");
    else{
        if(this->config->getValue("Server", "port").toInt() == 0)
            throw new QIrcException(SERVER_INVALID_DIRECTIVE_PORT);
    }

    //Connections
    if(!this->config->isValue("Server", "connections"))
        this->config->setValue("Server", "connections", "50");
    else{
        if(this->config->getValue("Server", "connections").toInt() == 0)
            throw new QIrcException(SERVER_INVALID_DIRECTIVE_CONNECTIONS);
    }

    //Hostname
    if(!this->config->isValue("Server", "hostname"))
        this->config->setValue("Server", "hostname", "qirc.dev");

    //User DB file=users.db
    if(!this->config->isValue("Server", "userdb"))
        this->config->setValue("Server", "userdb", "users.db");

    //Server name
    if(!this->config->isValue("Server", "name"))
        this->config->setValue("Server", "name", "qIRC server");

    //Welcome message
    if(!this->config->isValue("Server", "welcome_message"))
        this->config->setValue("Server", "name", "Welcome on qIRC server");

    //MOTD
    if(!this->config->isValue("Server", "motd"))
        this->config->setValue("Server", "motd", "Welcome on private IRC server");
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 *  Private slots
 * ----------------------------------------------------------------- */

void QIrcServer::handleNewConnection(){
    QTcpSocket* socket = this->server->nextPendingConnection();

    if(!socket)
        return;

    this->connections->insert(socket, QIrcConnection(QString().sprintf("%08p", socket), socket->peerAddress().toString()));

    emit sendMessage("[" + this->getConnection(socket).getId() + "] Incoming connection from " + socket->peerAddress().toString());

    connect(socket, SIGNAL(readyRead()), this, SLOT(serverReply()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnect()));
}

void QIrcServer::serverReply(){
    QRegExp protoUser("^USER\\ ([A-z0-9]+) ([A-z0-9\\*]+) ([^\\:]+) \\:(.+)$");
    QRegExp protoNick("^NICK ([A-z0-9]+)$");
    QRegExp protoAuth("^AUTH ([A-z0-9]+) (.*)$");
    QRegExp protoReg("^REG ([A-z0-9]+) (.*)$");
    QRegExp protoJoin("^JOIN ([\\#A-z0-9]+) ?(.*)$");
    QRegExp protoPart("^PART ([\\#A-z0-9]+) ?\\:?(.*)$");
    QRegExp protoWho("^WHO ([\\#A-z0-9]+) ?(.*)$");
    QRegExp protoNames("^NAMES ([\\#A-z0-9]+)$");
    QRegExp protoWhois("^WHOIS ([\\#A-z0-9]+) ?(.*)$");
    QRegExp protoPing("^PING (.+)$"); //pouze klient
    QRegExp protoPong("^PONG \\:(.+)$");
    QRegExp protoPrivMsg("^PRIVMSG ([\\#A-z0-9\\\\_]+) \\:(.*)$");
    QRegExp protoQuit("^QUIT( \\:(.*))?$");

    QTcpSocket* socket = qobject_cast<QTcpSocket*>(this->sender());

    //Tohle se v beznem svete nemuze stat..
    if(!this->connections->contains(socket))
        return;

    QByteArray rawData = socket->readAll();

    this->getConnection(socket).getBuffer().append(rawData);

    while(this->getConnection(socket).getBuffer().isReady()){
        rawData = this->getConnection(socket).getBuffer().flush().trimmed();
        emit sendMessage("[" + this->getConnection(socket).getId() + "] [DEBUG] " + rawData);

        //QUIT
        if(protoQuit.indexIn(rawData) != -1){
            QString msg = "";

            if(protoQuit.captureCount() == 2)
                msg = protoQuit.cap(2);

            this->phaseQuit(socket, msg);

            socket->disconnectFromHost();
        }
        //PING
        else if(protoPing.indexIn(rawData) != -1){
            QString msg = protoPing.cap(1);
            //>> :irc.atw-inter.net PONG irc.atw-inter.net :LAG1386480390208491
            this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " PONG " + this->config->getValue("Server", "hostname") + " " + msg);
        }
        //AUTH
        else if(protoAuth.indexIn(rawData) != -1){
            QString user = protoAuth.cap(1);
            QString pass = protoAuth.cap(2);

            this->phaseAuth(socket, user, pass);
        }
        //REG
        else if(protoReg.indexIn(rawData) != -1){
            QString user = protoReg.cap(1);
            QString pass = protoReg.cap(2);

            this->phaseReg(socket, user, pass);
        }
        //AUTH
        else if(protoAuth.indexIn(rawData) != -1){
            QString user = protoAuth.cap(1);
            QString pass = protoAuth.cap(2);

            this->phaseAuth(socket, user, pass);
        }
        //PONG
        else if(protoPong.indexIn(rawData) != -1){
            QString msg = protoPong.cap(1);

            this->getConnection(socket).setTickResponse(msg);
        }
        /*
         * CONNECTED
         */
        else if(this->getConnection(socket).getStatus() >= CONNECTED && this->getConnection(socket).getStatus() < PHASE_AUTHORIZED){
            //USER
            if(protoUser.indexIn(rawData) != -1){
                QString user = protoUser.cap(1);
                QString name = protoUser.cap(2);
                QString address = protoUser.cap(3);
                QString realName = protoUser.cap(4);

                if(this->users->isUser(user) && this->getConnection(socket).getLogin() != user){
                    //444	ERR_NOLOGIN	"<user> :User not logged in"
                    this->socketWrite(socket, QString(":%1 444 %2 :User not logged in")
                        .arg(this->config->getValue("Server", "hostname"))
                        .arg(user));
                }
                else{

                    this->getConnection(socket).setUser(user);
                    this->getConnection(socket).setAddress(address);
                    this->getConnection(socket).setRealName(realName);

                    if(this->getConnection(socket).getStatus() > CONNECTED){
                        this->getConnection(socket).setStatus(PHASE_AUTHORIZED);
                        this->phaseAuthorized(socket);
                    }
                    else
                        this->getConnection(socket).setStatus(PHASE_USER);
                }
            }
            //NICK
            else if(protoNick.indexIn(rawData) != -1){
                QString nick = protoNick.cap(1);

                if(this->users->isUser(nick) && this->getConnection(socket).getLogin() != nick){
                    //444	ERR_NOLOGIN	"<user> :User not logged in"
                    this->socketWrite(socket, QString(":%1 444 %2 :User not logged in")
                        .arg(this->config->getValue("Server", "hostname"))
                        .arg(nick));
                }
                else{

                    if(this->rooms["_system"].getUsers().contains(nick)){
                        this->socketWrite(socket, ":" + this->config->getValue("Server", "name") + " 433 * " + nick + " :Nickname is already in use.");
                    }
                    else{
                        this->rooms["_system"].addUser(nick);

                        this->getConnection(socket).setNick(nick);

                        if(this->getConnection(socket).getStatus() > CONNECTED){
                            this->getConnection(socket).setStatus(PHASE_AUTHORIZED);
                            this->phaseAuthorized(socket);
                        }
                        else
                            this->getConnection(socket).setStatus(PHASE_NICK);
                    }
                }
            }
            else{
                emit sendMessage("[" + this->getConnection(socket).getId() + "] [FIXIT] " + rawData);
            }
        }
        /*
         * AUTHORIZED
         */
        else if(this->getConnection(socket).getStatus() == PHASE_AUTHORIZED){
            //JOIN
            if(protoJoin.indexIn(rawData) != -1){
                QString target = protoJoin.cap(1);

                this->phaseJoin(socket, target);
            }
            //PART
            if(protoPart.indexIn(rawData) != -1){
                QString target = protoPart.cap(1);

                this->phasePart(socket, target);
            }
            //WHO*
            else if(protoWho.indexIn(rawData) != -1){
                QString target = protoWho.cap(1);

                this->phaseWho(socket, target);
            }
            //WHOIS*
            else if(protoWhois.indexIn(rawData) != -1){
                QString target = protoWhois.cap(1);

                this->phaseWhois(socket, target);
            }
            //NAMES
            else if(protoNames.indexIn(rawData) != -1){
                QString target = protoNames.cap(1);

                this->phaseNames(socket, target);
            }
            //PRIVMSG*
            else if(protoPrivMsg.indexIn(rawData) != -1){
                QString target = protoPrivMsg.cap(1);
                QString message = protoPrivMsg.cap(2);

                this->phasePrivmsg(socket, target, message);
            }
            //NICK
            else if(protoNick.indexIn(rawData) != -1){
                QString target = protoNick.cap(1);

                this->phaseNick(socket, target);
            }
        }

    }
}

void QIrcServer::timerTick(){
    emit sendMessage("[*] Timer tick: " + QString::number(this->connections->size()));

    QTcpSocket* socket;
    QList<QTcpSocket*> corpses;

    for(QHash<QTcpSocket*, QIrcConnection>::Iterator p = this->connections->begin(); p != this->connections->end(); p++){

        socket = p.key();

        if(this->getConnection(socket).getStatus() == DISCONNECTED || this->getConnection(socket).getStatus() == ZOMBIE)
            continue;

        if(this->getConnection(socket).getTickRequest() == this->getConnection(socket).getTickResponse()){
            this->getConnection(socket).setTickRequest(QString::number(QDateTime::currentMSecsSinceEpoch()));

            this->socketWrite(p.key(), "PING :" + this->getConnection(socket).getTickRequest());
        }
        else
            corpses.push_back(socket);
    }

    //Recycle corpses
    for(QList<QTcpSocket*>::Iterator p = corpses.begin(); p != corpses.end(); p++){
        emit sendMessage("[" + this->getConnection(socket).getId() + "] [!] Timeout exceeded");

        this->connections->remove(socket);
        (*p)->disconnectFromHost();
    }

    emit sendMessage("[*] Timer end tick: " + QString::number(this->connections->size()));
}

//Handle disconnect
void QIrcServer::clientDisconnect(){
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(this->sender());

    if(this->connections->contains(socket)){
        this->getConnection(socket).setStatus(DISCONNECTED);

        this->rooms["_system"].removeUser(this->getConnection(socket).getNick());

        emit sendMessage("[" + this->getConnection(socket).getId() + "] [*] Disconnected from " + this->getConnection(socket).getAddress());

        this->connections->remove(socket);
    }

    socket->deleteLater();
    socket->close();
}

// Helpers
void QIrcServer::socketWrite(QTcpSocket* socket, QString data){
    emit sendMessage(">> " + data);
    socket->write(data.toAscii() + "\r\n");
    socket->flush();
}

QTcpSocket* QIrcServer::getSocket(QString nick){
    for(QHash<QTcpSocket*, QIrcConnection>::Iterator p = this->connections->begin(); p != this->connections->end(); p++)
        if((*p).getNick() == nick)
            return p.key();

    return NULL;
}

QIrcConnection& QIrcServer::getConnection(QTcpSocket* socket){
    if(this->connections->contains(socket))
        return (*(this->connections))[socket];

    qDebug() << "Manual creating zombie";

    return (*(this->connections))[0];
}

// Phases

void QIrcServer::phaseAuthorized(QTcpSocket* socket){
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 001 " + this->getConnection(socket).getNick() + " :" + this->config->getValue("Server", "welcome_message") + " "+ this->getConnection(socket).getNick() +"!"+ this->getConnection(socket).getUser() +"@" + this->getConnection(socket).getAddress());
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 002 " + this->getConnection(socket).getNick() + " :Your host is "+ this->config->getValue("Server", "hostname") +", running version 0.1a");
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 003 " + this->getConnection(socket).getNick() + " :This server was created 2013-11-27");
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 251 " + this->getConnection(socket).getNick() + " :There are " + QString::number(this->rooms["_system"].getUsersCount()) + " users");
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 254 " + this->getConnection(socket).getNick() + " " + QString::number(this->rooms.count()) + " :channels formed");

    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 375 " + this->getConnection(socket).getNick() + " :- Message of the Day @"+ this->config->getValue("Server", "hostname") +" -");
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 372 " + this->getConnection(socket).getNick() + " :- " + QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss"));
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 372 " + this->getConnection(socket).getNick() + " :- " + this->config->getValue("Server", "motd"));
    this->socketWrite(socket, ":" + this->config->getValue("Server", "hostname") + " 376 " + this->getConnection(socket).getNick() + " :End of MOTD command.");
}

void QIrcServer::phaseJoin(QTcpSocket* socket, QString target){

    QTcpSocket* ptr;

    if(!this->rooms.contains(target)){
        emit sendMessage("[" + this->getConnection(socket).getId() + "] [*] Creating room " + target);

        QIrcRoom room(target, this->getConnection(socket).getNick());

        this->rooms.insert(target, room);
    }

    this->rooms[target].addUser(this->getConnection(socket).getNick());

    QStringList users = this->rooms[target].getUsers();

    for(QStringList::Iterator p = users.begin(); p != users.end(); p++){
        if((ptr = getSocket(*p))){
            if(*p == this->getConnection(socket).getNick()){
                this->socketWrite(ptr, QString(":%1!~%2@%3 JOIN %4")
                    .arg(this->getConnection(socket).getNick())
                    .arg(this->getConnection(socket).getUser())
                    .arg(this->getConnection(socket).getAddress())
                    .arg(target));

                this->phaseNames(ptr, target);

            }
            else{
                this->socketWrite(ptr, QString(":%1!~%2@%3 JOIN :%4")
                    .arg(this->getConnection(socket).getNick())
                    .arg(this->getConnection(socket).getUser())
                    .arg(this->getConnection(socket).getAddress())
                    .arg(target));

                this->phaseNames(ptr, target);
            }
        }
    }
}

void QIrcServer::phasePart(QTcpSocket* socket, QString target){
    QTcpSocket* ptr;

    if(!this->rooms.contains(target))
        return;

    this->rooms[target].removeUser(this->getConnection(socket).getNick());

    QStringList users = this->rooms[target].getUsers();

    for(QStringList::Iterator p = users.begin(); p != users.end(); p++){
        if((ptr = getSocket(*p))){
            //if(*p == this->getConnection(socket).getNick()){
                this->socketWrite(ptr, QString(":%1!~%2@%3 PART %4")
                    .arg(this->getConnection(socket).getNick())
                    .arg(this->getConnection(socket).getUser())
                    .arg(this->getConnection(socket).getAddress())
                    .arg(target));
            //}
        }
    }
}

void QIrcServer::phaseWho(QTcpSocket* socket, QString target){
    QTcpSocket* ptr;

    //Room
    if(target.startsWith('#')){
        if(this->rooms.contains(target)){
            QStringList users = this->rooms[target].getUsers();

            for(QStringList::Iterator p = users.begin(); p != users.end(); p++){
                if((ptr = getSocket(*p))){
                    //:irc.felk.cvut.cz 352 Filgron #fit11 ~filgy 176.74.128.47 irc.felk.cvut.cz Filgron H :0 203F Lord destructor
                    this->socketWrite(socket, QString(":%1 352 %2 %3 ~%4 %5 %6 %7 H :0 203F %8")
                        .arg(this->config->getValue("Server", "hostname"))
                        .arg(this->getConnection(socket).getNick())
                        .arg(target)

                        .arg(this->getConnection(ptr).getUser())
                        .arg(this->getConnection(ptr).getAddress())
                        .arg(this->config->getValue("Server", "hostname"))
                        .arg(this->getConnection(ptr).getNick())
                        .arg(this->getConnection(ptr).getRealName()));
                }
            }
        }

        //:irc.felk.cvut.cz 315 Filgron #fit11 :End of WHO list.
        this->socketWrite(socket, QString(":%1 315 %2 %3 :End of WHO list.")
            .arg(this->config->getValue("Server", "hostname"))
            .arg(this->getConnection(socket).getNick())
            .arg(target));
    }
    //Person
    else{
        if((ptr = getSocket(target))){
            //:irc.felk.cvut.cz 352 Filgron #fit11 ~filgy 176.74.128.47 irc.felk.cvut.cz Filgron H :0 203F Lord destructor
            this->socketWrite(socket, QString(":%1 352 %2 %3 ~%4 %5 %6 %7 H :0 203F %8")
                .arg(this->config->getValue("Server", "hostname"))
                .arg(this->getConnection(socket).getNick())
                .arg(target)

                .arg(this->getConnection(ptr).getUser())
                .arg(this->getConnection(ptr).getAddress())
                .arg(this->config->getValue("Server", "hostname"))
                .arg(this->getConnection(ptr).getNick())
                .arg(this->getConnection(ptr).getRealName()));
        }

        //:irc.felk.cvut.cz 315 Filgron #fit11 :End of WHO list.
        this->socketWrite(socket, QString(":%1 315 %2 %3 :End of WHO list.")
            .arg(this->config->getValue("Server", "hostname"))
            .arg(this->getConnection(socket).getNick())
            .arg(target));
    }
}

void QIrcServer::phaseWhois(QTcpSocket* socket, QString target){
    QTcpSocket* ptr;

    if((ptr = getSocket(target))){
        //:irc.felk.cvut.cz 311 Filgron Filgy ~quassel angie.sniff.ws * :Lord destroyer
        this->socketWrite(socket, QString(":%1 311 %2 %3 ~%4 %5 * :%6")
            .arg(this->config->getValue("Server", "hostname"))
            .arg(this->getConnection(socket).getNick())
            .arg(target)
            .arg(this->getConnection(ptr).getUser())
            .arg(this->getConnection(ptr).getAddress())
            .arg(this->getConnection(ptr).getRealName()));

        //:irc.felk.cvut.cz 312 Filgron Filgy irc.nfx.cz :Neutral czFree eXchange
        this->socketWrite(socket, QString(":%1 312 %2 %3 %4 :%5")
            .arg(this->config->getValue("Server", "hostname"))
            .arg(this->getConnection(socket).getNick())
            .arg(target)
            .arg(this->config->getValue("Server", "hostname"))
            .arg(this->config->getValue("Server", "name")));
    }
    //:irc.felk.cvut.cz 318 Filgron Filgy :End of WHOIS list.
    this->socketWrite(socket, QString(":%1 318 %2 %3 :End of WHOIS list")
        .arg(this->config->getValue("Server", "hostname"))
        .arg(this->getConnection(socket).getNick())
        .arg(target));
}

void QIrcServer::phaseNames(QTcpSocket* socket, QString target){
    if(target.startsWith('#')){
        QStringList users = this->rooms[target].getUsers();

        if(this->rooms.contains(target)){
            this->socketWrite(socket, QString(":%1 353 %2 = %3 :%4")
                .arg(this->config->getValue("Server", "hostname"))
                .arg(this->getConnection(socket).getNick())
                .arg(target)
                .arg(users.join(" ")));
        }

        this->socketWrite(socket, QString(":%1 366 %2 %3 :End of NAMES list.")
            .arg(this->config->getValue("Server", "hostname"))
            .arg(this->getConnection(socket).getNick())
            .arg(target));
    }
}

void QIrcServer::phasePrivmsg(QTcpSocket* socket, QString target, QString message){

    QTcpSocket* ptr;

    //Room
    if(target.startsWith('#')){
        if(this->rooms.contains(target)){
            QStringList users = this->rooms[target].getUsers();

            for(QStringList::Iterator p = users.begin(); p != users.end(); p++){
                if(*p != this->getConnection(socket).getNick())
                if((ptr = getSocket(*p))){
                    this->socketWrite(ptr, QString(":%1!~%2@%3 PRIVMSG %4 :%5")
                        .arg(this->getConnection(socket).getNick())
                            .arg(this->getConnection(socket).getUser())
                            .arg(this->getConnection(socket).getAddress())
                            .arg(target)
                            .arg(message));
                }
            }
        }
        else{
            this->socketWrite(socket, QString(":%1 401 %2 %3 :No such nick/channel")
                .arg(this->config->getValue("Server", "hostname"))
                .arg(this->getConnection(socket).getNick())
                .arg(target));
        }
    }
    //Person
    else{
        if((ptr = this->getSocket(target))){
            this->socketWrite(ptr, QString(":%1!~%2@%3 PRIVMSG %4 :%5")
                .arg(this->getConnection(socket).getNick())
                    .arg(this->getConnection(socket).getUser())
                    .arg(this->getConnection(socket).getAddress())
                    .arg(target)
                    .arg(message));
        }
        else{
            this->socketWrite(socket, QString(":%1 401 %2 %3 :No such nick/channel")
                .arg(this->config->getValue("Server", "hostname"))
                .arg(this->getConnection(socket).getNick())
                .arg(target));
        }
    }
}

void QIrcServer::phaseQuit(QTcpSocket* socket, QString message){
    QTcpSocket* ptr;

    QStringList survivors;

    for(QHash<QString, QIrcRoom>::Iterator p = this->rooms.begin(); p != this->rooms.end(); p++){
        QStringList users = (*p).getUsers();

        if(users.contains(this->getConnection(socket).getNick())){
            (*p).removeUser(this->getConnection(socket).getNick());

            for(QStringList::Iterator q = users.begin(); q != users.end(); q++){
                if(!survivors.contains(*q))
                    survivors.append(*q);
            }
        }
    }

    for(QStringList::Iterator p = survivors.begin(); p != survivors.end(); p++){
        if((ptr = this->getSocket(*p))){
            this->socketWrite(ptr, QString(":%1!~%2@%3 QUIT :%4")
                .arg(this->getConnection(socket).getNick())
                .arg(this->getConnection(socket).getUser())
                .arg(this->getConnection(socket).getAddress())
                .arg(message));
        }
    }
}

void QIrcServer::phaseNick(QTcpSocket* socket, QString target){

    QTcpSocket* ptr;

if(this->users->isUser(target) && this->getConnection(socket).getLogin() != target.toLower()){
        //444	ERR_NOLOGIN	"<user> :User not logged in"
        this->socketWrite(socket, QString(":%1 444 %2 :User not logged in")
            .arg(this->config->getValue("Server", "hostname"))
            .arg(target));
}
else{
    if(this->rooms["_system"].getUsers().contains(target)){
        this->socketWrite(socket, QString(":%1 433 %2 :Nickname is already in use.")
            .arg(this->config->getValue("Server", "name"))
            .arg(target));
    }
    else{
        this->rooms["_system"].removeUser(this->getConnection(socket).getNick());
        this->rooms["_system"].addUser(target);

        QStringList survivors;

        for(QHash<QString, QIrcRoom>::Iterator p = this->rooms.begin(); p != this->rooms.end(); p++){
            QStringList users = (*p).getUsers();

            if(users.contains(this->getConnection(socket).getNick())){
               (*p).removeUser(this->getConnection(socket).getNick());
               (*p).addUser(target);

               for(QStringList::Iterator q = users.begin(); q != users.end(); q++){
                   if(!survivors.contains(*q))
                       survivors.append(*q);
               }
            }
        }

        for(QStringList::Iterator p = survivors.begin(); p != survivors.end(); p++){
            if((ptr = this->getSocket(*p))){
                this->socketWrite(ptr, QString(":%1!~%2@%3 NICK :%4")
                    .arg(this->getConnection(socket).getNick())
                    .arg(this->getConnection(socket).getUser())
                    .arg(this->getConnection(socket).getAddress())
                    .arg(target));
            }
        }

        this->getConnection(socket).setNick(target);
    }
}
}

void QIrcServer::phaseAuth(QTcpSocket* socket, QString user, QString pass){
    if(!this->users->isUser(user)){
        this->socketWrite(socket, QString(":%1 451 :You have not registered")
            .arg(this->config->getValue("Server", "hostname")));
    }
    else if(!this->users->isValid(user, pass)){
        this->socketWrite(socket, QString(":%1 464 :Password incorrect")
            .arg(this->config->getValue("Server", "hostname")));
    }
    else{
        this->getConnection(socket).setLogin(user);
        emit sendMessage("[" + this->getConnection(socket).getId() + "] [*] Login user " + user);
    }
}

void QIrcServer::phaseReg(QTcpSocket* socket, QString user, QString pass){
    if(this->users->isUser(user)){
        this->socketWrite(socket, QString(":%1 462 :Unauthorized command (already registered)")
            .arg(this->config->getValue("Server", "hostname")));
    }
    else{
        this->users->addUser(user, pass);
        emit sendMessage("[" + this->getConnection(socket).getId() + "] [*] Created user " + user);
    }
}


text:
package org.hisp.dhis.tracker.preheat.supplier.strategy;

import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.query.QueryService;
import org.hisp.dhis.schema.SchemaService;
import org.hisp.dhis.trackedentity.TrackedEntityType;
import org.hisp.dhis.tracker.preheat.cache.PreheatCacheService;
import org.hisp.dhis.tracker.preheat.mappers.TrackedEntityTypeMapper;
import org.springframework.stereotype.Component;

/**
 * @author Luciano Fiandesio
 */
@Component
@StrategyFor( value = TrackedEntityType.class, mapper = TrackedEntityTypeMapper.class, cache = true, ttl = 10, capacity = 5 )
public class TrackedEntityTypeStrategy extends AbstractSchemaStrategy
{
    public TrackedEntityTypeStrategy( SchemaService schemaService, QueryService queryService,
        IdentifiableObjectManager manager, PreheatCacheService cacheService )
    {
        super( schemaService, queryService, manager, cacheService );
    }
}


text:
'use strict';

var pkg = require('./package.json'),
_ = require('underscore');

module.exports = function(){

  function failback(){

    var message = arguments[0];
    var callback = arguments[arguments.length-1];

    var error = new Error(message + ' failed: Your cachy does not have a proper storage engine configured');

    if(typeof callback === 'function') return callback(error);
    else throw error;
  }

  var exprt = {version : pkg.version};
  _.each(['write','has','read','remove','clear','keys', 'size'], function(fxn){ exprt[fxn] = _.partial(failback, 'cachy ' + fxn); } );
  return exprt;
};


text:
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default =

ReportDispatcher;  // This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) 2008-2016 Pivotal Labs

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /* eslint-disable sort-keys */function ReportDispatcher(methods) {const dispatchedMethods = methods || [];for (let i = 0; i < dispatchedMethods.length; i++) {const method = dispatchedMethods[i];this[method] = function (m) {return function () {dispatch(m, arguments);};}(method);}let reporters = [];let fallbackReporter = null;this.addReporter = function (reporter) {reporters.push(reporter);};this.provideFallbackReporter = function (reporter) {fallbackReporter = reporter;};this.clearReporters = function () {reporters = [];};return this;function dispatch(method, args) {
    if (reporters.length === 0 && fallbackReporter !== null) {
      reporters.push(fallbackReporter);
    }
    for (let i = 0; i < reporters.length; i++) {
      const reporter = reporters[i];
      if (reporter[method]) {
        reporter[method].apply(reporter, args);
      }
    }
  }
}


text:
var async = require("async");

module.exports = new Class({
    initialize: function (dataAccessor) {
        this.accessor = dataAccessor;
    },

    loadMessages: function (regId, msgIds, callback) {
        if (typeof(msgIds) == "function") {
            callback = msgIds;
            msgIds = null;
        }
        this.accessor.loadMsgRefs(regId, function (err, msgRefs) {
            if (err) {
                callback(err);
            } else if (Array.isArray(msgRefs)) {
                if (Array.isArray(msgIds)) {
                    msgRefs = msgRefs.filter(function (msgRef) {
                        return msgIds.indexOf(msgRef.msgId) >= 0;
                    });
                }
                async.map(msgRefs,
                        function (msgRef, next) {
                            this.accessor.loadMessage(msgRef.msgId, function (err, message) {
                                if (!err && message) {
                                    message.pushedAt = msgRef.pushedAt;
                                }
                                next(err, message);
                            });
                        }.bind(this),
                        callback
                );
            } else {
                callback(null, null);
            }
        }.bind(this));
        return this;
    },

    removeMessages: function (regId, msgIds, callback) {
        this.accessor.removeMsgRefs(regId, msgIds, callback);
    }
});


text:
namespace Editor
{

template<typename Method>
struct EventListener
{
    cocos2d::Ref *  target;
    Method          method;

    EventListener()
    : target(NULL)
    , method(NULL)
    {}

    EventListener(cocos2d::Ref *target, Method method)
    {
        this->target = target;
        this->method = method;
    }

    void set(cocos2d::Ref *target, Method method)
    {
        this->target = target;
        this->method = method;
    }

    void clear()
    {
        target = NULL;
        method = NULL;
    }

    operator bool()
    {
        return target != NULL && method != NULL;
    }

    bool operator == (const EventListener<Method> & other) const
    {
        return this->target == other.target &&
            this->method == other.method;
    }
};

template<typename Method>
EventListener<Method> makeListener(cocos2d::Ref* target, Method method)
{
    return EventListener<Method>(target, method);
}

} // end namespace Editor

#endif


text:
<?php

namespace ForkCMS\Tests\Utility\Thumbnails;

use ForkCMS\Utility\Thumbnails;
use PHPUnit\Framework\TestCase;

class ThumbnailsTest extends TestCase
{
    private const LANDSCAPE = '1000x500';
    private const PORTRAIT = '500x1000';
    private const SOURCE = 'source';
    private const SQUARE = '500x500';
    private const ONLY_WIDTH = '500x';
    private const ONLY_HEIGHT = 'x500';

    /** @var array  */
    private $folders = [];

    /** @var string  */
    private $filename;

    /** @var string  */
    private $rootPath;

    /** @var Thumbnails */
    private $thumbnails;

    private function createFolders()
    {
        foreach ($this->folders as $folder) {
            mkdir($folder);
        }
    }

    private function deleteFolders()
    {
        foreach ($this->folders as $folder) {
            rmdir($folder);
        }
    }

    private function deleteFiles()
    {
        unlink($this->rootPath . '/' . self::SOURCE . '/' . $this->filename);
    }

    /**
     * Put your temp image into your filesystem.
     * (Not good as unit tests must work with any system,
     * but my research about mocking resources gave me nothing)
     */
    protected function setUp()
    {
        // Init variables
        $sitePathWWW = __DIR__ . '/../../var/cache/test';
        $this->rootPath = realpath($sitePathWWW);
        $this->filename = '1.jpg';
        $this->thumbnails = new Thumbnails($sitePathWWW);
        $this->folders = [
            $this->rootPath . '/' . self::SOURCE,
            $this->rootPath . '/' . self::SQUARE,
            $this->rootPath . '/' . self::PORTRAIT,
            $this->rootPath . '/' . self::LANDSCAPE,
            $this->rootPath . '/' . self::ONLY_HEIGHT,
            $this->rootPath . '/' . self::ONLY_WIDTH,
        ];

        $this->createFolders();

        // Copy our file to /source folder
        copy(
            $this->rootPath . '/../../../src/Backend/Core/Installer/Data/images/' . $this->filename,
            $this->rootPath . '/' . self::SOURCE . '/' . $this->filename
        );
    }

    protected function tearDown()
    {
        $this->deleteFiles();
        $this->deleteFolders();
    }

    /**
     * We have one big test method, because setUp and tearDown are executed for every test method.
     */
    public function testClassMethods()
    {
        // Test thumbnail folders
        $this->assertEquals(
            [
                [
                    'dirname' => self::ONLY_WIDTH,
                    'path' => $this->rootPath . '/' . self::ONLY_WIDTH,
                    'url' => '',
                    'width' => (int) explode('x', self::ONLY_WIDTH)[0],
                    'height' => null,
                ],
                [
                    'dirname' => self::LANDSCAPE,
                    'path' => $this->rootPath . '/' . self::LANDSCAPE,
                    'url' => '',
                    'width' => (int) explode('x', self::LANDSCAPE)[0],
                    'height' => (int) explode('x', self::LANDSCAPE)[1],
                ],
                [
                    'dirname' => self::ONLY_HEIGHT,
                    'path' => $this->rootPath . '/' . self::ONLY_HEIGHT,
                    'url' => '',
                    'width' => null,
                    'height' => (int) explode('x', self::ONLY_HEIGHT)[1],
                ],
                [
                    'dirname' => self::PORTRAIT,
                    'path' => $this->rootPath . '/' . self::PORTRAIT,
                    'url' => '',
                    'width' => (int) explode('x', self::PORTRAIT)[0],
                    'height' => (int) explode('x', self::PORTRAIT)[1],
                ],
                [
                    'dirname' => self::SQUARE,
                    'path' => $this->rootPath . '/' . self::SQUARE,
                    'url' => '',
                    'width' => (int) explode('x', self::SQUARE)[0],
                    'height' => (int) explode('x', self::SQUARE)[0],
                ]
            ],
            $this->thumbnails->getFolders($this->rootPath)
        );

        // Test thumbnail generating
        $this->thumbnails->generate($this->rootPath, $this->rootPath . '/' . self::SOURCE . '/' . $this->filename);
        $this->assertTrue(is_file($this->rootPath . '/' . self::SQUARE . '/' . $this->filename));

        // Test thumbnail deleting
        $this->thumbnails->delete($this->rootPath, $this->filename);
        $this->assertFalse(is_file($this->rootPath . '/' . self::LANDSCAPE . '/' . $this->filename));
        $this->assertFalse(is_file($this->rootPath . '/' . self::PORTRAIT . '/' . $this->filename));
        $this->assertFalse(is_file($this->rootPath . '/' . self::SQUARE . '/' . $this->filename));
        $this->assertTrue(is_file($this->rootPath . '/' . self::SOURCE . '/' . $this->filename));
    }
}


text:
package com.devsaki.fakkudroid;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.devsaki.fakkudroid.database.FakkuDroidDB;
import com.devsaki.fakkudroid.database.domains.Attribute;
import com.devsaki.fakkudroid.database.domains.Content;
import com.devsaki.fakkudroid.database.enums.AttributeType;
import com.devsaki.fakkudroid.util.AndroidHelper;
import com.devsaki.fakkudroid.util.Constants;
import com.devsaki.fakkudroid.util.Helper;
import com.devsaki.fakkudroid.v2.bean.DoujinBean;
import com.devsaki.fakkudroid.v2.bean.URLBean;
import com.github.lzyzsd.circleprogress.DonutProgress;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ImporterActivity extends ActionBarActivity {

    private static final String TAG = ImporterActivity.class.getName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_importer);

        AndroidHelper.executeAsyncTask(new ImporterAsyncTask());
    }

    class ImporterAsyncTask extends AsyncTask<Integer,String,List<Content>>{

        private File downloadDir;
        private int currentPercent;
        private DonutProgress donutProgress;
        private TextView tvCurrentStatus;
        private FakkuDroidDB fakkuDroidDB;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            downloadDir = Helper.getDownloadDir("", ImporterActivity.this);

            donutProgress = (DonutProgress) findViewById(R.id.donut_progress);
            tvCurrentStatus = (TextView) findViewById(R.id.tvCurrentStatus);
            fakkuDroidDB = new FakkuDroidDB(ImporterActivity.this);
        }

        @Override
        protected void onPostExecute(List<Content> contents) {
            if(contents!=null&&contents.size()>0)
                fakkuDroidDB.insertContents(contents.toArray(new Content[contents.size()]));
            Intent intent = new Intent(ImporterActivity.this, DownloadsActivity.class);
            startActivity(intent);
            finish();
        }

        @Override
        protected void onProgressUpdate(String... values) {
            donutProgress.setProgress(currentPercent);
            tvCurrentStatus.setText(values[0]);
        }

        @Override
        protected List<Content> doInBackground(Integer... params) {
            List<Content> contents = null;
            File[] files = downloadDir.listFiles();
            int processeds = 0;
            if(files.length>0){
                contents = new ArrayList<>();
                Date importedDate = new Date();
                for(File file : files){
                    processeds++;
                    currentPercent = (int) (processeds*100.0/files.length);
                    if(file.isDirectory()){
                        publishProgress(file.getName());
                        File json = new File(file, Constants.JSON_FILE_NAME);
                        if(json.exists()){
                            try {
                                Content content = new Gson().fromJson(Helper.readTextFile(json), Content.class);
                                if(content.getStatus() != com.devsaki.fakkudroid.database.enums.Status.DOWNLOADED)
                                    content.setStatus(com.devsaki.fakkudroid.database.enums.Status.MIGRATED);
                                contents.add(content);
                            } catch (Exception e) {
                                Log.e(TAG, "Reading json file", e);
                            }
                        }else{
                            json = new File(file, Constants.JSON_FILE_NAME_V2);
                            if(json.exists()){
                                try {
                                    DoujinBean doujinBean = new Gson().fromJson(Helper.readTextFile(json), DoujinBean.class);
                                    Content content = new Content();
                                    content.setUrl(doujinBean.getId());
                                    content.setHtmlDescription(doujinBean.getDescription());
                                    content.setTitle(doujinBean.getTitle());
                                    content.setSerie(from(doujinBean.getSerie(), AttributeType.SERIE));
                                    Attribute artist = from(doujinBean.getArtist(), AttributeType.ARTIST);
                                    List<Attribute> artists = null;
                                    if(artist!=null){
                                        artists = new ArrayList<>(1);
                                        artists.add(artist);
                                    }
                                    content.setArtists(artists);
                                    content.setCoverImageUrl(doujinBean.getUrlImageTitle());
                                    content.setQtyPages(doujinBean.getQtyPages());
                                    Attribute translator = from(doujinBean.getTranslator(), AttributeType.TRANSLATOR);
                                    List<Attribute> translators = null;
                                    if(translator!=null){
                                        translators = new ArrayList<>(1);
                                        translators.add(translator);
                                    }
                                    content.setTranslators(translators);
                                    content.setTags(from(doujinBean.getLstTags(), AttributeType.TAG));
                                    content.setLanguage(from(doujinBean.getLanguage(), AttributeType.LANGUAGE));

                                    content.setStatus(com.devsaki.fakkudroid.database.enums.Status.MIGRATED);
                                    content.setDownloadDate(importedDate.getTime());
                                    contents.add(content);
                                } catch (Exception e) {
                                    Log.e(TAG, "Reading json file v2", e);
                                }
                            }
                        }
                    }
                }
            }
            return contents;
        }

        private List<Attribute> from(List<URLBean> urlBeans, AttributeType type){
            List<Attribute> attributes = null;
            if(urlBeans==null)
                return null;
            if(urlBeans.size()>0){
                attributes = new ArrayList<>();
                for (URLBean urlBean : urlBeans){
                    Attribute attribute = from(urlBean, type);
                    if(attribute!=null)
                        attributes.add(attribute);
                }
            }
            return attributes;
        }

        private Attribute from(URLBean urlBean, AttributeType type){
            if(urlBean == null){
                return null;
            }
            try{
                if(urlBean.getDescription()==null){
                    throw new RuntimeException("Problems loading attribute v2.");
                }
                Attribute attribute = new Attribute();
                attribute.setName(urlBean.getDescription());
                attribute.setUrl(urlBean.getId());
                attribute.setType(type);
                return attribute;
            }catch (Exception ex){
                Log.e(TAG, "Parsing urlBean to attribute" ,ex);
                return null;
            }
        }
    }
}


text:
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
	<cbid>CROMU_00001</cbid>
	<replay>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>iakaese\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>gfosqxn\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>ydvqsor\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>ncqywhy\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>hrkixkf\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>2\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>iakaese\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>gfosqxn\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>eixnywwzlkkdfbaxhw\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>iakaese\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>qixfrzwiioxiuqxhdhdfystl\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1:  qixfrzwiioxiuqxhdhdfystl\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>5\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Logging out...\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>2\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>ncqywhy\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>gfosqxn\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>mblxbxfluaps\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>6\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Exiting...\n</data></match></read>
	</replay>
</pov>