text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using java.util;
using java.io;
using edu.stanford.nlp.pipeline;
using Console = System.Console;
using edu.stanford.nlp.ling;
using System.Globalization;
using System.Threading;
using edu.stanford.nlp.trees;
using nsExtensions;
using nsNotenizerObjects;
using nsConstants;
using nsDB;
using nsEnums;
using nsParsers;
using nsComparsions;
using nsServices.DBServices;
using MongoDB.Bson;

namespace nsNotenizer
{
    /// <summary>
    /// Main class for application.
    /// </summary>
    public class Notenizer
    {
        #region Variables

        private bool _redirectOutputToFile = false;
        private String _redirectOutputToFileFileName = @"./out.txt";

        private StanfordCoreNLP _pipeline;
        private List<NotenizerNote> _notes;
        private StaticParser _staticParser;
        private ComparsionsManager _comparsionManager;
        private bool _verbose;

        #endregion Variables

        #region Constructors

        public Notenizer(bool verbose)
        {
            _verbose = verbose;
            _staticParser = new StaticParser();
            _comparsionManager = new ComparsionsManager();
        }

        #endregion Constuctors

        #region Properties

        public List<NotenizerNote> Notes
        {
            get { return _notes; }
        }

        /// <summary>
        /// Pipeline to StanfordCoreNLP project.
        /// </summary>
        public StanfordCoreNLP Pipeline
        {
            get
            {
                Properties properties;
                CultureInfo cultureInfo;
                String currentDirectory;

                try
                {
                    if (_pipeline == null)
                    {
                        String jarRoot = @"stanford-corenlp-3.5.2-models";

                        // Annotation pipeline configuration
                        properties = new Properties();
                        properties.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse");
                        properties.setProperty("sutime.binders", "0");
                        properties.setProperty("ner.useSUTime", "false");

                        // prevents time exception
                        cultureInfo = new CultureInfo("en-US");
                        Thread.CurrentThread.CurrentCulture = cultureInfo;
                        Thread.CurrentThread.CurrentUICulture = cultureInfo;

                        // We should change current directory, so StanfordCoreNLP could find all the model files automatically
                        currentDirectory = Environment.CurrentDirectory;
                        Directory.SetCurrentDirectory(jarRoot);
                        _pipeline = new StanfordCoreNLP(properties);
                        Directory.SetCurrentDirectory(currentDirectory);
                    }

                    return _pipeline;
                }
                catch (Exception ex)
                {
                    throw new Exception("Error creating pipelint to StanfordCoreNLP project." + Environment.NewLine + Environment.NewLine + ex.Message);
                }
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Runs text processing using StanfordCoreNLP procject.
        /// </summary>
        /// <param name="text">Text to process</param>
        public void RunCoreNLP(String text)
        {
            // needs to be before Annotation(text)
            // otherwise it throws error
            StanfordCoreNLP pipeLine = Pipeline;
            Annotation annotation = new Annotation(text);
            pipeLine.annotate(annotation);

            if (_redirectOutputToFile)
            {
                FileStream filestream = new FileStream(_redirectOutputToFileFileName, FileMode.OpenOrCreate, FileAccess.Write);
                var streamwriter = new StreamWriter(filestream);
                streamwriter.AutoFlush = true;
                Console.SetOut(streamwriter);
                Console.SetError(streamwriter);
            }

            if (_verbose)
            {
                // Result - Pretty Print
                using (ByteArrayOutputStream stream = new ByteArrayOutputStream())
                {
                    pipeLine.prettyPrint(annotation, new PrintWriter(stream));
                    Console.WriteLine(stream.toString());
                    stream.close();
                }
            }

            _notes = Parse(annotation);
            PrintNotes(_notes);
        }

        /// <summary>
        /// Gets rule for sentence
        /// </summary>
        /// <param name="sentence">Sentence to get rule for</param>
        /// <param name="matchedNote">Out matched note of sentence</param>
        /// <returns></returns>
        private NotenizerNoteRule GetRuleForSentence(NotenizerSentence sentence, out Note matchedNote)
        {
            Match match;
            Article article;
            Structure structure;
            Note matchedSentenceNote;
            NotenizerNoteRule matchedSentenceRule;
            NotenizerStructure matchedSentenceStructure;
            List<BsonDocument> sentencesWithSameStructure;

            matchedNote = null;
            structure = DocumentParser.GetHeighestMatch(
                sentence.Structure,
                DB.GetAll(DBConstants.StructuresCollectionName, DocumentCreator.CreateFilterByStructure(sentence)).Result,
                out match);

            if (structure == null)
                return null;

            matchedSentenceStructure = new NotenizerStructure(structure);

            sentencesWithSameStructure = DB.GetAll(
                DBConstants.SentencesCollectionName,
                DocumentCreator.CreateFilterById(DBConstants.StructureRefIdFieldName, matchedSentenceStructure.Structure.ID)).Result;

            nsNotenizerObjects.Sentence matchedSentence = null;

            if (sentencesWithSameStructure.Count > 0)
            {
                matchedSentence = DocumentParser.ParseSentence(sentencesWithSameStructure[0]);
                foreach (BsonDocument sentenceWithSameStructureLoop in sentencesWithSameStructure)
                {
                    if (sentenceWithSameStructureLoop[DBConstants.TextFieldName].AsString.Trim() == sentence.Sentence.Text)
                    {
                        match.Value = 100.0;
                        matchedSentence = DocumentParser.ParseSentence(sentenceWithSameStructureLoop);
                        break;
                    }
                }
            }

            if (matchedSentence == null)
                return null;

            article = DocumentParser.ParseArticle(
                DB.GetFirst(
                    DBConstants.ArticlesCollectionName,
                    DocumentCreator.CreateFilterById(sentence.Sentence.Article.ID)).Result);

            matchedSentenceNote = DocumentParser.ParseNote(
                DB.GetFirst(
                    DBConstants.NotesCollectionName,
                    DocumentCreator.CreateFilterById(matchedSentence.NoteID)).Result);

            matchedSentenceRule = DocumentParser.ParseRule(
                DB.GetFirst(
                    DBConstants.RulesCollectionName,
                    DocumentCreator.CreateFilterById(matchedSentence.RuleID)).Result);

            matchedSentenceRule.Structure = new NotenizerStructure(
                DocumentParser.ParseStructure(
                    DB.GetFirst(
                        DBConstants.StructuresCollectionName,
                        DocumentCreator.CreateFilterById(matchedSentenceRule.StructureID)).Result));

            matchedSentenceRule.Sentence = matchedSentence;
            matchedSentenceRule.Sentence.Article = article;
            matchedSentenceRule.Match = match;
            matchedNote = matchedSentenceNote;

            return matchedSentenceRule;
        }

        /// <summary>
        /// Gets and-rule for sentence.
        /// </summary>
        /// <param name="rule"></param>
        /// <param name="andRuleId"></param>
        /// <returns></returns>
        public NotenizerAndRule GetAndRuleForSentence(NotenizerRule rule, String andRuleId)
        {
            NotenizerAndRule andRule;

            andRule = DocumentParser.ParseAndRule(
                DB.GetFirst(
                    DBConstants.AndRulesCollectionName,
                    DocumentCreator.CreateFilterById(andRuleId)).Result);

            andRule.Structure = new NotenizerStructure(
                DocumentParser.ParseStructure(
                    DB.GetFirst(
                        DBConstants.StructuresCollectionName,
                        DocumentCreator.CreateFilterById(andRule.StructureID)).Result));

            andRule.Sentence = rule.Sentence;

            return andRule;
        }

        /// <summary>
        /// Gets article from database or creates a new one, if not found.
        /// </summary>
        /// <param name="text">Text of article</param>
        /// <returns></returns>
        private Article GetArticle(String text)
        {
            Article article;
            List<BsonDocument> articles = DB.GetAll(DBConstants.ArticlesCollectionName, DocumentCreator.CreateFilter(DBConstants.TextFieldName, text)).Result;

            if (articles.Count == 0)
            {
                article = new Article(String.Empty, DateTime.Now, DateTime.Now, text);
                article.ID = DB.InsertToCollection(DBConstants.ArticlesCollectionName, DocumentCreator.CreateArticleDocument(article)).Result;
            }
            else
                article = DocumentParser.ParseArticle(articles[0]);

            return article;
        }

        /// <summary>
        /// Parses the sentence.
        /// </summary>
        /// <param name="annotation"></param>
        /// <returns></returns>
        public List<NotenizerNote> Parse(Annotation annotation)
        {
            List<NotenizerNote> sentencesNoted = new List<NotenizerNote>();
            List<NotenizerNote> notesToSave = new List<NotenizerNote>();

            Article article = GetArticle(annotation.ToString().Trim());

            // ================== REFACTORED PART HERE ======================
            foreach (Annotation sentenceLoop in annotation.get(typeof(CoreAnnotations.SentencesAnnotation)) as ArrayList)
            {
                NotenizerSentence sentence = new NotenizerSentence(sentenceLoop, article);
                Note matchedNote;

                NotenizerNoteRule rule = GetRuleForSentence(sentence, out matchedNote);

                if (rule != null && rule.Structure.Dependencies != null && rule.Structure.Dependencies.Count > 0)
                {
                    NotenizerNote parsedNote = ApplyRule(sentence, rule);
                    parsedNote.Note = matchedNote;

                    if (parsedNote.Note.AndRuleID != DBConstants.BsonNullValue)
                        parsedNote.AndRule = GetAndRuleForSentence(rule, parsedNote.Note.AndRuleID);

                    //Console.WriteLine("Parsed note: " + parsedNote.OriginalSentence + " ===> " + parsedNote.Text);
                    sentencesNoted.Add(parsedNote);

                    continue;
                }

                NotenizerNote note = _staticParser.Parse(sentence);
                notesToSave.Add(note);
            }

            // inserting into DB AFTER ALL sentences from article were processed
            // to avoid processed sentence to affect processing other sentences from article
            foreach (NotenizerNote sentenceNotedLoop in notesToSave)
            {
                // save rule's structure
                NotenizerNoteRule rule = sentenceNotedLoop.CreateRule();
                sentenceNotedLoop.CreateStructure();
                rule.Structure.Structure.ID = DB.InsertToCollection(DBConstants.StructuresCollectionName, DocumentCreator.CreateStructureDocument(rule)).Result;

                // save sentence's structure
                NotenizerStructure sentenceStructure = sentenceNotedLoop.OriginalSentence.Structure;
                sentenceStructure.Structure.ID = DB.InsertToCollection(DBConstants.StructuresCollectionName, DocumentCreator.CreateStructureDocument(sentenceStructure)).Result;

                // save rule
                rule.ID = DB.InsertToCollection(DBConstants.RulesCollectionName, DocumentCreator.CreateRuleDocument(rule)).Result;

                // save note
                Note note = sentenceNotedLoop.CreateNote();
                note.ID = DB.InsertToCollection(DBConstants.NotesCollectionName, DocumentCreator.CreateNoteDocument(
                    sentenceNotedLoop,
                    rule.ID,
                    String.Empty)).Result;

                // save sentence
                sentenceNotedLoop.OriginalSentence.Sentence.ID = DB.InsertToCollection(DBConstants.SentencesCollectionName, DocumentCreator.CreateSentenceDocument(
                    sentenceNotedLoop.OriginalSentence,
                    sentenceStructure.Structure.ID,
                    article.ID,
                    rule.ID,
                    String.Empty,
                    note.ID)).Result;

                Console.WriteLine("Parsed note: " + sentenceNotedLoop.OriginalSentence + " ===> " + sentenceNotedLoop.Text);
                sentencesNoted.Add(sentenceNotedLoop);
            }

            return sentencesNoted;
        }

        /// <summary>
        /// Prints notes to console.
        /// </summary>
        /// <param name="notes"></param>
        public void PrintNotes(List<NotenizerNote> notes)
        {
            Console.WriteLine();
            Console.WriteLine("<======== NOTES ========>");

            foreach (NotenizerNote noteLoop in notes)
            {
                Console.WriteLine(noteLoop.OriginalSentence + " ---> " + noteLoop.Text);
            }
        }

        /// <summary>
        /// Applies rule.
        /// Parses sentence by applied rule.
        /// </summary>
        /// <param name="sentence">Sentence to apply rule to</param>
        /// <param name="rule">Rule for parsing to apply</param>
        /// <returns></returns>
        public NotenizerNote ApplyRule(NotenizerSentence sentence, NotenizerRule rule)
        {
            NotenizerNote note = new NotenizerNote(sentence);
            NotePart notePart = new NotePart(sentence);

            foreach (NotenizerDependency ruleLoop in rule.Structure.Dependencies)
            {
                ApplyRule(sentence, ruleLoop, notePart);
            }

            note.Add(notePart);

            if (rule is NotenizerNoteRule)
                ApplyRule(note, rule as NotenizerNoteRule);
            else if (rule is NotenizerAndRule)
                ApplyRule(note, rule as NotenizerAndRule);
            //note.Note = rule.Note;
            note.Structure = rule.Structure;
            return note;
        }

        /// <summary>
        /// Aplies rule.
        /// </summary>
        /// <param name="note"></param>
        /// <param name="noteRule"></param>
        private void ApplyRule(NotenizerNote note, NotenizerNoteRule noteRule)
        {
            note.SplitToSentences(noteRule.SentencesTerminators);
            note.Rule = noteRule;
        }

        /// <summary>
        /// Applies rule.
        /// </summary>
        /// <param name="note"></param>
        /// <param name="andParserRule"></param>
        private void ApplyRule(NotenizerNote note, NotenizerAndRule andParserRule)
        {
            note.SplitToSentences(andParserRule.SentenceTerminator);
            note.AndRule = andParserRule;
        }

        /// <summary>
        /// Applies rule.
        /// Parses sentence by applied rule and part of note of original sentence.
        /// </summary>
        /// <param name="sentence">Sentence to apply rule to</param>
        /// <param name="rule">Rule for parsing to apply</param>
        /// <param name="notePart">Part of note</param>
        private void ApplyRule(NotenizerSentence sentence, NotenizerDependency rule, NotePart notePart)
        {
            NotenizerDependency dependency = null;// = sentence.FindDependency(rule);
            double match = 0.0;
            double currentMatch = 0.0;

            foreach (NotenizerDependency dependencyLoop in sentence.Structure.FindDependencies(rule))
            {
                if (dependencyLoop == null)
                    continue;

                if ((currentMatch = _comparsionManager.Compare(rule, dependencyLoop, sentence.Structure.Dependencies.Count)) > match)
                {
                    match = currentMatch;
                    dependency = dependencyLoop;
                }
            }

            if (dependency != null)
            {
                NoteParticle dependencyObj = new NoteParticle(dependency, rule.TokenType, rule.Position);
                notePart.Add(dependencyObj);
            }
        }

        #endregion Methods
    }
}


text:
"""
An abstraction layer over OS-dependent file-like objects, that provides a
consistent view of a *duplex byte stream*.
"""
import sys
import os
import socket
import time
import errno
from rpyc.lib import safe_import
from rpyc.lib.compat import select, select_error, BYTES_LITERAL, get_exc_errno, maxint
win32file = safe_import("win32file")
win32pipe = safe_import("win32pipe")
msvcrt = safe_import("msvcrt")
ssl = safe_import("ssl")

retry_errnos = (errno.EAGAIN, errno.EWOULDBLOCK)

class Stream(object):
    """Base Stream"""

    __slots__ = ()
    def close(self):
        """closes the stream, releasing any system resources associated with it"""
        raise NotImplementedError()
    @property
    def closed(self):
        """tests whether the stream is closed or not"""
        raise NotImplementedError()
    def fileno(self):
        """returns the stream's file descriptor"""
        raise NotImplementedError()
    def poll(self, timeout):
        """indicates whether the stream has data to read (within *timeout*
        seconds)"""
        try:
            while True:
                try:
                    rl, _, _ = select([self], [], [], timeout)
                except select_error as ex:
                    if ex[0] == errno.EINTR:
                        continue
                    else:
                        raise
                else:
                    break
        except ValueError as ex:
            # i get this some times: "ValueError: file descriptor cannot be a negative integer (-1)"
            # let's translate it to select.error
            raise select_error(str(ex))
        return bool(rl)
    def read(self, count):
        """reads **exactly** *count* bytes, or raise EOFError

        :param count: the number of bytes to read

        :returns: read data
        """
        raise NotImplementedError()
    def write(self, data):
        """writes the entire *data*, or raise EOFError

        :param data: a string of binary data
        """
        raise NotImplementedError()

class ClosedFile(object):
    """Represents a closed file object (singleton)"""
    __slots__ = ()
    def __getattr__(self, name):
        if name.startswith("__"): # issue 71
            raise AttributeError("stream has been closed")
        raise EOFError("stream has been closed")
    def close(self):
        pass
    @property
    def closed(self):
        return True
    def fileno(self):
        raise EOFError("stream has been closed")
ClosedFile = ClosedFile()

class SocketStream(Stream):
    """A stream over a socket"""

    __slots__ = ("sock",)
    MAX_IO_CHUNK = 8000
    def __init__(self, sock):
        self.sock = sock

    @classmethod
    def _connect(cls, host, port, family = socket.AF_INET, socktype = socket.SOCK_STREAM,
            proto = 0, timeout = 3, nodelay = False, keepalive = False):
        family, socktype, proto, _, sockaddr = socket.getaddrinfo(host, port, family,
            socktype, proto)[0]
        s = socket.socket(family, socktype, proto)
        s.settimeout(timeout)
        s.connect(sockaddr)
        if nodelay:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        if keepalive:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # Linux specific: after 10 idle minutes, start sending keepalives every 5 minutes.
            # Drop connection after 10 failed keepalives
            if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10 * 60)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5 * 60)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 10)
        return s

    @classmethod
    def connect(cls, host, port, **kwargs):
        """factory method that creates a ``SocketStream`` over a socket connected
        to *host* and *port*

        :param host: the host name
        :param port: the TCP port
        :param kwargs: additional keyword arguments: ``family``, ``socktype``,
                       ``proto``, ``timeout``, ``nodelay``, passed directly to
                       the ``socket`` constructor, or ``ipv6``.
        :param ipv6: if True, creates an IPv6 socket (``AF_INET6``); otherwise
                     an IPv4 (``AF_INET``) socket is created

        :returns: a :class:`SocketStream`
        """
        if kwargs.pop("ipv6", False):
            kwargs["family"] = socket.AF_INET6
        return cls(cls._connect(host, port, **kwargs))

    @classmethod
    def ssl_connect(cls, host, port, ssl_kwargs, **kwargs):
        """factory method that creates a ``SocketStream`` over an SSL-wrapped
        socket, connected to *host* and *port* with the given credentials.

        :param host: the host name
        :param port: the TCP port
        :param ssl_kwargs: a dictionary of keyword arguments to be passed
                           directly to ``ssl.wrap_socket``
        :param kwargs: additional keyword arguments: ``family``, ``socktype``,
                       ``proto``, ``timeout``, ``nodelay``, passed directly to
                       the ``socket`` constructor, or ``ipv6``.
        :param ipv6: if True, creates an IPv6 socket (``AF_INET6``); otherwise
                     an IPv4 (``AF_INET``) socket is created

        :returns: a :class:`SocketStream`
        """
        if kwargs.pop("ipv6", False):
            kwargs["family"] = socket.AF_INET6
        s = cls._connect(host, port, **kwargs)
        s2 = ssl.wrap_socket(s, **ssl_kwargs)
        return cls(s2)

    @property
    def closed(self):
        return self.sock is ClosedFile
    def close(self):
        if not self.closed:
            try:
                self.sock.shutdown(socket.SHUT_RDWR)
            except Exception:
                pass
        self.sock.close()
        self.sock = ClosedFile
    def fileno(self):
        try:
            return self.sock.fileno()
        except socket.error:
            self.close()
            ex = sys.exc_info()[1]
            if get_exc_errno(ex) == errno.EBADF:
                raise EOFError()
            else:
                raise

    def read(self, count):
        data = []
        while count > 0:
            try:
                buf = self.sock.recv(min(self.MAX_IO_CHUNK, count))
            except socket.timeout:
                continue
            except socket.error:
                ex = sys.exc_info()[1]
                if get_exc_errno(ex) in retry_errnos:
                    # windows just has to be a bitch
                    continue
                self.close()
                raise EOFError(ex)
            if not buf:
                self.close()
                raise EOFError("connection closed by peer")
            data.append(buf)
            count -= len(buf)
        return BYTES_LITERAL("").join(data)
    def write(self, data):
        try:
            while data:
                count = self.sock.send(data[:self.MAX_IO_CHUNK])
                data = data[count:]
        except socket.error:
            ex = sys.exc_info()[1]
            self.close()
            raise EOFError(ex)

class TunneledSocketStream(SocketStream):
    """A socket stream over an SSH tunnel (terminates the tunnel when the connection closes)"""

    __slots__ = ("tun",)
    def __init__(self, sock):
        self.sock = sock
        self.tun = None
    def close(self):
        SocketStream.close(self)
        if self.tun:
            self.tun.close()

class PipeStream(Stream):
    """A stream over two simplex pipes (one used to input, another for output)"""

    __slots__ = ("incoming", "outgoing")
    MAX_IO_CHUNK = 32000
    def __init__(self, incoming, outgoing):
        outgoing.flush()
        self.incoming = incoming
        self.outgoing = outgoing
    @classmethod
    def from_std(cls):
        """factory method that creates a PipeStream over the standard pipes
        (``stdin`` and ``stdout``)

        :returns: a :class:`PipeStream` instance
        """
        return cls(sys.stdin, sys.stdout)
    @classmethod
    def create_pair(cls):
        """factory method that creates two pairs of anonymous pipes, and
        creates two PipeStreams over them. Useful for ``fork()``.

        :returns: a tuple of two :class:`PipeStream` instances
        """
        r1, w1 = os.pipe()
        r2, w2 = os.pipe()
        side1 = cls(os.fdopen(r1, "rb"), os.fdopen(w2, "wb"))
        side2 = cls(os.fdopen(r2, "rb"), os.fdopen(w1, "wb"))
        return side1, side2
    @property
    def closed(self):
        return self.incoming is ClosedFile
    def close(self):
        self.incoming.close()
        self.outgoing.close()
        self.incoming = ClosedFile
        self.outgoing = ClosedFile
    def fileno(self):
        return self.incoming.fileno()
    def read(self, count):
        data = []
        try:
            while count > 0:
                buf = os.read(self.incoming.fileno(), min(self.MAX_IO_CHUNK, count))
                if not buf:
                    raise EOFError("connection closed by peer")
                data.append(buf)
                count -= len(buf)
        except EOFError:
            self.close()
            raise
        except EnvironmentError:
            ex = sys.exc_info()[1]
            self.close()
            raise EOFError(ex)
        return BYTES_LITERAL("").join(data)
    def write(self, data):
        try:
            while data:
                chunk = data[:self.MAX_IO_CHUNK]
                written = os.write(self.outgoing.fileno(), chunk)
                data = data[written:]
        except EnvironmentError:
            ex = sys.exc_info()[1]
            self.close()
            raise EOFError(ex)

class Win32PipeStream(Stream):
    """A stream over two simplex pipes (one used to input, another for output).
    This is an implementation for Windows pipes (which suck)"""

    __slots__ = ("incoming", "outgoing", "_fileno", "_keepalive")
    PIPE_BUFFER_SIZE = 130000
    MAX_IO_CHUNK = 32000

    def __init__(self, incoming, outgoing):
        self._keepalive = (incoming, outgoing)
        if hasattr(incoming, "fileno"):
            self._fileno = incoming.fileno()
            incoming = msvcrt.get_osfhandle(incoming.fileno())
        if hasattr(outgoing, "fileno"):
            outgoing = msvcrt.get_osfhandle(outgoing.fileno())
        self.incoming = incoming
        self.outgoing = outgoing
    @classmethod
    def from_std(cls):
        return cls(sys.stdin, sys.stdout)
    @classmethod
    def create_pair(cls):
        r1, w1 = win32pipe.CreatePipe(None, cls.PIPE_BUFFER_SIZE)
        r2, w2 = win32pipe.CreatePipe(None, cls.PIPE_BUFFER_SIZE)
        return cls(r1, w2), cls(r2, w1)

    def fileno(self):
        return self._fileno
    @property
    def closed(self):
        return self.incoming is ClosedFile
    def close(self):
        if self.closed:
            return
        try:
            win32file.CloseHandle(self.incoming)
        except Exception:
            pass
        self.incoming = ClosedFile
        try:
            win32file.CloseHandle(self.outgoing)
        except Exception:
            pass
        self.outgoing = ClosedFile
    def read(self, count):
        try:
            data = []
            while count > 0:
                dummy, buf = win32file.ReadFile(self.incoming, int(min(self.MAX_IO_CHUNK, count)))
                count -= len(buf)
                data.append(buf)
        except TypeError:
            ex = sys.exc_info()[1]
            if not self.closed:
                raise
            raise EOFError(ex)
        except win32file.error:
            ex = sys.exc_info()[1]
            self.close()
            raise EOFError(ex)
        return BYTES_LITERAL("").join(data)
    def write(self, data):
        try:
            while data:
                dummy, count = win32file.WriteFile(self.outgoing, data[:self.MAX_IO_CHUNK])
                data = data[count:]
        except TypeError:
            ex = sys.exc_info()[1]
            if not self.closed:
                raise
            raise EOFError(ex)
        except win32file.error:
            ex = sys.exc_info()[1]
            self.close()
            raise EOFError(ex)

    def poll(self, timeout, interval = 0.1):
        """a poor man's version of select()"""
        if timeout is None:
            timeout = maxint
        length = 0
        tmax = time.time() + timeout
        try:
            while length == 0:
                length = win32pipe.PeekNamedPipe(self.incoming, 0)[1]
                if time.time() >= tmax:
                    break
                time.sleep(interval)
        except TypeError:
            ex = sys.exc_info()[1]
            if not self.closed:
                raise
            raise EOFError(ex)
        return length != 0

class NamedPipeStream(Win32PipeStream):
    """A stream over two named pipes (one used to input, another for output).
    Windows implementation."""

    NAMED_PIPE_PREFIX = r'\\.\pipe\rpyc_'
    PIPE_IO_TIMEOUT = 3
    CONNECT_TIMEOUT = 3
    __slots__ = ("is_server_side",)

    def __init__(self, handle, is_server_side):
        Win32PipeStream.__init__(self, handle, handle)
        self.is_server_side = is_server_side
    @classmethod
    def from_std(cls):
        raise NotImplementedError()
    @classmethod
    def create_pair(cls):
        raise NotImplementedError()

    @classmethod
    def create_server(cls, pipename, connect = True):
        """factory method that creates a server-side ``NamedPipeStream``, over
        a newly-created *named pipe* of the given name.

        :param pipename: the name of the pipe. It will be considered absolute if
                         it starts with ``\\\\.``; otherwise ``\\\\.\\pipe\\rpyc``
                         will be prepended.
        :param connect: whether to connect on creation or not

        :returns: a :class:`NamedPipeStream` instance
        """
        if not pipename.startswith("\\\\."):
            pipename = cls.NAMED_PIPE_PREFIX + pipename
        handle = win32pipe.CreateNamedPipe(
            pipename,
            win32pipe.PIPE_ACCESS_DUPLEX,
            win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT,
            1,
            cls.PIPE_BUFFER_SIZE,
            cls.PIPE_BUFFER_SIZE,
            cls.PIPE_IO_TIMEOUT * 1000,
            None
        )
        inst = cls(handle, True)
        if connect:
            inst.connect_server()
        return inst

    def connect_server(self):
        """connects the server side of an unconnected named pipe (blocks
        until a connection arrives)"""
        if not self.is_server_side:
            raise ValueError("this must be the server side")
        win32pipe.ConnectNamedPipe(self.incoming, None)

    @classmethod
    def create_client(cls, pipename):
        """factory method that creates a client-side ``NamedPipeStream``, over
        a newly-created *named pipe* of the given name.

        :param pipename: the name of the pipe. It will be considered absolute if
                         it starts with ``\\\\.``; otherwise ``\\\\.\\pipe\\rpyc``
                         will be prepended.

        :returns: a :class:`NamedPipeStream` instance
        """
        if not pipename.startswith("\\\\."):
            pipename = cls.NAMED_PIPE_PREFIX + pipename
        handle = win32file.CreateFile(
            pipename,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0,
            None,
            win32file.OPEN_EXISTING,
            0,
            None
        )
        return cls(handle, False)

    def close(self):
        if self.closed:
            return
        if self.is_server_side:
            win32file.FlushFileBuffers(self.outgoing)
            win32pipe.DisconnectNamedPipe(self.outgoing)
        Win32PipeStream.close(self)

if sys.platform == "win32":
    PipeStream = Win32PipeStream

redpajama_set_name: RedPajamaGithub


text:
/*******************************************************************************
 * Copyright (c) 2017, Sandeep Prakash <123sandy@gmail.com>
 *
 * \file   tcp-server.hpp
 *
 * \author Sandeep Prakash
 *
 * \date   Apr 18, 2017
 *
 * \brief
 *
 ******************************************************************************/

#ifndef __SRC_UTILS_TCP_SERVER_HPP__
#define __SRC_UTILS_TCP_SERVER_HPP__
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <sys/time.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>

#include <event2/event.h>
#include <event2/util.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>

#include <iostream>
#include <thread>
#include <chrono>
#include "thread-pool.hpp"
#include "logger.hpp"
#include "tcp-listener.hpp"

/********************************* CONSTANTS **********************************/

/*********************************** MACROS ***********************************/

/******************************** ENUMERATIONS ********************************/

/*********************** CLASS/STRUCTURE/UNION DATA TYPES *********************/
class TcpServer;

typedef void (*OnLocalEvent) (void *this_);

typedef struct _client_ctxt {
   int client_fd;
   struct event *client_event;
   struct bufferevent *client_bev;
   struct sockaddr_in *px_sock_addr_in;
   TcpServer *tcpServer;
   bool disconnected;
} client_ctxt;

typedef struct _local_event_ctxt {
   OnLocalEvent onLocalEvent;
   void *onLocalEventThis;
   struct timeval tv;
   struct event *event;
} local_event_ctxt;

typedef void (*OnMessage) (client_ctxt *client, uint8_t *message, uint32_t length, void *this_);

typedef void (*OnConnection) (client_ctxt *client, void *this_);

typedef void (*OnDisconnect) (client_ctxt *client, short what, void *this_);

class TcpServer {
public:
   TcpServer (in_addr_t ip, in_port_t port);
   ~TcpServer ();
   int start ();
   void OnNewMessage (OnMessage onMessage, void *this_);
   void OnNewConnection (OnConnection onConnection, void *this_);
   void OnPeerDisconnect (OnDisconnect onDisconnect, void *this_);
   ThreadPool *getWorkerPool ();
   void handleConnection (int client_fd,
                             struct sockaddr_in *px_sock_addr_in);
   void newLocalEvent (OnLocalEvent onLocalEvent, void *this_, struct timeval tv);

private:
   in_addr_t mIp;
   in_port_t mPort;
   ThreadPool *mWorkerPool;
   TcpListener *mTcpListener;
   OnMessage mOnMessage;
   OnConnection mOnConnection;
   OnDisconnect mOnDisconnect;
   void *mOnMessageThis;
   void *mOnConnectionThis;
   void *mOnDisconnectThis;

   static void onConnection (int client_fd,
                             struct sockaddr_in *px_sock_addr_in, void *this_);

   static void * workerRoutine (void *arg, struct event_base *base);

   static void * localEventRoutine (void *arg, struct event_base *base);

   static void _onRead (struct bufferevent *bev, void *ctx);

   static void _onWrite (struct bufferevent *bev, void *ctx);

   static void _onError (struct bufferevent *bev, short what, void *ctx);

   static void onTimerExpiry (evutil_socket_t fd, short what, void *ctx);

   void readMessage (client_ctxt *client, struct bufferevent *bev);

   void onError (client_ctxt *client, struct bufferevent *bev, short what);

};

/***************************** FUNCTION PROTOTYPES ****************************/

#endif /* __SRC_UTILS_TCP_SERVER_HPP__ */


text:
"""A class for SQLGitHub sessions.

Sample Usage:
    g = Github(token)
    s = SgSession(g, ["name", "description"], "abseil.repos")
    print(s.Execute())
"""

import table as tb
import table_fetcher
from expression import SgExpression
from grouping import SgGrouping
from ordering import SgOrdering
from ordering import SgTableOrdering

# TODO(lnishan): Change it to SgSessionSimple and add SgSession to handle unions and joins.
class SgSession:
    """A class for SQLGitHub sessions."""

    def __init__(self, github, field_exprs, source=None, condition=None, groups=None, having=None, orders=None, limit=None):
        self._field_exprs = field_exprs
        self._source = source
        self._condition = condition
        self._groups = groups
        self._having = having
        self._orders = orders
        self._limit = limit

        rel_keys = SgExpression.ExtractTokensFromExpressions(self._field_exprs)
        if self._condition:
            rel_keys += SgExpression.ExtractTokensFromExpressions([self._condition])
        if self._groups:
            rel_keys += SgExpression.ExtractTokensFromExpressions(self._groups)
        if self._having:
            rel_keys += SgExpression.ExtractTokensFromExpressions([self._having])
        if self._orders:
            rel_keys += SgExpression.ExtractTokensFromExpressions(self._orders[0])
        rel_keys = list(set(rel_keys))
        if u"*" in rel_keys:
            rel_keys = [u"*"]
        self._fetcher = table_fetcher.SgTableFetcher(github, rel_keys)

    def _GetEmptyTable(self):
        table = tb.SgTable()
        table.SetFields(self._field_exprs)
        return table

    def Execute(self):
        # source is either a label (eg. "google.issues") or a SgSession
        if self._source:
            source_table = self._source.Execute() if isinstance(self._source, SgSession) else self._fetcher.Fetch(self._source)
            if not source_table[:]:
                return self._GetEmptyTable()
            else:
                if u"*" in self._field_exprs:
                    self._field_exprs = source_table.GetFields()
        else:
            source_table = tb.SgTable()
            source_table.SetFields([u"Dummy Field"])
            source_table.Append([u"Dummy Value"])

        # evaluate where
        if self._condition:
            filtered_table = tb.SgTable()
            filtered_table.SetFields(source_table.GetFields())
            meets = SgExpression.EvaluateExpression(source_table, self._condition)
            for i, row in enumerate(source_table):
                if meets[i]:
                    filtered_table.Append(row)
        else:
            filtered_table = source_table
        if not filtered_table[:]:
            return self._GetEmptyTable()

        # evaluate all necessary expressions
        # in reversed order because we process from the rightmost item first
        select_tokens = SgExpression.ExtractTokensFromExpressions(self._field_exprs[:])
        eval_exprs = select_tokens
        if self._orders:
            order_tokens = SgExpression.ExtractTokensFromExpressions(self._orders[0])
            eval_exprs += order_tokens
        if self._having:
            having_tokens = SgExpression.ExtractTokensFromExpressions([self._having])
            eval_exprs += having_tokens
        if self._groups:
            eval_exprs += self._groups
        res_table = SgExpression.EvaluateExpressions(filtered_table, eval_exprs)

        # group by
        if self._groups:
            res_tables = SgGrouping.GenerateGroups(res_table, self._groups)
        else:
            res_tables = [res_table]

        # having
        if self._having:
            filtered_tables = []
            for table in res_tables:
                if all(SgExpression.EvaluateExpression(table, self._having)):
                    filtered_tables.append(table.SliceCol(0, len(table.GetFields()) - len(having_tokens)))
            res_tables = filtered_tables

        # order by
        if self._orders:
            for table in res_tables:
                table.Copy(table.SliceCol(0, len(table.GetFields()) - len(order_tokens)).Chain(SgExpression.EvaluateExpressions(table, self._orders[0])))
                ordering = SgOrdering(table, self._orders[1])
                table.Copy(ordering.Sort(keep_order_fields=True))
            ordering = SgTableOrdering(res_tables, self._orders[1])
            res_tables = ordering.Sort()

        # TODO(lnishan): Support having here

        # process select
        for table in res_tables:
            table.Copy(SgExpression.EvaluateExpressions(table, self._field_exprs))

        # check if all tokens in expressions are contained in aggregate functions
        check_exprs = [expr for expr in self._field_exprs if expr not in self._groups] if self._groups else self._field_exprs
        if SgExpression.IsAllTokensInAggregate(check_exprs):
            for table in res_tables:
                table = table.SetTable([table[0]])

        merged_table = tb.SgTable()
        merged_table.SetFields(res_tables[0].GetFields())
        for table in res_tables:
            for row in table:
                merged_table.Append(row)

        # process limit
        if self._limit:
            merged_table.SetTable(merged_table[:self._limit])

        return merged_table


text:
""" Display Windbarbs.
"""

import itertools

import numpy as np
from vispy import app
from vispy.visuals import WindbarbVisual
from vispy.visuals.transforms import NullTransform

class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, title="Windbarb plot", keys="interactive",
                            size=(830, 430))

        self.windbarb_length = 25
        self.grid_spacing = 50

        self.grid_coords = None
        self.line_vertices = None
        self.last_mouse = (0, 0)

        self.generate_grid()

        direction_vectors = (self.grid_coords - self.last_mouse).astype(
            np.float32)
        direction_vectors[:] /= 10
        direction_vectors[:, 1] *= -1

        self.visual = WindbarbVisual(pos=self.grid_coords,
                                     wind=direction_vectors,
                                     trig=False,
                                     edge_color='black',
                                     face_color='black',
                                     size=self.windbarb_length)

        self.visual.events.update.connect(lambda evt: self.update())
        self.visual.transform = NullTransform()

        self.show()

    def generate_grid(self):
        n = self.grid_spacing / 2.
        num_cols = int(self.physical_size[0] / n * 2)
        num_rows = int(self.physical_size[1] / n * 2)
        coords = []

        # Generate grid
        for i, j in itertools.product(range(num_rows), range(num_cols)):
            x = n + (n * 2 * j)
            y = n + (n * 2 * i)

            coords.append((x, y))

        self.grid_coords = np.array(coords)

    def on_resize(self, event):
        self.generate_grid()
        self.rotate_arrows(np.array(self.last_mouse))

        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)
        self.visual.transforms.configure(canvas=self, viewport=vp)

    def rotate_arrows(self, point_towards):
        direction_vectors = (self.grid_coords - point_towards).astype(
            np.float32)
        direction_vectors[:] /= 10
        direction_vectors[:, 1] *= -1

        self.visual.set_data(
            pos=self.grid_coords,
            wind=direction_vectors,
            size=self.windbarb_length,
        )

    def on_mouse_move(self, event):
        self.last_mouse = event.pos
        self.rotate_arrows(np.array(event.pos))

    def on_draw(self, event):
        self.context.clear(color='white')
        self.visual.draw()

if __name__ == '__main__':
    canvas = Canvas()
    canvas.measure_fps()
    app.run()


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_vertical_margin"
        android:paddingRight="@dimen/activity_vertical_margin"
        android:gravity="center_vertical"
        android:background="@drawable/countdown_background">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/days_counter"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:gravity="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

            <TextView
                android:id="@+id/days_indicator"
                android:layout_width="0dp"
                android:layout_weight="2"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginStart="@dimen/activity_vertical_margin"
                android:maxLines="1"
                android:ellipsize="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/hours_counter"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:gravity="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

            <TextView
                android:id="@+id/hours_indicator"
                android:layout_width="0dp"
                android:layout_weight="2"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginStart="@dimen/activity_vertical_margin"
                android:maxLines="1"
                android:ellipsize="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/minutes_counter"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:gravity="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

            <TextView
                android:id="@+id/minutes_indicator"
                android:layout_width="0dp"
                android:layout_weight="2"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginStart="@dimen/activity_vertical_margin"
                android:maxLines="1"
                android:ellipsize="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/seconds_counter"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:gravity="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

            <TextView
                android:id="@+id/seconds_indicator"
                android:layout_width="0dp"
                android:layout_weight="2"
                android:layout_height="wrap_content"
                android:textSize="@dimen/countdown_numbers_font_size"
                android:textColor="@color/white"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginStart="@dimen/activity_vertical_margin"
                android:maxLines="1"
                android:ellipsize="end"
                android:shadowColor="@android:color/black"
                android:shadowDx="1"
                android:shadowDy="1"
                android:shadowRadius="1" />

        </LinearLayout>

        <TextView
            android:id="@+id/remaining_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="@string/till_junamex"
            android:textSize="@dimen/countdown_subtitle_font_size"
            android:textColor="@color/white"
            android:shadowColor="@android:color/black"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="1"/>

    </LinearLayout>

    <include layout="@layout/toolbar"/>
</RelativeLayout>


text:
class UserPasswordResetsController < ApplicationController

  before_filter :load_user_using_perishable_token, :only => [:edit, :update]

  def new
  end

  def create
    @user = User.find_by_email(params[:user][:email])
    if @user
      @user.reset_perishable_token!
      UserMailer.reset_password(@user).deliver
      redirect_to(login_path, :notice => t("successfully_created", :scope => 'user_password_resets.controller'))
    else
      @user = User.new(:email => params[:user][:email])
      @user.valid?
      render :new
    end
  end

  def edit

  end

  def update
    @user.password = params[:user][:password]
    @user.password_confirmation = params[:user][:password_confirmation]
    if @user.save
      redirect_to(root_path, :notice => t("successfully_updated", :scope => 'user_password_reset.controller'))
    else
      render :action => :edit
    end
  end
end


text:
/**
 * Graphical editor
 */
function GUIEditor(editor) {
	this.editor = editor;
	this.guiContent = null;
	this.xmlContent = null;
	this.elementIndex = 0;
	this.rootElement = null;
	this.active = false;
	this.selectedElement = null;
}

GUIEditor.prototype.initialize = function(parentContainer) {
	this.xmlContent = $("<div class='" + xmlContentClass + "'/>");
	this.xmlContent.data("xml", {});
	this.placeholder = $("<div/>").attr("class", "placeholder").html("There are no elements in this document.  Use the menu on the right to add new top level elements.")
			.appendTo(this.xmlContent);

	this.guiContent = $("<div/>").attr({'id' : guiContentClass + this.editor.instanceNumber, 'class' : guiContentClass}).appendTo(parentContainer);

	this.guiContent.append(this.xmlContent);

	this.documentElement = new AbstractXMLObject(this.editor, null);
	this.documentElement.domNode = this.xmlContent;
	this.documentElement.childContainer = this.xmlContent;
	this.documentElement.placeholder = this.placeholder;

	this.setRootElement(this.editor.xmlState.xml.children()[0], false);

	this._initEventBindings();
	return this;
};

// Set the root element for this editor
// node - xml node from an xml document to be used as the root node for this editor
GUIEditor.prototype.setRootElement = function(node, render) {
	var objectType = this.editor.schemaTree.getElementDefinition(node);
	if (objectType == null)
		objectType = this.editor.schemaTree.rootElement;
	this.rootElement = new XMLElement(node, objectType, this.editor);
	if (render || arguments.length == 1)
		this.rootElement.render(this.documentElement, true);
};

// Initialize editor wide event bindings
GUIEditor.prototype._initEventBindings = function() {
	var self = this;
	// Attributes
	this.xmlContent.on('click', '.' + attributeContainerClass, function(event){
		$(this).data('xmlAttribute').select();
		event.stopPropagation();
	}).on('click', '.' + attributeContainerClass + " > a", function(event){
		var attribute = $(this).parents('.' + attributeContainerClass).eq(0).data('xmlAttribute');
		attribute.remove();
		attribute.xmlElement.updated({action : 'attributeRemoved', target : attribute});
		self.editor.xmlState.documentChangedEvent();
		event.stopPropagation();
	}).on('change', '.' + attributeContainerClass + ' > input,.' + attributeContainerClass + ' > textarea,'
			+ '.' + attributeContainerClass + ' > select', function(event){
		var attribute = $(this).parents('.' + attributeContainerClass).eq(0).data('xmlAttribute');
		attribute.syncValue();
		attribute.xmlElement.updated({action : 'attributeSynced', target : attribute});
		self.editor.xmlState.documentChangedEvent();
	});
	// Element
	this.xmlContent.on('click', '.' + xmlElementClass, function(event){
		self.selectElement(this);
		event.stopPropagation();
	}).on('click', '.move_up', function(event){
		self.moveElement($(this).parents('.' + xmlElementClass).eq(0).data('xmlElement'), true);
		event.stopPropagation();
	}).on('click', '.move_down', function(event){
		self.moveElement($(this).parents('.' + xmlElementClass).eq(0).data('xmlElement'));
		event.stopPropagation();
	}).on('click', '.top_actions .delete', function(event){
		self.deleteElement($(this).parents('.' + xmlElementClass).eq(0).data('xmlElement'));
		event.stopPropagation();
	}).on('click', '.toggle_collapse', function(event){
		var $this = $(this);
		var contentBlock = $this.closest('.' + xmlElementClass).find('.content_block');
		if ($this.html() == "+") {
			$this.html("_");
			contentBlock.slideDown(200);
		} else {
			$this.html("+");
			contentBlock.slideUp(200);
		}
		event.stopPropagation();
	}).on('change', '.element_text', function(event){
		var xmlElement = $(this).parents('.' + xmlElementClass).eq(0).data('xmlElement')
		xmlElement.syncText();
		xmlElement.updated({action : 'valueSynced'});
		self.editor.xmlState.documentChangedEvent();
	});
};

// Make this editor the active editor and show it
GUIEditor.prototype.activate = function() {
	this.active = true;
	this.deselect();

	this.editor.textEditor.resetSelectedTagRange();
	if (this.editor.textEditor.isModified() || (this.editor.textEditor.isInitialized() && this.editor.xmlState.isChanged())) {
		this.editor.refreshDisplay();
		this.editor.textEditor.setInitialized();
	}
	this.guiContent.show();
	return this;
};

// Deactivate and hide this editor
GUIEditor.prototype.deactivate = function() {
	this.active = false;
	this.guiContent.hide();
	return this;
};

// Get the next index in the sequence to be used for uniquely addressable ids
GUIEditor.prototype.nextIndex = function() {
	return xmlElementClass + (++this.elementIndex);
};

// Clear all elements
GUIEditor.prototype.clearElements = function() {
	$("." + topLevelContainerClass).remove();
	return this;
};

GUIEditor.prototype.resize = function() {
	//xmlContent.width(guiContent.width() - menuContainer.width() - 30);
	return this;
};

// Refresh the contents of this editor
GUIEditor.prototype.refreshDisplay = function() {
	this.deselect();
	this.elementIndex = 0;
	this.rootElement.xmlNode = this.editor.xmlState.xml.children().first();
	this.refreshElements();
	return this;
};

// Refresh the display of all elements
GUIEditor.prototype.refreshElements = function() {
	var node = this.documentElement.getDomNode();
	node.empty();
	node = node[0];
	var originalParent = node.parentNode;
	var fragment = document.createDocumentFragment();
	fragment.appendChild(node);

	// Clear out the previous contents and then rebuild it
	this.rootElement.render(this.documentElement, true);
	this.editor.addTopLevelMenu.populate(this.rootElement);

	originalParent.appendChild(fragment);
	return this;
};

// Inform the editor that a new element has been added, and update the editor state accordingly
GUIEditor.prototype.addElementEvent = function(parentElement, newElement) {
	if (parentElement.domNodeID != this.xmlContent.attr("id")) {
		parentElement.updated({action : 'childAdded', target : newElement});
	}

	var state = this.editor;

	this.focusObject(newElement.domNode);
	this.selectElement(newElement);
	if (parentElement == this.rootElement)
		this.editor.addTopLevelMenu.populate(this.rootElement);
	this.editor.xmlState.documentChangedEvent();
	this.editor.resize();
};

// Inform the editor that a new attribute has been added
GUIEditor.prototype.addAttributeEvent = function(parentElement, objectType, addButton) {
	var attribute = new XMLAttribute(objectType, parentElement, this.editor);
	attribute.render();
	parentElement.updated({action : 'attributeAdded', target : objectType.name});
	this.focusObject(attribute.attributeContainer);
	addButton.addClass("disabled");
	attribute.addButton = addButton;
	this.editor.xmlState.documentChangedEvent();
	this.editor.resize();
};

// Select element selected and inform the editor state of this change
GUIEditor.prototype.selectElement = function(selected) {
	if (!selected || selected.length == 0) {
		this.deselect();
	} else {
		$("." + xmlElementClass + ".selected").removeClass("selected");
		$('.' + attributeContainerClass + ".selected").removeClass("selected");
		if (selected instanceof XMLElement){
			this.selectedElement = selected;
		} else {
			selected = $(selected);
			this.selectedElement = selected.data("xmlElement");
			selected = this.selectedElement;
		}
		selected.select();
		this.editor.modifyMenu.refreshContextualMenus(selected);
	}
	return this;
};

// Unselect the currently selected element or attribute
GUIEditor.prototype.deselect = function() {
	var selectedAttributes = $('.' + attributeContainerClass + ".selected");
	if (selectedAttributes.length > 0) {
		selectedAttributes.removeClass('selected');
		return this;
	}
	$("." + xmlElementClass + ".selected").removeClass("selected");
	this.selectedElement = null;
	if (this.editor.modifyMenu != null)
		this.editor.modifyMenu.clearContextualMenus();
	return this;
};

// Delete the selected element or attribute
GUIEditor.prototype.deleteSelected = function() {
	if (this.selectedElement == null)
		return this;
	try {
		var selectedAttribute = this.selectedElement.getSelectedAttribute();
	} catch(error) {
		// Attribute container undefined
		var selectedAttribute = [];
		selectedAttribute.length = 0;
	}
	if (selectedAttribute.length > 0) {
		this.selectAttribute(true);
		var newSelection = selectedAttribute.prev('.' + attributeContainerClass);
		if (newSelection.length == 0)
			newSelection = selectedAttribute.next('.' + attributeContainerClass);
		newSelection.addClass("selected");

		var xmlAttribute = selectedAttribute.data("xmlAttribute");
		xmlAttribute.remove();
	} else {
		this.deleteElement(this.selectedElement);
	}
	return this;
};

// Delete an element from the document and update the editor state
GUIEditor.prototype.deleteElement = function(xmlElement) {
	var parent = xmlElement.parentElement;
	var index = xmlElement.objectType.localName;
	if (!parent || !(parent instanceof XMLElement) || !parent.childCanBeRemoved(xmlElement.objectType))
		return;
	parent.childRemoved(xmlElement);
	var isSelected = xmlElement.isSelected();
	if (isSelected) {
		var afterDeleteSelection = xmlElement.domNode.next("." + xmlElementClass);
		if (afterDeleteSelection.length == 0)
			afterDeleteSelection = xmlElement.domNode.prev("." + xmlElementClass);
		if (afterDeleteSelection.length == 0)
			afterDeleteSelection = xmlElement.domNode.parents("." + xmlElementClass).first();
		this.selectElement(afterDeleteSelection);
	} else if (parent.isSelected && parent != this.rootElement) {
		this.editor.modifyMenu.refreshContextualMenus(parent);
	}
	if (parent == this.rootElement) {
		this.editor.addTopLevelMenu.populate(this.rootElement);
	}
	xmlElement.remove();
	parent.updated({action : 'childRemoved', target : xmlElement});
	this.editor.xmlState.documentChangedEvent();
	return this;
};

// Move the currently selected element by x number of positions
GUIEditor.prototype.moveSelected = function(up) {
	return this.moveElement(this.selectedElement, up);
};

// Move xmlElement by x number of positions
GUIEditor.prototype.moveElement = function(xmlElement, up) {
	if (xmlElement == null)
		return this;
	var result = up? xmlElement.moveUp() : xmlElement.moveDown();
	if (result) {
		this.editor.xmlState.documentChangedEvent();
		xmlElement.focus();
	}
	return this;
};

// Update an elements position in the XML document to reflect its position in the editor
GUIEditor.prototype.updateElementPosition = function(moved) {
	var movedElement = moved.data('xmlElement');

	var sibling = moved.prev('.' + xmlElementClass);
	if (sibling.length == 0) {
		sibling = moved.next('.' + xmlElementClass);
		movedElement.xmlNode.detach().insertBefore(sibling.data('xmlElement').xmlNode);
	} else {
		movedElement.xmlNode.detach().insertAfter(sibling.data('xmlElement').xmlNode);
	}
	this.selectElement(moved);
	this.editor.xmlState.documentChangedEvent();
};

// Select the next or previous sibling element of the selected element
GUIEditor.prototype.selectSibling = function(reverse) {
	var direction = reverse? 'prev' : 'next';
	if (this.selectedElement.domNode.length > 0) {
		newSelection = this.selectedElement.domNode[direction]("." + xmlElementClass);
		if (newSelection.length == 0 && !this.selectedElement.isTopLevel) {
			// If there is no next sibling but the parent has one, then go to parents sibling
			this.selectedElement.domNode.parents("." + xmlElementClass).each(function(){
				newSelection = $(this)[direction]("." + xmlElementClass);
				if (newSelection.length > 0 || $(this).data("xmlElement").isTopLevel)
					return false;
			});
		}
	} else {
		if (!reverse)
			newSelection = $("." + xmlElementClass).first();
	}

	if (newSelection.length == 0)
		return this;
	this.selectElement(newSelection.first()).selectedElement.focus();
	return this;
};

// Select the parent of the currently selected element
GUIEditor.prototype.selectParent = function(reverse) {
	if (reverse)
		newSelection = this.selectedElement.domNode.find("." + xmlElementClass);
	else newSelection = this.selectedElement.domNode.parents("." + xmlElementClass);
	if (newSelection.length == 0)
		return this;
	this.selectElement(newSelection.first()).selectedElement.focus();
	return this;
};

// Select the next child of the currently selected element.  If it has no children,
// then select the next sibling if any are available.
GUIEditor.prototype.selectNext = function(reverse) {
	var newSelection = null;
	if (this.selectedElement == null) {
		if (!reverse)
			newSelection = $("." + xmlElementClass).first();
	} else {
		var found = false;
		var allElements = $("." + xmlElementClass + ":visible", this.xmlContent);

		if (reverse)
			allElements = $(allElements.get().reverse());

		var selectedElement = this.selectedElement;
		allElements.each(function(){
			if (found) {
				newSelection = $(this);
				return false;
			} else if (this.id == selectedElement.domNodeID) {
				found = true;
			}
		});
	}

	if (newSelection != null)
		this.selectElement(newSelection.first()).selectedElement.focus();
	return this;
};

// Select the previous or next attribute of the selected element
GUIEditor.prototype.selectAttribute = function(reverse) {
	if (this.selectedElement == null) {
		return this;
	} else {
		var selectedAttribute = this.selectedElement.getSelectedAttribute();
		if (selectedAttribute.length > 0) {
			var newSelection = selectedAttribute[reverse? 'prev' : 'next']("." + attributeContainerClass);
			if (newSelection.length > 0) {
				$("." + attributeContainerClass + ".selected").removeClass("selected");
				newSelection.addClass("selected");
			}
		} else {
			if (this.selectedElement.attributeContainer)
				selectedAttribute = this.selectedElement.attributeContainer.children("." + attributeContainerClass)
						.first().addClass("selected");
		}
	}
};

// Find and select the nearest element text field in an element or its children
GUIEditor.prototype.focusSelectedText = function() {
	if (this.selectedElement == null)
		return this;
	var focused = null;
	if (this.selectedElement.textInput != null) {
		focused = this.selectedElement.textInput.focus();
	} else {
		focused = this.selectedElement.domNode.find("input[type=text].element_text:visible, textarea.element_text:visible, select.element_text:visible").first().focus();
	}
	if (focused == null || focused.length == 0)
		return this;
	// If the focused input was in an element other than the selected one, then select it
	var containerElement = focused.parents("." + xmlElementClass);
	if (containerElement !== this.selectedElement)
		this.selectElement(containerElement);
	return this;
};

// Find and focus the nearest input field in the selected element or its children.  If the
// input field focused belonged to a child, then select that child.
GUIEditor.prototype.focusInput = function(reverse) {
	var focused = $("input:focus, textarea:focus, select:focus");
	if (focused.length == 0 && this.selectedElement == null) {
		if (reverse)
			return this;
		// Nothing is selected or focused, so grab the first available input
		focused = this.xmlContent.find("input[type=text]:visible, textarea:visible, select:visible").first().focus();
	} else {
		// When an input is already focused, tabbing selects the next input
		var foundFocus = false;
		var inputsSelector = "input[type=text]:visible, textarea:visible, select:visible";
		// If no inputs are focused but an element is selected, seek the next input near this element
		if (this.selectedElement != null && focused.length == 0) {
			inputsSelector += ", ." + xmlElementClass;
			focused = this.selectedElement.domNode;
		}
		var visibleInputs = this.xmlContent.find(inputsSelector);
		// If in reverse mode, get the previous input
		if (reverse) {
			visibleInputs = $(visibleInputs.get().reverse());
		}
		// Seek the next input after the focused one
		visibleInputs.each(function(){
			// Can't focus a xml class if they are present.
			if (foundFocus && !$(this).hasClass(xmlElementClass)) {
				focused = $(this).focus();
				return false;
			} else if (this.id == focused.attr('id')) {
				foundFocus = true;
			}
		});
	}
	// If the focused input was in an element other than the selected one, then select it
	var containerElement = focused.parents("." + xmlElementClass);
	if (containerElement !== this.selectedElement)
		this.selectElement(containerElement);
	var container = focused.parents('.' + attributeContainerClass);
	if (container.length > 0)
		container.addClass('selected');
	return this;
};

// Return true if the given dom node is vertically completely on screen
GUIEditor.prototype.isCompletelyOnScreen = function(object) {
	var objectTop = object.offset().top;
	var objectBottom = objectTop + object.height();
	var docViewTop = $(window).scrollTop() + this.editor.editorHeader.height();
	var docViewBottom = docViewTop + $(window).height() - this.editor.editorHeader.height();

	return (docViewTop < objectTop) && (docViewBottom > objectBottom);
};

// If the given target is not completely on screen then scroll the window to the top of the target
GUIEditor.prototype.focusObject = function(focusTarget) {
	if (!this.isCompletelyOnScreen(focusTarget)){
		var scrollHeight = focusTarget.offset().top + (focusTarget.height()/2) - ($(window).height()/2);
		if (scrollHeight > focusTarget.offset().top)
			scrollHeight = focusTarget.offset().top;
		scrollHeight -= this.editor.editorHeader.height();
		$("html, body").stop().animate({ scrollTop: scrollHeight }, 500);
	}
};


text:
var MAX_RETRIEVED_POSTS = 20;

displayedCards = new ReactiveVar('');
retrievedCards = new ReactiveVar('');
keywords = new ReactiveVar('');

function getInitialCards() {

    var fbPage = Session.get("fbPage");
    if (fbPage) {
        //get page posts
        Meteor.call('getProcessedPagePosts', fbPage, MAX_RETRIEVED_POSTS, function (err, postsData) {
            if (err) {
                console.log(err);
                Session.set("retrievingCards", false);
            }
            else {
                if (postsData && postsData.data) {

                    displayedCards.set(postsData.data);
                    retrievedCards.set(postsData.data);

                    $('#refreshPostsButton').removeClass('disabled');

                    //pagination
                    if (postsData.paging.next) {
                        Session.set("nextPostsUntil", postsData.paging.next);
                    }
                    else {
                        Session.set("nextPostsUntil", "");
                    }
                }
                Session.set("retrievingCards", false);
            }
        });
    }
}

function loadMoreCards() {
    if (!Session.get("retrievingCards")) {
        Session.set("retrievingCards", true);
        var fbPage = Session.get("fbPage");
        var nextPostsUntil = Session.get("nextPostsUntil");
        if (fbPage && nextPostsUntil) {
            //get page posts
            Meteor.call('getProcessedPagePosts', fbPage, MAX_RETRIEVED_POSTS, nextPostsUntil, function (err, postsData) {
                if (err) {
                    console.log(err);
                    Session.set("retrievingCards", false);
                }
                else {
                    if (postsData && postsData.data) {
                        var lastCard = retrievedCards.get()[retrievedCards.get().length - 1];
                        var newCards = [];

                        //First post from the "next" posts if the same as the last post from the previous set of posts, Facebook magic dunno :)
                        //Probably something to do with the until timestamp, easy fix is to remove it so we don't have duplicate posts
                        if (lastCard && (lastCard.id == postsData.data[0].id)) {
                            newCards = _.rest(postsData.data, 1);
                        }
                        else {
                            newCards = postsData.data;
                        }

                        retrievedCards.set(retrievedCards.get().concat(newCards));

                        // search keywords
                        if (keywords.get()) {
                            var filteredCards = [];
                            var keywordsArray = [];
                            _.each(keywords.get(), function(introducedKeyword){
                                    keywordsArray.push(introducedKeyword.keyword);
                            });
                            var regex = new RegExp(keywordsArray.join("|").toLocaleLowerCase());
                            _.each(retrievedCards.get(), function (card) {
                                if (card.message) {
                                    if (regex.test(card.message.toLowerCase())) {
                                        filteredCards.push(card);
                                    }
                                }
                            });
                            displayedCards.set(filteredCards);
                        }
                        else {
                            displayedCards.set(displayedCards.get().concat(newCards));
                        }

                        //pagination
                        if (postsData.paging.next) {
                            Session.set("nextPostsUntil", postsData.paging.next);
                        }
                        else {
                            Session.set("nextPostsUntil", "");
                        }
                    }
                    Session.set("retrievingCards", false);
                }
            });
        }
    }
}

function refreshPosts() {
    $('#searchInput').val('');
    keywords.set('');
    displayedCards.set('');
    retrievedCards.set('');
    getInitialCards();
}

function trimSpaces(string){
    string = string.replace(/(^\s*)|(\s*$)/gi,"");
    string = string.replace(/[ ]{2,}/gi," ");
    string = string.replace(/\n /,"\n");
    return string;
}

Template.index.created = function () {
    Session.set("fbPage", Router.current().params.pageName);
}

Template.index.onRendered(function () {
    refreshPosts();

});

Template.postsContainerTemplate.onRendered(function () {

    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            loadMoreCards();
        }
    });
});

Template.index.events({

    'submit .changePageForm': function (event) {
        event.preventDefault();

        $("#changePageModal").modal("hide");
        var newPage = event.target.pageName.value;

        if (newPage) {
            Session.set("fbPage", newPage);
            Router.go('index', {pageName: newPage});
            refreshPosts();
        }

        // Prevent default form submit
        return false;
    },

    'click #refreshPostsButton': function () {
        refreshPosts();
    },

    'click #searchButton': function () {
        if (Session.get("fbPage")) {
            if (retrievedCards.get() && $('#searchInput').val()) {
                var introducedKeywords = trimSpaces($('#searchInput').val()).split(' ');
                var keywordsObjects = [];
                _.each(introducedKeywords, function(introducedKeyword) {
                    keywordsObjects.push({
                        keyword : introducedKeyword
                    });
                });
                keywords.set(keywordsObjects);
                var filteredCards = [];
                var regex = new RegExp(introducedKeywords.join("|").toLocaleLowerCase());
                _.each(retrievedCards.get(), function (card) {
                    if (card.message) {
                        if (regex.test(card.message.toLowerCase())) {
                            filteredCards.push(card);
                        }
                    }
                });
                displayedCards.set(filteredCards);
            }
            else {
                refreshPosts();
            }
        }
    },

    'click #loadMorePostsButton': function () {
        loadMoreCards();
    }
});

Template.index.helpers({
    fbPage: function () {
        return Session.get("fbPage");
    },

    displayedCards: function () {
        return displayedCards.get();
    },

    retrievedCards: function () {
        return retrievedCards.get();
    },

    keywords : function() {
      return keywords.get();
    }
});

Template.postsContainerTemplate.helpers({
    displayedCards: function () {
        return displayedCards.get();
    }
});


text:
package svk.sglubos.opencalculator.gui.components.calculations;

import java.math.BigDecimal;
import svk.sglubos.calculationlib.data.VariableDatabase;
import svk.sglubos.calculationlib.maths.MathematicalCore;
import svk.sglubos.calculationlib.maths.Variable;
import svk.sglubos.calculationlib.util.GreekAlphabeth;
import svk.sglubos.opencalculator.Config;
import svk.sglubos.opencalculator.api.gui.components.CalculationPanelCore;
import svk.sglubos.opencalculator.api.gui.components.calculationlog.CalculationLogBuilder;
import svk.sglubos.opencalculator.gui.components.DatabasePanel;

public class OverenieOhybPanel extends CalculationPanelCore {
    private DatabasePanel display;
    /**
     * Creates new form CalculationPanelTemplate
     */
    public OverenieOhybPanel() {
        initComponents();

        name = "Overenie v ohybe";

        initBuilder(200);
    }

     public void setDatabaseDisplay(DatabasePanel display) {
        this.display = display;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        inputWrapper = new javax.swing.JPanel();
        mdNumberPanel = new svk.sglubos.calculationlib.gui.components.GenericNumberPane();
        hNumberPanel = new svk.sglubos.calculationlib.gui.components.GenericNumberPane();
        bNumberPanel = new svk.sglubos.calculationlib.gui.components.GenericNumberPane();
        showCalculationButton = new javax.swing.JButton();
        calculateButton = new javax.swing.JButton();
        outputWrapper = new javax.swing.JPanel();
        vyuzitiePercentNumberPane = new svk.sglubos.calculationlib.gui.components.GenericNumberPane();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Overenie v ohybe"));

        inputWrapper.setBorder(javax.swing.BorderFactory.createTitledBorder("Vstup"));

        mdNumberPanel.setNameLabel("Md");
        mdNumberPanel.setUnitLabel("kN*m");

        hNumberPanel.setNameLabel("h");
        hNumberPanel.setUnitLabel("mm");

        bNumberPanel.setNameLabel("B");
        bNumberPanel.setUnitLabel("mm");

        javax.swing.GroupLayout inputWrapperLayout = new javax.swing.GroupLayout(inputWrapper);
        inputWrapper.setLayout(inputWrapperLayout);
        inputWrapperLayout.setHorizontalGroup(
            inputWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(inputWrapperLayout.createSequentialGroup()
                .addGroup(inputWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(inputWrapperLayout.createSequentialGroup()
                        .addComponent(bNumberPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hNumberPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(mdNumberPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 20, Short.MAX_VALUE))
        );
        inputWrapperLayout.setVerticalGroup(
            inputWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(inputWrapperLayout.createSequentialGroup()
                .addGroup(inputWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bNumberPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(hNumberPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mdNumberPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );

        showCalculationButton.setText("Zobraziť výpočet");
        showCalculationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showCalculationButtonActionPerformed(evt);
            }
        });

        calculateButton.setText("Vypočítať");
        calculateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calculateButtonActionPerformed(evt);
            }
        });

        outputWrapper.setBorder(javax.swing.BorderFactory.createTitledBorder("Výsledky"));

        vyuzitiePercentNumberPane.setEditable(false);
        vyuzitiePercentNumberPane.setNameLabel("Využitie");
        vyuzitiePercentNumberPane.setUnitLabel("%");

        javax.swing.GroupLayout outputWrapperLayout = new javax.swing.GroupLayout(outputWrapper);
        outputWrapper.setLayout(outputWrapperLayout);
        outputWrapperLayout.setHorizontalGroup(
            outputWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(outputWrapperLayout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(vyuzitiePercentNumberPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        outputWrapperLayout.setVerticalGroup(
            outputWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, outputWrapperLayout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(vyuzitiePercentNumberPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(inputWrapper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(calculateButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(showCalculationButton))
                    .addComponent(outputWrapper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(inputWrapper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(calculateButton)
                    .addComponent(showCalculationButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(outputWrapper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void showCalculationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showCalculationButtonActionPerformed
       showCalculation();
    }//GEN-LAST:event_showCalculationButtonActionPerformed

    private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calculateButtonActionPerformed
        if(isValidCalculation()) {
            calculate();
        }
    }//GEN-LAST:event_calculateButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private svk.sglubos.calculationlib.gui.components.GenericNumberPane bNumberPanel;
    private javax.swing.JButton calculateButton;
    private svk.sglubos.calculationlib.gui.components.GenericNumberPane hNumberPanel;
    private javax.swing.JPanel inputWrapper;
    private svk.sglubos.calculationlib.gui.components.GenericNumberPane mdNumberPanel;
    private javax.swing.JPanel outputWrapper;
    private javax.swing.JButton showCalculationButton;
    private svk.sglubos.calculationlib.gui.components.GenericNumberPane vyuzitiePercentNumberPane;
    // End of variables declaration//GEN-END:variables

    private boolean isValidCalculation() {
        return (bNumberPanel.isValidValue() && hNumberPanel.isValidValue() && mdNumberPanel.isValidValue());
    }

    private void calculate() {
        builder.reset();

        Variable b = bNumberPanel.getValue();
        Variable h = hNumberPanel.getValue();
        Variable md = mdNumberPanel.getValue();

        Variable kmod = core.get(MathematicalCore.LOCATION_EXTERNAL, "kmod");
        Variable gamman = core.get(MathematicalCore.LOCATION_EXTERNAL, "gamman");
        Variable fmk = core.get(MathematicalCore.LOCATION_EXTERNAL, display.getDatabaseType().equals("rastene") ? "fmk" : "fmgk");

        builder.append(b, bNumberPanel);
        builder.append(h, hNumberPanel);
        builder.append(md, mdNumberPanel);
        builder.paragraph();

        builder.appendString("Drevo: ", ((VariableDatabase) display.getCurrentDatabase()).getName());
        builder.append(kmod.getValue(), kmod.getEvaluationVars());
        builder.append(gamman.getValue(), gamman.getEvaluationVars());
        builder.paragraph();

        Variable vy = new Variable(BigDecimal.ONE.divide(new BigDecimal("6"), Config.CALCULATION__MATH_CONTEXT)).multiply(b.scale(-3)).multiply(h.scale(-3).pow(2));
        builder.append(vy, "Vy", "m^3");
        builder.paragraph();
        vy.setEvaluation(vy.getValue().toPlainString());
        vy.setEvaluationVars("Vy");

        Variable sigma = md.scale(-3).divide(vy);
        builder.append(sigma, GreekAlphabeth.Lowercase.SIGMA + "md", "MPa");
        builder.paragraph();
        sigma.setEvaluation(sigma.getValue().toPlainString());
        sigma.setEvaluationVars(GreekAlphabeth.Lowercase.SIGMA + "md");

        Variable fmd = kmod.multiply(fmk.divide(gamman));
        builder.append(fmd, "Fmd", "MPa");
        builder.paragraph();
        fmd.setEvaluation(fmd.getValue().toPlainString());
        fmd.setEvaluationVars("Fmd");

        Variable vyuzitiepercent = sigma.divide(fmd).scale(2);
        builder.append(vyuzitiepercent, "využitie ", "%");
        vyuzitiePercentNumberPane.display(vyuzitiepercent.getValue(), Config.DISPLAY_PRECISSION);

        calculated = true;
         if(logger.openNewCalculation()) {
            showCalculation();
        }
    }
}


text:
package kodkod.engine.ucore;

import kodkod.engine.fol2sat.TranslationLog;
import kodkod.engine.fol2sat.Translator;
import kodkod.engine.satlab.ReductionStrategy;
import kodkod.engine.satlab.ResolutionTrace;
import kodkod.util.ints.IntCollection;
import kodkod.util.ints.IntSet;
import kodkod.util.ints.IntTreeSet;
import kodkod.util.ints.Ints;

/**
* Naive Core Extraction is a strategy for generating unsat cores that are minimal at the logic level.
 * Specifically, let C be a core that is minimal according to this strategy,
 * and let F(C) be the top-level logic constraints
 * corresponding to C.  Then, this strategy guarantees that there is no clause
 * c in C such that F(C - c) is a strict subset of F(C). Furthermore, it also
 * guarantees that for all f in F(C), F(C) - f is satisfiable.  This is a stronger
 * guarantee than that of {@linkplain HybridStrategy}.  In general, using this strategy
 * is more expensive, timewise, than using {@linkplain HybridStrategy}.
 *
 * <p>This implementation of NCE will work properly only on CNFs generated by the kodkod {@linkplain Translator}. </p>
* @author Emina Torlak
* @see HybridStrategy
*/
public final class NCEStrategy implements ReductionStrategy {
	private final IntCollection varsToTry;
	private final IntSet coreVars;

	/**
	 * Constructs an NCE strategy that will use the given translation
	 * log to relate the cnf clauses back to the logic constraints from
	 * which they were generated.
	 */
	public NCEStrategy(final TranslationLog log) {
		varsToTry = StrategyUtils.rootVars(log);
		coreVars = new IntTreeSet();//new IntTreeSet(varsToTry);
		coreVars.addAll(varsToTry);
	}

	/**
	 * {@inheritDoc}
	 * @see kodkod.engine.satlab.ReductionStrategy#next(kodkod.engine.satlab.ResolutionTrace)
	 */
	public IntSet next(ResolutionTrace trace) {
		if (varsToTry.isEmpty()) return Ints.EMPTY_SET;
		// if the last attempt at reduction was unsuccessful,
		// add the unit clauses that we tried to discard back to coreVars
		coreVars.addAll(StrategyUtils.coreTailUnits(trace));
		final int first = varsToTry.iterator().next();//varsToTry.min();
		varsToTry.remove(first);
		coreVars.remove(first);
		// get all axioms corresponding to the clauses that
		// form the translations of formulas identified by coreVars
		final IntSet relevantClauses = StrategyUtils.clausesFor(trace, coreVars);
		assert !relevantClauses.isEmpty() && !relevantClauses.contains(trace.size()-1);
		return relevantClauses;
	}

}