text:
<?php

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 *
 * @author Denis Simakov <akinoame1@gmail.com>
 * @author Andrew Pleshakov <beotiger@mail.ru>
 * @author Змей Этерийский evil_snake@eternion.ru
 * @author Hikaru Nakajima <jisatsu@mail.ru>
 * @author Alexei Tereschenko <alexeitlex@yahoo.com>
 * @author Irina Ponomareva irinaponomareva@webperfectionist.com
 * @author Alexander Sorkin <kibizoid@gmail.com>
 * @author Kirill Krasnov <krasnovforum@gmail.com>
 * @author Vlad Tsybenko <vlad.development@gmail.com>
 * @author Aleksey Osadchiy <rfc@nm.ru>
 * @author Aleksandr Selivanov <alexgearbox@gmail.com>
 * @author Ladyko Andrey <fylh@succexy.spb.ru>
 * @author Eugene <windy.wanderer@gmail.com>
 * @author Johnny Utah <pcpa@cyberpunk.su>
 * @author Ivan I. Udovichenko (sendtome@mymailbox.pp.ua)
 */
$lang['menu']                  = 'Управление плагинами';
$lang['download']              = 'Скачать и установить новый плагин';
$lang['manage']                = 'Установленные плагины';
$lang['btn_info']              = 'данные';
$lang['btn_update']            = 'обновить';
$lang['btn_delete']            = 'удалить';
$lang['btn_settings']          = 'настройки';
$lang['btn_download']          = 'Скачать';
$lang['btn_enable']            = 'Сохранить';
$lang['url']                   = 'Адрес';
$lang['installed']             = 'Установлен:';
$lang['lastupdate']            = 'Последнее обновление:';
$lang['source']                = 'Источник:';
$lang['unknown']               = 'неизвестно';
$lang['updating']              = 'Обновление...';
$lang['updated']               = 'Плагин %s успешно обновлён';
$lang['updates']               = 'Следующие плагины были успешно обновлены';
$lang['update_none']           = 'Обновления не найдены.';
$lang['deleting']              = 'Удаление...';
$lang['deleted']               = 'Плагин %s удалён.';
$lang['downloading']           = 'Скачивание...';
$lang['downloaded']            = 'Плагин %s успешно установлен';
$lang['downloads']             = 'Следующие плагины были успешно установлены:';
$lang['download_none']         = 'Плагины не найдены или возникла неизвестная проблема в процессе скачивания и установки.';
$lang['plugin']                = 'Плагин:';
$lang['components']            = 'Компоненты';
$lang['noinfo']                = 'Этот плагин не сообщил никаких данных, он может быть нерабочим.';
$lang['name']                  = 'Название:';
$lang['date']                  = 'Дата:';
$lang['type']                  = 'Тип:';
$lang['desc']                  = 'Описание:';
$lang['author']                = 'Автор:';
$lang['www']                   = 'Страница:';
$lang['error']                 = 'Произошла неизвестная ошибка.';
$lang['error_download']        = 'Не могу скачать файл плагина: %s';
$lang['error_badurl']          = 'Возможно неправильный адрес — не могу определить имя файла из адреса';
$lang['error_dircreate']       = 'Не могу создать временную директорию для скачивания';
$lang['error_decompress']      = 'Менеджеру плагинов не удалось распаковать скачанный файл. Это может быть результатом ошибки при скачивании, в этом случае вы можете попробовать снова, или же плагин упакован неизвестным архиватором, тогда вам необходимо скачать и установить плагин вручную.';
$lang['error_copy']            = 'Произошла ошибка копирования при попытке установки файлов для плагина %s: переполнение диска или неправильные права доступа. Это могло привести к частичной установке плагина и неустойчивости работы вашей вики.';
$lang['error_delete']          = 'Произошла ошибка при попытке удалить плагин %s.  Наиболее вероятно, что нет необходимых прав доступа к файлам или директориям';
$lang['enabled']               = 'Плагин %s включен.';
$lang['notenabled']            = 'Не удалось включить плагин %s. Проверьте системные права доступа к файлам.';
$lang['disabled']              = 'Плагин %s отключен.';
$lang['notdisabled']           = 'Не удалось отключить плагин %s. Проверьте системные права доступа к файлам.';
$lang['packageinstalled']      = 'Пакет (%d плагин(а): %s) успешно установлен.';


text:
double
attribute_hidden
erfl (double x)
{
  return erf (x);
}

redpajama_set_name: RedPajamaGithub


text:
WINRT_EXPORT namespace winrt {

namespace ABI::Windows::Foundation::Collections {

#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif

#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif

#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif

#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif

}

namespace Windows::ApplicationModel::DataTransfer::ShareTarget {

template <typename D>
struct WINRT_EBO impl_IQuickLink
{
    hstring Title() const;
    void Title(hstring_ref value) const;
    Windows::Storage::Streams::RandomAccessStreamReference Thumbnail() const;
    void Thumbnail(const Windows::Storage::Streams::RandomAccessStreamReference & value) const;
    hstring Id() const;
    void Id(hstring_ref value) const;
    Windows::Foundation::Collections::IVector<hstring> SupportedDataFormats() const;
    Windows::Foundation::Collections::IVector<hstring> SupportedFileTypes() const;
};

template <typename D>
struct WINRT_EBO impl_IShareOperation
{
    Windows::ApplicationModel::DataTransfer::DataPackageView Data() const;
    hstring QuickLinkId() const;
    void RemoveThisQuickLink() const;
    void ReportStarted() const;
    void ReportDataRetrieved() const;
    void ReportSubmittedBackgroundTask() const;
    void ReportCompleted(const Windows::ApplicationModel::DataTransfer::ShareTarget::QuickLink & quicklink) const;
    void ReportCompleted() const;
    void ReportError(hstring_ref value) const;
};

template <typename D>
struct WINRT_EBO impl_IShareOperation2
{
    void DismissUI() const;
};

struct IQuickLink :
    Windows::IInspectable,
    impl::consume<IQuickLink>
{
    IQuickLink(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IQuickLink>(m_ptr); }
};

struct IShareOperation :
    Windows::IInspectable,
    impl::consume<IShareOperation>
{
    IShareOperation(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IShareOperation>(m_ptr); }
};

struct IShareOperation2 :
    Windows::IInspectable,
    impl::consume<IShareOperation2>
{
    IShareOperation2(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IShareOperation2>(m_ptr); }
};

}

}


text:
THIS PROJECT IS NOW OFFICIALLY DEPRECATED
-----------------------------------------

Kalabox is now deprecated and will EOL sometime later in 2019.

Check out https://www.kalabox.io for information on how to migrate to either Lando or Pantheon Localdev

Pantheon on Kalabox
===================

**"Pantheon on Kalabox"** is a [Kalabox](http://kalabox.io) plugin that allows users to authenticate with their Pantheon account and then...

  1. Pull down sites they have spun up on their Pantheon dashboard.
  2. Achieve parity with the Pantheon environment locally, including access to power services like Solr and Redis.
  3. Push changes back up to their Pantheon site.
  4. Get Pantheon specific power tools such as Terminus, Drush and WP-CLI.

While **"Pantheon on Kalabox"** is an external Kalabox plugin we actually include it as part of the default Kalabox offering along with the [**"PHP on Kalabox"**](http://github.com/kalabox/kalabox-app-php) plugin.

**We highly recommend you read the main [Kalabox docs](http://docs.kalabox.io) before continuing.**

Getting Started
---------------

Your best bet to learn more about the various aspects of **"Pantheon on Kalabox"** is to check out [our documentation](http://pantheon.kalabox.io). Here are some good topics to get you started:

  * [Using the Kalabox CLI with Pantheon apps](http://pantheon.kalabox.io/en/stable/users/cli)
  * [Using the Kalabox GUI with Pantheon apps](http://pantheon.kalabox.io/en/stable/users/gui)
  * [The Pantheon Services & Environment](http://pantheon.kalabox.io/en/stable/users/services)
  * [The Pantheon tooling with which we ship](http://pantheon.kalabox.io/en/stable/users/tooling)

Support
-------

To get help...

  1. Make sure your question isn't answered in either the [core docs](http://support.kalabox.io/solution/categories), the [Pantheon app docs](http://pantheon.kalabox.io/), or the [PHP docs](http://php.kalabox.io/).
  2. Thoroughly search the [Github issue queue](https://github.com/kalabox/kalabox/issues) for any existing issues similar to yours.
  3. If all else fails, create an issue and follow the pre-populated guidelines and the [CONTRIB.MD](https://raw.githubusercontent.com/kalabox/kalabox-app-pantheon/v0.13/CONTRIBUTING.md) as best as possible.

Some examples of good issue reporting:

  - [https://github.com/kalabox/kalabox/issues/565](https://github.com/kalabox/kalabox/issues/565)
  - [https://github.com/kalabox/kalabox/issues/557](https://github.com/kalabox/kalabox/issues/557)

Kalabox is an open-source project. As such, support is a community-lead effort. Please help us keep issue noise to a minimum and be patient with the Kalabox community members who donate time to help out.

**If you are interested in dedicated support or customizations, check out [our support offerings.](http://kalabox.io/support)**

Development Releases
--------------------

**Not For General Use**
These builds are intended primarily for developers working on Kalabox and those who are experienced enough with the Kalabox framework and want to test apps before they are released. Most users won't be interested.

We produce development releases for every commit merged into our `v0.13` branch. **These releases are not officially supported** but we have made them available to intrepid users who want to try the bleeding edge or are interested in trying out a recent bug fix before an official release is rolled.

  * **Windows** - [http://apps.kalabox.io/kalabox-app-pantheon-latest.zip](http://apps.kalabox.io/kalabox-app-pantheon-latest.zip)
  * **POSIX** - [http://apps.kalabox.io/kalabox-app-pantheon-latest.tar.gz](http://apps.kalabox.io/kalabox-app-pantheon-latest.tar.gz)

**NOTE:** Releases can take some time to build after we merge in commits. For that reason you might want to check the time of the last commit and if it is within a few hours you might want to hold off a bit before trying the new latest release.

You can also easily verify that the release you downloaded matches the latest commit. All development releases look something like `0.13.0-alpha.1-4-g63b0db0`. This means 4 commits after the `0.13.0-alpha.1` tag and with commit hash `g63b0db0`. You should make sure this commit hash matches or comes before the latest commit.

Check out for help on [installing Kalabox plugins manually](http://docs.kalabox.io/en/stable/developers/plugins)

Other Resources
---------------

* [Mountain climbing advice](https://www.youtube.com/watch?v=tkBVDh7my9Q)


text:
package com.webpagebytes.wpbsample.controllers;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.fop.apps.MimeConstants;

import com.webpagebytes.cms.WPBContentProvider;
import com.webpagebytes.cms.WPBForward;
import com.webpagebytes.cms.WPBModel;
import com.webpagebytes.cms.exception.WPBException;
import com.webpagebytes.wpbsample.data.DepositWithdrawal;
import com.webpagebytes.wpbsample.data.Session;
import com.webpagebytes.wpbsample.data.Transaction;
import com.webpagebytes.wpbsample.utility.SampleFopService;

public class ReportAllController extends GenericController {

	public void initialize(WPBContentProvider contentProvider) {
		// TODO Auto-generated method stub
		super.initialize(contentProvider);
	}

	public void handleRequest(HttpServletRequest request,
			HttpServletResponse response, WPBModel model, WPBForward forward) throws WPBException {
		Session session = getSession(request, response);
		if (false == handleAuthentication(request, response, model, forward, session))
		{
			return;
		}
		Integer user_id = (Integer) session.getSessionMap().get(SESSION_LOGIN_USERID);

		OutputStream os = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream(10000);
		ByteArrayInputStream bis = null;
		try
		{
			Date date = new Date(0);
			List<Transaction> transactions = database.getTransactionsForUser(user_id, date, 1, MAX_RECORDS);
			long sumTransactions = 0;
			for(Transaction t: transactions)
			{
				sumTransactions += t.getAmount();
			}
			model.getCmsApplicationModel().put("sumTransactions", sumTransactions);

			List<DepositWithdrawal> deposits = database.getDepositsWithdrawalsForUser(user_id, DepositWithdrawal.OperationType.DEPOSIT, date, 1, MAX_RECORDS);
			long sumDeposits = 0;
			for(DepositWithdrawal d: deposits)
			{
				sumDeposits += d.getAmount();
			}
			model.getCmsApplicationModel().put("sumDeposits", sumDeposits);

			List<DepositWithdrawal> withdrawals = database.getDepositsWithdrawalsForUser(user_id, DepositWithdrawal.OperationType.WITHDRAWAL, date, 1, MAX_RECORDS);
			long sumWithdrawals = 0;
			for(DepositWithdrawal w: withdrawals)
			{
				sumWithdrawals += w.getAmount();
			}
			model.getCmsApplicationModel().put("sumWithdrawals", sumWithdrawals);
			long maxValue = sumTransactions;
			if (maxValue < sumDeposits)
			{
				maxValue = sumDeposits;
			}
			if (maxValue < sumWithdrawals)
			{
				maxValue = sumWithdrawals;
			}
			model.getCmsApplicationModel().put("maxValue", maxValue);

			response.setContentType("image/png");

			model.getCmsApplicationModel().put("user_id", user_id);

			SampleFopService fopService = SampleFopService.getInstance();
			String fopPageGuid = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY).get("pageGuid");;
			contentProvider.writePageContent(fopPageGuid, model, baos);
			bis = new ByteArrayInputStream(baos.toByteArray());
			baos.close();
			os = response.getOutputStream();
			fopService.getContent(bis, MimeConstants.MIME_PNG, os);

		}
		catch (Exception e)
		{
			e.printStackTrace(System.out);
		}
		finally
		{
			if (os != null)
			{
				IOUtils.closeQuietly(os);
			}
			if (baos != null)
			{
				IOUtils.closeQuietly(baos);
			}
			if (bis != null)
			{
				IOUtils.closeQuietly(bis);
			}
		}

	}

}


text:
require_relative "./websocket"
require "set"
require "uri"
require "net/http"
require "rubygems"
require "json"

class Bot
   attr_accessor :debug, :speak

   def initialize(auth, userId, roomId)
      @auth          = auth
      @userId        = userId
      @roomId        = roomId
      @debug         = false
      @callback      = nil
      @currentDjId   = nil
      @currentSongId = nil
      @lastHeartbeat = Time.now
      @lastActivity  = Time.now
      @clientId      = '%s-0.59633534294921572' % Time.now.to_i
      @_msgId        = 0
      @_cmds         = []
      @_isConnected  = false
      @fanOf         = Set.new
      @currentStatus = "available"
      @signals       = {}

      connect(@roomId)
   end

   def connect(roomId)
      uri = URI.parse("http://turntable.fm:80/api/room.which_chatserver?roomid=%s" % @roomId)
      response = Net::HTTP.get_response(uri)
      data = JSON.parse(response.body)
      host, port = data[1]["chatserver"][0], data[1]["chatserver"][1]
      url = "ws://%s:%s/socket.io/websocket" % [host, port]
      @ws = WebSocket.new(url)
      if @roomId
         def clb
            rq = { "api" => "room.register", "roomid" => @roomId }
            _send(rq, nil)
         end
         @callback = method(:clb)
      end
   end

   def setTmpSong(data)
      @tmpSong = { "command" => "endsong", "room" => data["room"], "success" => true }
   end

   def on_message(msg)
      heartbeat_rgx = /~m~[0-9]+~m~(~h~[0-9]+)/
      if heartbeat_rgx.match(msg)
         _heartbeat(heartbeat_rgx.match(msg)[1])
         @lastHeartbeat = Time.now
         updatePresence()
         return
      end

      if @debug
         puts "> %s" % msg
      end

      if msg == "~m~10~m~no_session"
         def clb(obj)
            if not @isConnected
               def fanof(data)
                  @fanOf |= Set.new(data["fanof"])
                  updatePresence()
                  Thread.new do
                     updatePresence()
                     sleep 1000
                  end
                  emit("ready")
               end
               getFanOf(method(:fanof))
            end
            @callback.call()
            @isConnected = true
         end
         userAuthenticate(method(:clb))
         return
      end

      @lastActivity = Time.now
      len_rgx = /~m~([0-9]+)~m~/
      len = len_rgx.match(msg)[1]
      obj = JSON.parse(msg[msg.index("{"), msg.length])
      for id, rq, clb in @_cmds
         if id == obj["msgid"]
            if rq["api"] == "room.info"
               if obj["success"]
                  currentDj = obj["room"]["metadata"]["current_dj"]
                  currentSong = obj["room"]["metadata"]["current_song"]
                  if currentDj
                     @currentDj = currentDj
                  end
                  if currentSong
                     @currentSongId = currentSong["_id"]
                  end
               end

            elsif rq["api"] == "room.register"
               if obj["success"]
                  @roomId = rq["roomid"]
                  def info_clb(data)
                     setTmpSong(data)
                     emit("roomChanged", data)
                  end
                  roomInfo(method(:info_clb))
               else
                  emit("roomChanged", obj)
               end
               clb = nil

            elsif rq["api"] == "room.deregister"
               if obj["success"]
                  @roomId = nil
               end
            end

            if clb
               clb.call(obj)
            end

            @_cmds.delete([id, rq, clb])
            break
         end
      end

      if obj["command"] == "registered"
         emit("registered", obj)
      elsif obj["command"] == "deregistered"
         emit("deregistered", obj)
      elsif obj["command"] == "speak"
         emit("speak", obj)
      elsif obj["command"] == "pmmed"
         emit("pmmed", obj)
      elsif obj["command"] == "nosong"
         @currentDjId = nil
         @currentSongId = nil
         emit("endsong", @tmpSong)
         emit("nosong", obj)
      elsif obj["command"] == "newsong"
         if @currentSongId
            emit("endsong", @tmpSong)
         end
         @currentDjId = obj["room"]["metadata"]["current_dj"]
         @currentSongId = obj["room"]["metadata"]["current_song"]["_id"]
         setTmpSong(obj)
         emit("newsong", obj)
      elsif obj["command"] == "update_votes"
         if @tmpSong
            @tmpSong["room"]['metadata']['upvotes']   = obj['room']['metadata']['upvotes']
            @tmpSong['room']['metadata']['downvotes'] = obj['room']['metadata']['downvotes']
            @tmpSong['room']['metadata']['listeners'] = obj['room']['metadata']['listeners']
         end
         emit("update_votes", obj)
      elsif obj["command"] == "booted_user"
         emit('booted_user', obj)
      elsif obj["command"] == "update_user"
         emit('update_user', obj)
      elsif obj["command"] == "add_dj"
         emit('add_dj', obj)
      elsif obj["command"] == "rem_dj"
         emit('rem_dj', obj)
      elsif obj["command"] == "new_moderator"
         emit('new_moderator', obj)
      elsif obj["command"] == "rem_moderator"
         emit('rem_moderator', obj)
      elsif obj["command"] == "snagged"
         emit('snagged', obj)
      end
   end

   def _heartbeat(msg)
      @ws.send('~m~%s~m~%s' % [msg.length, msg])
      @_msgId += 1
   end

   def _send(rq, callback=nil)
      rq["msgid"] = @_msgId
      rq["clientid"] = @clientId
      if not rq["userid"]
         rq["userid"] = @userId
      end
      rq["userauth"] = @auth

      msg = JSON.generate(rq)

      if @debug
         puts "< %s" % msg
      end

      @ws.send('~m~%s~m~%s' % [msg.length, msg])
      @_cmds.push([@_msgId, rq, callback])
      @_msgId += 1
   end

   def roomNow(callback=nil)
      rq = { "api" => "room.now" }
      _send(rq, callback)
   end

   def updatePresence(callback=nil)
      rq = { "api" => "presence.update", "status" => @currentStatus }
      _send(rq, callback)
   end

   def listRooms(skip=nil, callback=nil)
      if not skip
         skip = 0
      end
      rq = { "api" => "room.list_rooms", "skip" => skip }
      _sned(rq, callback)
   end

   def directoryGraph(callback=nil)
      rq = { "api" => "room.directory_graph" }
      _send(rq, callback)
   end

   # TODO
   def stalk(*args)
   end

   def getFavorites(callback=nil)
      rq = { "api" => "room.get_favorites" }
      _send(rq, callback)
   end

   def addFavorite(roomId, callback=nil)
      rq = { "api" => "room.add_favorite", "roomid" => roomId }
      _send(rq, callback)
   end

   def remFavorite(roomId, callback=nil)
      rq = { "api" => "room.rem_favorite", "roomid" => roomId }
      _send(rq, callback)
   end

   # TODO
   def roomRegister(callback=nil)
   end

   def roomDeregister(callback=nil)
      rq = { "api" => "room.deregister", "roomid" => @roomId }
      _send(rq, callback)
   end

   def roomInfo(*args)
      rq = { "api" => "room.info", "roomid" => @roomId }
      callback = args[0]
      _send(rq, callback)
   end

   def speak(msg, callback=nil)
      rq = { "api" => "room.speak", "roomid" => @roomId, "text" => msg.to_s }
      _send(rq, callback)
   end

   def pm(msg, userid, callback=nil)
      rq = { "api" => "pm.send", "receiverid" => userid, "text" => msg.to_s }
      _send(rq, callback)
   end

   def pmHistory(userid, callback=nil)
      rq = { "api" => "pm.history", "receiverid" => userid }
      _send(rq, callback)
   end

   def bootUser(userId, reason="", callback=nil)
      rq = { "api" => "room.boot_user", "roomid" => @roomId, "target_userid" => userId, "reason" => reason }
      _send(rq, callback)
   end

   def boot(userId, reason="", callback=nil)
      bootUser(userId, reason, callback)
   end

   def addModerator(userId, callback=nil)
      rq = { "api" => "room.add_moderator", "roomid" => @roomId, "target_userid" => userId }
      _send(rq, callback)
   end

   def remModerator(userId, callback=nil)
      rq = { "api" => "room.rem_moderator", "roomid" => @roomId, "target_userid" => userId }
      _send(rq, callback)
   end

   def addDj(callback=nil)
      rq = { "api" => "room.add_dj", "roomid" => @roomId }
      _send(rq, callback)
   end

   def remDj(userId, callback=nil)
      rq = { "api" => "room.rem_dj", "roomid" => @roomId, "djid" => userId}
      _send(rq, callback)
   end

   def stopSong(callback=nil)
      rq = { "api" => "room.stop_song", "roomid" => @roomId }
      _send(rq, callback)
   end

   def skip(callback=nil)
      stopSong(callback)
   end

   def snag(callback=nil)
      sh = Digest::SHA1.hexdigest(Random.rand.to_s)
      fh = Digest::SHA1.hexdigest(Random.rand.to_s)
      i = [@userid, @currentDjId, @currentSongId, @roomId, 'queue', 'board', false, false, sh]
      vh = Digest::SHA1.hexdigest(i.join('/'))
      rq = {
         "api"      => 'snag.add',
         "djid"     => @currentDjId,
         "songid"   => @currentSongId,
         "roomid"   => @roomId,
         "site"     => 'queue',
         "location" => 'board',
         "in_queue" => false,
         "blocked"  => false,
         "vh"       => vh,
         "sh"       => sh,
         "fh"       => fh
      }
      _send(rq, callback)
   end

   def vote(direction = "up", callback = nil)
    vh  = Digest::SHA1.hexdigest(@roomId + direction + @currentSongId)
    th  = Digest::SHA1.hexdigest(Random.rand.to_s)
    ph  = Digest::SHA1.hexdigest(Random.rand.to_s)
    rq  = { "api" => 'room.vote', "roomid" => @roomId, "val" => direction, "vh" => vh, "th" => th, "ph" => ph }
    puts rq
    _send(rq, callback)
   end

   def bop
     vote
   end

   def userAuthenticate(callback)
      rq = { "api" => "user.authenticate" }
      _send(rq, callback)
   end

   def userInfo(callback=nil)
      rq = { "api" => "user.info" }
      _send(rq, callback)
   end

   def getFanOf(callback=nil)
      rq = { "api" => "user.get_fan_of" }
      _send(rq, callback)
   end

   def getFans(callback=nil)
      rq = { "api" => "user.get_fans" }
      _send(rq, callback)
   end

   def getUserId(username, callback=nil)
      rq = { "api" => "user.get_id", "name" => username }
      _send(rq, callback)
   end

   def getStickers(callback=nil)
      rq = { "api" => "sticker.get" }
      _send(rq, callback)
   end

   def getStickerPlacements(userid, callback=nil)
      rq = { "api" => "sticker.get_placements", userid: userid }
      _send(rq, callback)
   end

   def getProfile(callback=nil)
      rq = { "api" => 'user.get_profile'}
      _send(rq, callback)
   end

   # Modify a user's profile
   #
   # @param profile [Hash] The profile changes to apply
   # @options profile [Hash] "name" User's name
   # @options profile [Hash] "twitter" User's twitter account
   # @options profile [Hash] "facebook" User's facebook account
   # @options profile [Hash] "website" User's homepage
   # @options profile [Hash] "about" User's about field
   # @options profile [Hash] "topartists" User's top artists
   # @options profile [Hash] "hangout" Room in which user usually hangs out in
   def modifyProfile(profile, callback)
      rq = {"api" => 'user.modify_profile'}
      rq.merge! profile
      _send(rq, callback)
   end

   def modifyLaptop(laptop="linux", callback=nil)
      rq = { "api" => "user.modify", "laptop" => laptop }
      _send(rq, callback)
   end

   def modifyName(name, callback=nil)
      rq = { "api" => "user.modify", "name" => name }
      _send(rq, callback)
   end

   def setAvatar(avatarId, callback=nil)
      rq = { "api" => "user.set_avatar", "avatarid" => avatarId }
      _send(rq, callback)
   end

   def becomeFan(userId, callback=nil)
      rq = { "api" => "user.become_fan", "djid" => userId }
      _send(rq, callback)
   end

   def removeFan(userId, callback=nil)
      rq = { "api" => "user.remove_fan", "djid" => userId }
      _send(rq, callback)
   end

   # TODO
   def playlistAll(callback=nil)

   end

   # TODO
   def playlistAdd(callback=nil)

   end

   # TODO
   def playlistRemove(callback=nil)

   end

   # TODO
   def playlistReorder(callback=nil)

   end

   def setStatus(st, callback)
      @currentStatus = st
      updatePresence()
      if callback
         callback({ "success" => true })
      end
   end

   def emit(signal, data=nil)
      callbacks = @signals[signal]
      callbacks = [] if not callbacks
      for clb in callbacks
         clb.call(data)
      end
   end

   def on(signal, callback)
      if not @signals[signal]
         @signals[signal] = []
      end
      @signals[signal].push(callback)
   end

   def start
      while data = @ws.receive()
         on_message(data)
      end
   end
end


text:
import * as nodemailer from 'nodemailer';
import * as Promise from 'bluebird';
import { mail } from '../settings';
var debug = require('debug')('yuedun:message');

export default class Message {
    mailTo: string;
    subject: string;
    text: string;
    content: string;
    /**
     * Creates an instance of Message.
     * @param {string} mailTo
     * @param {string} subject
     * @param {string} [html] html版本的内容
     * @param {string} [text] 普通文本版本的内容
     * @memberof Message
     */
    constructor(mailTo: string, subject: string, html: string, text: string) {
        this.mailTo = mailTo;
        this.subject = subject;
        this.text = text;
        this.content = html;
    }

    send() {
        // create reusable transporter object using the default SMTP transport
        var transporter = nodemailer.createTransport({
            service: '163',
            // host: 'smtp.gmail.com',
            // port: 465,
            // secure: true, // use SSL
            auth: {
                user: mail.from,
                pass: mail.pass
            }
        });

        // setup e-mail data with unicode symbols
        var mailOptions = {
            from: mail.from, // sender address
            to: this.mailTo, // list of receivers
            subject: this.subject, // Subject line
            text: this.text, // plaintext body
            html: this.content// html body
        };
        return new Promise((resolve, reject) => {
            transporter.verify(function (error: any, success: any) {
                if (error) {
                    reject(error);
                } else {
                    // send mail with defined transport object
                    transporter.sendMail(mailOptions, function (error: any, info: any) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(info);
                        }
                    });
                }
            });
        })
    }
}


text:
namespace TC.Unity.Composition.UnitTests.Dependencies
{
    public class SomeArgumentType
    {
        public string SomeValue { get; set; }
    }
}


text:
Rubyists test. It is oft considered a virtue. But why? Testing does more than prove that software
works. There is a great amount of theory that has gone into it, and hundreds of books have been
written on the topic with opinions on the matter usually strong.

What does testing do to you as a programmer? How does it change your habits? If you are doing it
right, it has one obvious change:

#### You are thinking ahead, and in a complete manner.

The benefits of this are obvious. How about we start off by making a very simple failing test.

```BASH
mkdir some_dir
cd some_dir
mkdir spec
editor spec/my_first_spec.rb
```

Now, we can write a simple test. We will start at a very basic level.

```RUBY
describe Bob do
  let(:bob) { Bob.new }

  it "can tell you hes wearing pants" do
    expect(bob.pants?).to eq true
  end
end
```

and now, we can save and run our spec

`rspec spec/my_first_spec.rb`

but we do not quite get a failure yet:

```BASH
Press ENTER or type command to continue
/home/bobby/ruby_tutorial-ocr/some_dir/my_first_spec.rb:1:in <top (required)>: uninitialized constant Bob (NameError)
```

However, we can solve this. we need to  make a few changes.

`editor spec/my_first_spec.rb`

```RUBY
require './lib/bob'
...
```

If we add this to the top we can now do this:

```BASH
mkdir lib
editor lib/bob.rb
```

and fix it by creating a class `Bob`

```RUBY
class Bob

end

```

and now when we run our spec again,

`rspec spec/my_first_spec.rb`

we get some new output:

```BASH
F

Failures:

  1) Bob can tell you hes wearing pants
       Failure/Error: expect(Bob.pants?).to eq true
            NoMethodError:
                   undefined method pants? for Bob:Class
                        # ./spec/my_first_spec.rb:5:in `block (2 levels) in <top (required)>

                        Finished in 0.00049 seconds (files took 1.41 seconds to load)
                        1 example, 1 failure

                        Failed examples:

                        rspec ./spec/my_first_spec.rb:4 # Bob can tell you hes wearing pants

```

Okay, so now we can fix this to make it passing.

`editor lib/bob.rb`

```RUBY
class Bob
  def pants?
    true
  end
end

```

and we ought to be passing now!

```
bobby@devbox:~/ruby_tutorial-ocr/some_dir$ rspec spec/
.

Finished in 0.02111 seconds (files took 0.11633 seconds to load)
1 example, 0 failures

```

Boom! Passing tests. See, the glory of this is if we have good test coverage, we can change many parts
and know immediately if we have broken anything. We will be writing tests for all the work we do from
here onwards.

#### [Shelr Screencast With Audio](/shelr/1426787266/)

#### [Going Deeper](/introduction/bot.md)


text:
package com.sebastian_daschner.jaxrs_analyzer.analysis.classes;

import com.sebastian_daschner.jaxrs_analyzer.analysis.classes.annotation.DefaultValueAnnotationVisitor;
import com.sebastian_daschner.jaxrs_analyzer.analysis.classes.annotation.ParamAnnotationVisitor;
import com.sebastian_daschner.jaxrs_analyzer.model.Types;
import com.sebastian_daschner.jaxrs_analyzer.model.rest.MethodParameter;
import com.sebastian_daschner.jaxrs_analyzer.model.rest.ParameterType;
import com.sebastian_daschner.jaxrs_analyzer.model.rest.TypeIdentifier;
import com.sebastian_daschner.jaxrs_analyzer.model.results.ClassResult;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;

/**
 * @author Sebastian Daschner
 */
class JAXRSFieldVisitor extends FieldVisitor {

    private final ClassResult classResult;
    private final String signature;
    private MethodParameter parameter;

    JAXRSFieldVisitor(final ClassResult classResult, final String desc, final String signature) {
        super(Opcodes.ASM5);
        this.classResult = classResult;
        this.signature = signature == null ? desc : signature;
    }

    @Override
    public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
        switch (desc) {
            case Types.PATH_PARAM:
                return paramAnnotationVisitor(ParameterType.PATH);
            case Types.QUERY_PARAM:
                return paramAnnotationVisitor(ParameterType.QUERY);
            case Types.HEADER_PARAM:
                return paramAnnotationVisitor(ParameterType.HEADER);
            case Types.FORM_PARAM:
                return paramAnnotationVisitor(ParameterType.FORM);
            case Types.COOKIE_PARAM:
                return paramAnnotationVisitor(ParameterType.COOKIE);
            case Types.MATRIX_PARAM:
                return paramAnnotationVisitor(ParameterType.MATRIX);
            case Types.DEFAULT_VALUE:
                return defaultAnnotationVisitor();
            default:
                return null;
        }
    }

    private AnnotationVisitor paramAnnotationVisitor(final ParameterType parameterType) {
        if (parameter == null)
            parameter = new MethodParameter(TypeIdentifier.ofType(signature), parameterType);
        else
            parameter.setParameterType(parameterType);
        return new ParamAnnotationVisitor(parameter);
    }

    private AnnotationVisitor defaultAnnotationVisitor() {
        if (parameter == null)
            parameter = new MethodParameter(TypeIdentifier.ofType(signature));
        return new DefaultValueAnnotationVisitor(parameter);
    }

    @Override
    public void visitEnd() {
        if (parameter != null)
            classResult.getClassFields().add(parameter);
    }

}


text:
"""
test_kpm
----------------------------------

Tests for `kpm` module.
"""

import unittest

class TestKpm(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_000_something(self):
        pass

if __name__ == '__main__':
    import sys
    sys.exit(unittest.main())


text:
package com.epam.dlab.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects.ToStringHelper;

public class ResourceEnvBaseDTO<T extends ResourceEnvBaseDTO<?>> extends ResourceSysBaseDTO<T> {
    @JsonProperty("exploratory_name")
    private String exploratoryName;
    @JsonProperty("application")
    private String applicationName;

    @SuppressWarnings("unchecked")
	private final T self = (T)this;

    public String getExploratoryName() {
        return exploratoryName;
    }

    public void setExploratoryName(String exploratoryName) {
        this.exploratoryName = exploratoryName;
    }

    public T withExploratoryName(String exploratoryName) {
        setExploratoryName(exploratoryName);
        return self;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public T withApplicationName(String applicationName) {
        setApplicationName(applicationName);
        return self;
    }

    @Override
    public ToStringHelper toStringHelper(Object self) {
    	return super.toStringHelper(self)
    	        .add("applicationName", applicationName)
    	        .add("exploratoryName", exploratoryName);
    }

    @Override
    public String toString() {
    	return toStringHelper(this).toString();
    }
}


text:
'use strict';

var config = {
	site : 'http://www.some.com',
	domains : {
		some : 'some.com'
	},
	el : {
		productList : $('#product_list'),
		productTemplate : $('#productTemplate'),
		loader : $('#loader'),
		err : $("#err")
	},
	urls : {
		favouriteProducts : 'http://127.0.0.1/ajax/favorite_products'
	},
	errors : {
		400 : '400',
		500 : '500',
		timeout : 'timeout'
	},
	errorMessages : {
		serverConnectionFailed : 'Sunucuya bağlanılamıyor...',/*400*/
		internalServerError : 'Sunucu taraflı bir hata oluştu...',/*500*/
		timeout : 'Sayfa zaman aşımına uğradı. Lütfen tekrar deneyiniz...',
		unidentifiedError : 'Beklenmeyen bir hata oluştu. Lütfen tekrar deneyiniz.'
	},
	stringBoundry : 16,
	stringExtension : '...',
	json : {
		shortDesc : 'short_description'
	}
}


text:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>

<body>
<script src="../../node-xmpp-browser.js"></script>
<script src="chat.js"></script>
</body> </html>


text:
#ifndef DUEL6_RENDERER_GL4_GL4PROGRAM_H
#define DUEL6_RENDERER_GL4_GL4PROGRAM_H

#include "../../Type.h"
#include "../../math/Matrix.h"
#include "GL4Types.h"
#include "GL4Shader.h"

namespace Duel6 {
    class GL4Program {
    private:
        const GL4Shader &vertexShader;
        const GL4Shader &fragmentShader;
        GLuint id;

    public:
        GL4Program(const GL4Shader &vertexShader, const GL4Shader &fragmentShader);
        ~GL4Program();

        void bind();
        GLint uniformLocation(const GLchar *name);

        void setUniform(const GLchar *name, Int32 value);
        void setUniform(const GLchar *name, Float32 value);
        void setUniform(const GLchar *name, Float32 value[4]);
        void setUniform(const GLchar *name, const Matrix &value);

        GLuint getId() const;

        const GL4Shader &getVertexShader() const;
        const GL4Shader &getFragmentShader() const;
    };
}

#endif


text:
<!DOCTYPE html>
<title>CS2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="/build/style.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">


text:
(function ( $ ) {
	window.InlineShortcodeView_vc_masonry_grid = window.InlineShortcodeView_vc_basic_grid.extend();
})( window.jQuery );


text:
using dbqf.Configuration;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace dbqf.Sql.Configuration
{
    /// <summary>
    /// Represents a view of the database to be used for user querying.  Must be used with ISqlSubject types.
    /// </summary>
    public class MatrixConfiguration : IMatrixConfiguration
    {
        protected List<ISqlSubject> _subjects;
        protected Dictionary<ISqlSubject, Dictionary<ISqlSubject, MatrixNode>> _matrix;

        public MatrixConfiguration()
        {
            _subjects = new List<ISqlSubject>();
            _matrix = new Dictionary<ISqlSubject, Dictionary<ISqlSubject, MatrixNode>>();
        }

        public ISubject this[string displayName]
        {
            get
            {
                return _subjects.Find((s) => { return s.DisplayName.Equals(displayName); });
            }
        }

        public MatrixNode this[ISqlSubject from, ISqlSubject to]
        {
            get { return _matrix[from][to]; }
        }

        private void TypeCheck(ISubject item)
        {
            if (!(item is ISqlSubject))
                throw new ArgumentException("Subjects must be of type ISqlSubject.");
        }

        /// <summary>
        /// Fluently adds a new subject to the configuration.
        /// </summary>
        /// <param name="subject"></param>
        /// <returns></returns>
        public MatrixConfiguration Subject(ISqlSubject subject)
        {
            Add(subject);
            return this;
        }

        public MatrixConfiguration Matrix(ISqlSubject from, ISqlSubject to, string sql)
        {
            return Matrix(from, to, sql, null);
        }

        public MatrixConfiguration Matrix(ISqlSubject from, ISqlSubject to, string sql, string tooltip)
        {
            var node = _matrix[from][to];
            node.Query = sql;
            node.ToolTip = tooltip;

            return this;
        }

        protected virtual void AddToMatrix(ISqlSubject subject)
        {
            _matrix.Add(subject, new Dictionary<ISqlSubject, MatrixNode>());
            foreach (var s in _subjects)
            {
                _matrix[subject].Add(s, new MatrixNode());

                if (!_matrix[s].ContainsKey(subject))
                    _matrix[s].Add(subject, new MatrixNode());
            }
        }

        protected virtual void RemoveFromMatrix(ISqlSubject subject)
        {
            _matrix.Remove(subject);
            foreach (var s in _subjects)
            {
                if (_matrix[s].ContainsKey(subject))
                    _matrix[s].Remove(subject);
            }
        }

        #region IList Members

        public int IndexOf(ISubject item)
        {
            TypeCheck(item);
            return _subjects.IndexOf((ISqlSubject)item);
        }

        public void Insert(int index, ISubject item)
        {
            TypeCheck(item);
            _subjects.Insert(index, (ISqlSubject)item);
            AddToMatrix((ISqlSubject)item);
        }

        public void RemoveAt(int index)
        {
            RemoveFromMatrix(_subjects[index]);
            _subjects.RemoveAt(index);
        }

        public ISubject this[int index]
        {
            get
            {
                return _subjects[index];
            }
            set
            {
                TypeCheck(value);
                _subjects[index] = (ISqlSubject)value;
            }
        }

        public void Add(ISubject item)
        {
            TypeCheck(item);
            _subjects.Add((ISqlSubject)item);
            AddToMatrix((ISqlSubject)item);
            item.Configuration = this;
        }

        public void Clear()
        {
            _subjects.Clear();
            _matrix.Clear();
        }

        public bool Contains(ISubject item)
        {
            if (item is ISqlSubject)
                return _subjects.Contains((ISqlSubject)item);
            return false;
        }

        public void CopyTo(ISubject[] array, int arrayIndex)
        {
            for (int i = 0; arrayIndex + i < array.Length && i < _subjects.Count; i++)
                array[arrayIndex + i] = _subjects[i];
        }

        public int Count
        {
            get { return _subjects.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(ISubject item)
        {
            if (item is ISqlSubject && _subjects.Remove((ISqlSubject)item))
            {
                RemoveFromMatrix((ISqlSubject)item);
                return true;
            }

            return false;
        }

        public IEnumerator<ISubject> GetEnumerator()
        {
            foreach (var s in _subjects)
                yield return s;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}


text:
'use strict';

describe('infoLog', () => {
  const infoLog = require('../infoLog');

  it('logs messages to the console', () => {
    console.log = jest.fn();

    infoLog('This is a log message');

    expect(console.log).toHaveBeenCalledWith('This is a log message');
  });

  it('logs messages with multiple arguments to the console', () => {
    console.log = jest.fn();

    const data = 'log';
    infoLog('This is a', data, 'message');

    expect(console.log).toHaveBeenCalledWith('This is a', 'log', 'message');
  });
});


text:
import java.util.Stack;

import javafx.scene.shape.Ellipse;

public class ReverseStack{

    public static void main(String []args){

        Stack<Integer> s = new Stack<Integer>();
        s.push(4);
        s.push(3);
        s.push(2);
        s.push(1);
        printStack(s);
        System.out.println("---------------");
        sortStack(s);
        printStack(s);
    }

    public static void printStack(Stack<Integer> s) {
        for (Integer i : s) {
            System.out.println(i);
        }
    }

    public static void reverseStack(Stack<Integer> stack) {
        if (!stack.isEmpty()) {
            int temp = stack.pop();
            reverseStack(stack);
            insertIntoBottom(stack, temp);
        }
    }

    public static void insertIntoBottom(Stack<Integer> stack, int n) {
        if(stack.isEmpty()) {
            stack.push(n);
        }
        else {
            int temp = stack.pop();
            insertIntoBottom(stack, n);
            stack.push(temp);
        }
    }

    public static void sortStack(Stack<Integer> stack) {
        if(!stack.isEmpty()) {
            int temp = stack.pop();
            sortStack(stack);
            insertSorted(stack, temp);
        }
    }

    public static void insertSorted(Stack<Integer> stack, int n) {
        if(stack.isEmpty() || n > stack.peek()) {
            stack.push(n);
        }
        else {
            int temp = stack.pop();
            insertSorted(stack, n);
            stack.push(temp);
        }
    }
}


text:
"use strict";

module.exports = {
    description: "Issue #103 - Validate async fails silently",
    options: {
        asyncTimeout: 500
    },
    schema: {
        required: ["recType", "luValue"],
        properties: {
            luValue: {
                type: "string"
            },
            useAsIs: {
                type: "integer"
            },
            valueText: {
                type: "string"
            },
            sequence: {
                type: "integer",
                minimum: 0
            },
            description: {
                type: "string"
            },
            valueInt: {
                type: "integer"
            },
            recType: {
                type: "string",
                enum: []
            },
            recProps: {
                type: "object",
                properties: {},
                additionalProperties: false
            },
            control: {
                "$ref": "control"
            }
        },
        additionalProperties: false,
        type: "object",
        title: "lookup schema for bankCodeType"
    },
    tests: [
        {
            async: false,
            description: "should fail with correct error - sync",
            validateSchemaOnly: true,
            valid: false,
            after: function (errs) {
                expect(errs.length).toBe(1);
            }
        },
        {
            async: true,
            description: "should fail with correct error - async",
            validateSchemaOnly: true,
            valid: false,
            after: function (errs) {
                expect(errs.length).toBe(1);
            }
        }
    ]
};


text:
.icon-home{
	background:url('/any/img/shop.png') no-repeat center left;
	float:left;
	display:block;
	width:35px;
	height:30px;
}
.icon-basket{
	background:url('/any/img/basket.png') no-repeat center center;
}
.icon-location{
	background:url('/any/img/location.png') no-repeat center left;
}
.icon-mail{
	background:url('/any/img/mail.png') no-repeat center left;
}
.icon-whois{
	background:url('/any/img/whois.png') no-repeat center left;
}
.socialmedia .fb{
        background-image:url('/any/img/fb.png');
}
.socialmedia .twitter{
	background-image:url('/any/img/tw.png');
}
.socialmedia .google{
	background-image:url('/any/img/gg.png');
}
.socialmedia .pint{
	background-image:url('/any/img/pin.png');
}
.menuicon:before{
	content:url('/any/img/menu.png');
	float:left;
	margin-right:10px;
}
.star-vote{
	background:url('/any/img/star-vote.png') no-repeat center center;
}
.star-empty{
	background:url('/any/img/star-empty.png') no-repeat center center;
}
.icon-visa{
	background:url('/any/img/visa.png') no-repeat center center transparent;
}
.icon-mastercart{
	background:url('/any/img/mastercard.png') no-repeat center center transparent;
}
.icon-amex{
	background:url('/any/img/amex.png') no-repeat center center transparent;
}
.icon-discover{
	background:url('/any/img/discover.png') no-repeat center center transparent;
}
.icon-paypal{
	background:url('/any/img/paypal.png') no-repeat center center transparent;
}
.icon-shipping{
	background:url('/any/img/shipping.png') no-repeat center center transparent;
}
.icon-basket-main{
	background:url('/any/img/basket-main.png') no-repeat center center;
}
.icon-profil{
	background:url('/any/img/small-profil.png') no-repeat center center;
}


text:
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>

	<title>DataView with Dynamic loading linked to DataStore</title>


text:
/**
 */
package br.ufc.great.catchml.catchML.impl;

import br.ufc.great.catchml.catchML.AbstractDeclaration;
import br.ufc.great.catchml.catchML.BINARYOPERATOR;
import br.ufc.great.catchml.catchML.CatchMLPackage;
import br.ufc.great.catchml.catchML.LogicExpression;
import br.ufc.great.catchml.catchML.MULTIPLEOPERATOR;
import br.ufc.great.catchml.catchML.TEMPORALOPERATOR;
import br.ufc.great.catchml.catchML.TEMPUNTILOPERATOR;

import java.util.Collection;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * An implementation of the model object 'Logic Expression'.
 *
 *

 * The following features are implemented:
 *

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getExpr Expr}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getValue Value}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getOpBin Op Bin}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getLeft Left}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getRight Right}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getOpMul Op Mul}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getArgs Args}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getOpTemp Op Temp}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getTemporal Temporal}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getOpTempUntil Op Temp Until}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getLeftExp Left Exp}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getRightExp Right Exp}

 *
{@link br.ufc.great.catchml.catchML.impl.LogicExpressionImpl#getOp Op}

 *

 *

 *
 * @generated
 */
public class LogicExpressionImpl extends MinimalEObjectImpl.Container implements LogicExpression
{
  /**
   * The cached value of the '{@link #getExpr() Expr}' containment reference.
   *
   *
   * @see #getExpr()
   * @generated
   * @ordered
   */
  protected LogicExpression expr;

  /**
   * The cached value of the '{@link #getValue() Value}' reference.
   *
   *
   * @see #getValue()
   * @generated
   * @ordered
   */
  protected AbstractDeclaration value;

  /**
   * The default value of the '{@link #getOpBin() Op Bin}' attribute.
   *
   *
   * @see #getOpBin()
   * @generated
   * @ordered
   */
  protected static final BINARYOPERATOR OP_BIN_EDEFAULT = BINARYOPERATOR.NOR;

  /**
   * The cached value of the '{@link #getOpBin() Op Bin}' attribute.
   *
   *
   * @see #getOpBin()
   * @generated
   * @ordered
   */
  protected BINARYOPERATOR opBin = OP_BIN_EDEFAULT;

  /**
   * The cached value of the '{@link #getLeft() Left}' containment reference.
   *
   *
   * @see #getLeft()
   * @generated
   * @ordered
   */
  protected LogicExpression left;

  /**
   * The cached value of the '{@link #getRight() Right}' containment reference.
   *
   *
   * @see #getRight()
   * @generated
   * @ordered
   */
  protected LogicExpression right;

  /**
   * The default value of the '{@link #getOpMul() Op Mul}' attribute.
   *
   *
   * @see #getOpMul()
   * @generated
   * @ordered
   */
  protected static final MULTIPLEOPERATOR OP_MUL_EDEFAULT = MULTIPLEOPERATOR.XOR;

  /**
   * The cached value of the '{@link #getOpMul() Op Mul}' attribute.
   *
   *
   * @see #getOpMul()
   * @generated
   * @ordered
   */
  protected MULTIPLEOPERATOR opMul = OP_MUL_EDEFAULT;

  /**
   * The cached value of the '{@link #getArgs() Args}' containment reference list.
   *
   *
   * @see #getArgs()
   * @generated
   * @ordered
   */
  protected EList<LogicExpression> args;

  /**
   * The default value of the '{@link #getOpTemp() Op Temp}' attribute.
   *
   *
   * @see #getOpTemp()
   * @generated
   * @ordered
   */
  protected static final TEMPORALOPERATOR OP_TEMP_EDEFAULT = TEMPORALOPERATOR.EX;

  /**
   * The cached value of the '{@link #getOpTemp() Op Temp}' attribute.
   *
   *
   * @see #getOpTemp()
   * @generated
   * @ordered
   */
  protected TEMPORALOPERATOR opTemp = OP_TEMP_EDEFAULT;

  /**
   * The cached value of the '{@link #getTemporal() Temporal}' containment reference.
   *
   *
   * @see #getTemporal()
   * @generated
   * @ordered
   */
  protected LogicExpression temporal;

  /**
   * The default value of the '{@link #getOpTempUntil() Op Temp Until}' attribute.
   *
   *
   * @see #getOpTempUntil()
   * @generated
   * @ordered
   */
  protected static final TEMPUNTILOPERATOR OP_TEMP_UNTIL_EDEFAULT = TEMPUNTILOPERATOR.E;

  /**
   * The cached value of the '{@link #getOpTempUntil() Op Temp Until}' attribute.
   *
   *
   * @see #getOpTempUntil()
   * @generated
   * @ordered
   */
  protected TEMPUNTILOPERATOR opTempUntil = OP_TEMP_UNTIL_EDEFAULT;

  /**
   * The cached value of the '{@link #getLeftExp() Left Exp}' containment reference.
   *
   *
   * @see #getLeftExp()
   * @generated
   * @ordered
   */
  protected LogicExpression leftExp;

  /**
   * The cached value of the '{@link #getRightExp() Right Exp}' containment reference.
   *
   *
   * @see #getRightExp()
   * @generated
   * @ordered
   */
  protected LogicExpression rightExp;

  /**
   * The default value of the '{@link #getOp() Op}' attribute.
   *
   *
   * @see #getOp()
   * @generated
   * @ordered
   */
  protected static final String OP_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getOp() Op}' attribute.
   *
   *
   * @see #getOp()
   * @generated
   * @ordered
   */
  protected String op = OP_EDEFAULT;

  /**
   *
   *
   * @generated
   */
  protected LogicExpressionImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return CatchMLPackage.Literals.LOGIC_EXPRESSION;
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getExpr()
  {
    return expr;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetExpr(LogicExpression newExpr, NotificationChain msgs)
  {
    LogicExpression oldExpr = expr;
    expr = newExpr;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__EXPR, oldExpr, newExpr);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setExpr(LogicExpression newExpr)
  {
    if (newExpr != expr)
    {
      NotificationChain msgs = null;
      if (expr != null)
        msgs = ((InternalEObject)expr).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__EXPR, null, msgs);
      if (newExpr != null)
        msgs = ((InternalEObject)newExpr).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__EXPR, null, msgs);
      msgs = basicSetExpr(newExpr, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__EXPR, newExpr, newExpr));
  }

  /**
   *
   *
   * @generated
   */
  public AbstractDeclaration getValue()
  {
    if (value != null && value.eIsProxy())
    {
      InternalEObject oldValue = (InternalEObject)value;
      value = (AbstractDeclaration)eResolveProxy(oldValue);
      if (value != oldValue)
      {
        if (eNotificationRequired())
          eNotify(new ENotificationImpl(this, Notification.RESOLVE, CatchMLPackage.LOGIC_EXPRESSION__VALUE, oldValue, value));
      }
    }
    return value;
  }

  /**
   *
   *
   * @generated
   */
  public AbstractDeclaration basicGetValue()
  {
    return value;
  }

  /**
   *
   *
   * @generated
   */
  public void setValue(AbstractDeclaration newValue)
  {
    AbstractDeclaration oldValue = value;
    value = newValue;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__VALUE, oldValue, value));
  }

  /**
   *
   *
   * @generated
   */
  public BINARYOPERATOR getOpBin()
  {
    return opBin;
  }

  /**
   *
   *
   * @generated
   */
  public void setOpBin(BINARYOPERATOR newOpBin)
  {
    BINARYOPERATOR oldOpBin = opBin;
    opBin = newOpBin == null ? OP_BIN_EDEFAULT : newOpBin;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__OP_BIN, oldOpBin, opBin));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getLeft()
  {
    return left;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetLeft(LogicExpression newLeft, NotificationChain msgs)
  {
    LogicExpression oldLeft = left;
    left = newLeft;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__LEFT, oldLeft, newLeft);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setLeft(LogicExpression newLeft)
  {
    if (newLeft != left)
    {
      NotificationChain msgs = null;
      if (left != null)
        msgs = ((InternalEObject)left).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__LEFT, null, msgs);
      if (newLeft != null)
        msgs = ((InternalEObject)newLeft).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__LEFT, null, msgs);
      msgs = basicSetLeft(newLeft, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__LEFT, newLeft, newLeft));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getRight()
  {
    return right;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetRight(LogicExpression newRight, NotificationChain msgs)
  {
    LogicExpression oldRight = right;
    right = newRight;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__RIGHT, oldRight, newRight);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setRight(LogicExpression newRight)
  {
    if (newRight != right)
    {
      NotificationChain msgs = null;
      if (right != null)
        msgs = ((InternalEObject)right).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__RIGHT, null, msgs);
      if (newRight != null)
        msgs = ((InternalEObject)newRight).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__RIGHT, null, msgs);
      msgs = basicSetRight(newRight, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__RIGHT, newRight, newRight));
  }

  /**
   *
   *
   * @generated
   */
  public MULTIPLEOPERATOR getOpMul()
  {
    return opMul;
  }

  /**
   *
   *
   * @generated
   */
  public void setOpMul(MULTIPLEOPERATOR newOpMul)
  {
    MULTIPLEOPERATOR oldOpMul = opMul;
    opMul = newOpMul == null ? OP_MUL_EDEFAULT : newOpMul;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__OP_MUL, oldOpMul, opMul));
  }

  /**
   *
   *
   * @generated
   */
  public EList<LogicExpression> getArgs()
  {
    if (args == null)
    {
      args = new EObjectContainmentEList<LogicExpression>(LogicExpression.class, this, CatchMLPackage.LOGIC_EXPRESSION__ARGS);
    }
    return args;
  }

  /**
   *
   *
   * @generated
   */
  public TEMPORALOPERATOR getOpTemp()
  {
    return opTemp;
  }

  /**
   *
   *
   * @generated
   */
  public void setOpTemp(TEMPORALOPERATOR newOpTemp)
  {
    TEMPORALOPERATOR oldOpTemp = opTemp;
    opTemp = newOpTemp == null ? OP_TEMP_EDEFAULT : newOpTemp;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP, oldOpTemp, opTemp));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getTemporal()
  {
    return temporal;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetTemporal(LogicExpression newTemporal, NotificationChain msgs)
  {
    LogicExpression oldTemporal = temporal;
    temporal = newTemporal;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL, oldTemporal, newTemporal);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setTemporal(LogicExpression newTemporal)
  {
    if (newTemporal != temporal)
    {
      NotificationChain msgs = null;
      if (temporal != null)
        msgs = ((InternalEObject)temporal).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL, null, msgs);
      if (newTemporal != null)
        msgs = ((InternalEObject)newTemporal).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL, null, msgs);
      msgs = basicSetTemporal(newTemporal, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL, newTemporal, newTemporal));
  }

  /**
   *
   *
   * @generated
   */
  public TEMPUNTILOPERATOR getOpTempUntil()
  {
    return opTempUntil;
  }

  /**
   *
   *
   * @generated
   */
  public void setOpTempUntil(TEMPUNTILOPERATOR newOpTempUntil)
  {
    TEMPUNTILOPERATOR oldOpTempUntil = opTempUntil;
    opTempUntil = newOpTempUntil == null ? OP_TEMP_UNTIL_EDEFAULT : newOpTempUntil;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP_UNTIL, oldOpTempUntil, opTempUntil));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getLeftExp()
  {
    return leftExp;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetLeftExp(LogicExpression newLeftExp, NotificationChain msgs)
  {
    LogicExpression oldLeftExp = leftExp;
    leftExp = newLeftExp;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP, oldLeftExp, newLeftExp);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setLeftExp(LogicExpression newLeftExp)
  {
    if (newLeftExp != leftExp)
    {
      NotificationChain msgs = null;
      if (leftExp != null)
        msgs = ((InternalEObject)leftExp).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP, null, msgs);
      if (newLeftExp != null)
        msgs = ((InternalEObject)newLeftExp).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP, null, msgs);
      msgs = basicSetLeftExp(newLeftExp, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP, newLeftExp, newLeftExp));
  }

  /**
   *
   *
   * @generated
   */
  public LogicExpression getRightExp()
  {
    return rightExp;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetRightExp(LogicExpression newRightExp, NotificationChain msgs)
  {
    LogicExpression oldRightExp = rightExp;
    rightExp = newRightExp;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP, oldRightExp, newRightExp);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setRightExp(LogicExpression newRightExp)
  {
    if (newRightExp != rightExp)
    {
      NotificationChain msgs = null;
      if (rightExp != null)
        msgs = ((InternalEObject)rightExp).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP, null, msgs);
      if (newRightExp != null)
        msgs = ((InternalEObject)newRightExp).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP, null, msgs);
      msgs = basicSetRightExp(newRightExp, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP, newRightExp, newRightExp));
  }

  /**
   *
   *
   * @generated
   */
  public String getOp()
  {
    return op;
  }

  /**
   *
   *
   * @generated
   */
  public void setOp(String newOp)
  {
    String oldOp = op;
    op = newOp;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, CatchMLPackage.LOGIC_EXPRESSION__OP, oldOp, op));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case CatchMLPackage.LOGIC_EXPRESSION__EXPR:
        return basicSetExpr(null, msgs);
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT:
        return basicSetLeft(null, msgs);
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT:
        return basicSetRight(null, msgs);
      case CatchMLPackage.LOGIC_EXPRESSION__ARGS:
        return ((InternalEList<?>)getArgs()).basicRemove(otherEnd, msgs);
      case CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL:
        return basicSetTemporal(null, msgs);
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP:
        return basicSetLeftExp(null, msgs);
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP:
        return basicSetRightExp(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case CatchMLPackage.LOGIC_EXPRESSION__EXPR:
        return getExpr();
      case CatchMLPackage.LOGIC_EXPRESSION__VALUE:
        if (resolve) return getValue();
        return basicGetValue();
      case CatchMLPackage.LOGIC_EXPRESSION__OP_BIN:
        return getOpBin();
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT:
        return getLeft();
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT:
        return getRight();
      case CatchMLPackage.LOGIC_EXPRESSION__OP_MUL:
        return getOpMul();
      case CatchMLPackage.LOGIC_EXPRESSION__ARGS:
        return getArgs();
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP:
        return getOpTemp();
      case CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL:
        return getTemporal();
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP_UNTIL:
        return getOpTempUntil();
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP:
        return getLeftExp();
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP:
        return getRightExp();
      case CatchMLPackage.LOGIC_EXPRESSION__OP:
        return getOp();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @SuppressWarnings("unchecked")
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case CatchMLPackage.LOGIC_EXPRESSION__EXPR:
        setExpr((LogicExpression)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__VALUE:
        setValue((AbstractDeclaration)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_BIN:
        setOpBin((BINARYOPERATOR)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT:
        setLeft((LogicExpression)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT:
        setRight((LogicExpression)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_MUL:
        setOpMul((MULTIPLEOPERATOR)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__ARGS:
        getArgs().clear();
        getArgs().addAll((Collection<? extends LogicExpression>)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP:
        setOpTemp((TEMPORALOPERATOR)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL:
        setTemporal((LogicExpression)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP_UNTIL:
        setOpTempUntil((TEMPUNTILOPERATOR)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP:
        setLeftExp((LogicExpression)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP:
        setRightExp((LogicExpression)newValue);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP:
        setOp((String)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case CatchMLPackage.LOGIC_EXPRESSION__EXPR:
        setExpr((LogicExpression)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__VALUE:
        setValue((AbstractDeclaration)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_BIN:
        setOpBin(OP_BIN_EDEFAULT);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT:
        setLeft((LogicExpression)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT:
        setRight((LogicExpression)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_MUL:
        setOpMul(OP_MUL_EDEFAULT);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__ARGS:
        getArgs().clear();
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP:
        setOpTemp(OP_TEMP_EDEFAULT);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL:
        setTemporal((LogicExpression)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP_UNTIL:
        setOpTempUntil(OP_TEMP_UNTIL_EDEFAULT);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP:
        setLeftExp((LogicExpression)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP:
        setRightExp((LogicExpression)null);
        return;
      case CatchMLPackage.LOGIC_EXPRESSION__OP:
        setOp(OP_EDEFAULT);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case CatchMLPackage.LOGIC_EXPRESSION__EXPR:
        return expr != null;
      case CatchMLPackage.LOGIC_EXPRESSION__VALUE:
        return value != null;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_BIN:
        return opBin != OP_BIN_EDEFAULT;
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT:
        return left != null;
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT:
        return right != null;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_MUL:
        return opMul != OP_MUL_EDEFAULT;
      case CatchMLPackage.LOGIC_EXPRESSION__ARGS:
        return args != null && !args.isEmpty();
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP:
        return opTemp != OP_TEMP_EDEFAULT;
      case CatchMLPackage.LOGIC_EXPRESSION__TEMPORAL:
        return temporal != null;
      case CatchMLPackage.LOGIC_EXPRESSION__OP_TEMP_UNTIL:
        return opTempUntil != OP_TEMP_UNTIL_EDEFAULT;
      case CatchMLPackage.LOGIC_EXPRESSION__LEFT_EXP:
        return leftExp != null;
      case CatchMLPackage.LOGIC_EXPRESSION__RIGHT_EXP:
        return rightExp != null;
      case CatchMLPackage.LOGIC_EXPRESSION__OP:
        return OP_EDEFAULT == null ? op != null : !OP_EDEFAULT.equals(op);
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (opBin: ");
    result.append(opBin);
    result.append(", opMul: ");
    result.append(opMul);
    result.append(", opTemp: ");
    result.append(opTemp);
    result.append(", opTempUntil: ");
    result.append(opTempUntil);
    result.append(", op: ");
    result.append(op);
    result.append(')');
    return result.toString();
  }

} //LogicExpressionImpl


text:
use ElectricCommander;
use ElectricCommander::PropDB;
use JSON;
use Data::Dumper;

use constant {
    SUCCESS => 0,
    ERROR   => 1,
};

## get an EC object
my $ec = new ElectricCommander();

my $projName = '$[/myProject/name]';
my $configPropertySheet;
eval {
    $configPropertySheet = $ec->getPropertyValue('/myProject/ec_configPropertySheet');
    1;
} or do {
    $configPropertySheet = 'weblogic_cfgs';
    #    $configPropertySheet = 'ec_plugin_cfgs';
};

eval {
    createConfigurationPropertySheet($configPropertySheet);
    1;
} or do {
    my $err = $@;
    print $err;
    rollback($configPropertySheet, $err);
    $ec->setProperty("/myJob/configError", $err);
    exit 1;
};

my $steps     = [];
my $stepsJSON = eval {$ec->getPropertyValue("/projects/$projName/procedures/CreateConfiguration/ec_stepsWithAttachedCredentials")};
if ($stepsJSON) {
    $steps = decode_json($stepsJSON);
}

my $configName = '$[config]';

eval {
    my $opts = getActualParameters();

    for my $param (
        $ec->getFormalParameters({
                projectName   => $projName,
                procedureName => 'CreateConfiguration',
            }
        )->findnodes('//formalParameter')
    ) {
        my $type = $param->findvalue('type') . '';
        if ($type eq 'credential') {
            my $required       = $param->findvalue('required') . '';
            my $fieldName      = $param->findvalue('formalParameterName') . '';
            my $credentialName = $opts->{$fieldName};

            eval {
                my $createEmpty = 0;
                if (!$credentialName) {
                    # next;
                    $createEmpty    = 1;
                    $credentialName = $fieldName;
                }
                my $ref = createAndAttachCredential($credentialName, $configName, $configPropertySheet, $steps, $createEmpty);
                1;
            } or do {
                my $err = $@;
                if ($required) {
                    die $err;
                }
                else {
                    print "Failed to create credential $credentialName: $err\n";
                }
            };
        } ## end if ($type eq 'credential')
    } ## end for my $param ($ec->getFormalParameters...)
    1;
} or do {
    my $err = $@;
    print $err;
    rollback($configPropertySheet, $err);
    $ec->setProperty("/myJob/configError", $err);
    exit 1;
};

sub createAndAttachCredential {
    my ($credName, $configName, $configPropertySheet, $steps, $createEmpty) = @_;

    # if ($createEmpty) {
    #     print "CREATING EMPTY CREDENTIAL '$projName' : '$credName'\n";
    #     $ec->createCredential($projName, $credName, '', '');
    # }

    my $xpath;
    my $errors;
    my $clientID     = '';
    my $clientSecret = '';
    unless ($createEmpty) {
        $xpath        = $ec->getFullCredential($credName);
        $errors       = $ec->checkAllErrors($xpath);
        $clientID     = $xpath->findvalue("//userName");
        $clientSecret = $xpath->findvalue("//password");
    }

    my ($existingCredRef, $existingCredProjectName, $existingCredName);
    eval {
        $existingCredRef  = $xpath->findvalue("//credentialReference")->string_value();
        $existingCredName = $xpath->findvalue("//credentialName")->string_value();
        # here we have the credential that has been passed as a reference.
        $existingCredProjectName = $1 if $existingCredRef =~ m|\/projects\/(.*?)\/|s;
        # now we have all three of them. And if these values are defined - we have
        # existing credential that we just need to attach instead of create.
    } unless $createEmpty;
    my $projName = '$[/myProject/projectName]';

    my $credObjectName = $credName eq 'credential' ? $configName : "${configName}_${credName}";
    # die $credObjectName;
    my $configPath = "/projects/$projName/$configPropertySheet/$configName/$credName";
    if (!$existingCredRef) {
        print "No existing credential reference... Creating...\n";
        # Create credential
        $ec->deleteCredential($projName, $credObjectName);
        $xpath = $ec->createCredential($projName, $credObjectName, $clientID, $clientSecret);
        $errors .= $ec->checkAllErrors($xpath);

        # Give config the credential's real name

        $xpath = $ec->setProperty($configPath, $credObjectName);
        $errors .= $ec->checkAllErrors($xpath);

        # Give job launcher full permissions on the credential
        my $user = '$[/myJob/launchedByUser]';
        $xpath = $ec->createAclEntry(
            "user", $user, {
                projectName                => $projName,
                credentialName             => $credObjectName,
                readPrivilege              => 'allow',
                modifyPrivilege            => 'allow',
                executePrivilege           => 'allow',
                changePermissionsPrivilege => 'allow'
            }
        );
        $errors .= $ec->checkAllErrors($xpath);
    } ## end if (!$existingCredRef)
        # Attach credential to steps that will need it
    for my $step (@$steps) {
        if ($existingCredRef) {
            $credObjectName = $existingCredRef;
        }
        print "Attaching credential to procedure " . $step->{procedureName} . " at step " . $step->{stepName} . "\n";
        my $apath = $ec->attachCredential(
            $projName,
            $credObjectName, {
                procedureName => $step->{procedureName},
                stepName      => $step->{stepName}
            }
        );
        $errors .= $ec->checkAllErrors($apath);
    }

    if ("$errors" ne "") {
        # Cleanup the partially created configuration we just created
        $ec->deleteProperty($configPath);
        $ec->deleteCredential($projName, $credObjectName);
        my $errMsg = "Error creating configuration credential: " . $errors;
        $ec->setProperty("/myJob/configError", $errMsg);
        die $errMsg;
    }
} ## end sub createAndAttachCredential

sub rollback {
    my ($configPropertySheet, $error) = @_;

    if ($error !~ /already exists/) {
        my $configName = '$[config]';
        $ec->deleteProperty("/myProject/$configPropertySheet/$configName");
    }
}

sub getActualParameters {
    my $x       = $ec->getJobDetails($ENV{COMMANDER_JOBID});
    my $nodeset = $x->find('//actualParameter');
    my $opts;

    foreach my $node ($nodeset->get_nodelist) {
        my $parm = $node->findvalue('actualParameterName');
        if ($parm =~ m/credential$/s) {
            my $value = $node->findvalue('value');
            unless ($value) {
                # return undef;
                # $opts->{$parm} = $parm;
                # no cred ref here, we can next;
                next;
            }
            my $credRef = getCredentialReference($parm);
            if ($credRef) {
                my $key = $parm . '_ref';
                $opts->{$key} = $credRef;
            }
        }
        my $val = $node->findvalue('value');
        $opts->{$parm} = "$val";
    }
    return $opts;
} ## end sub getActualParameters

sub getCredentialReference {
    my ($credName) = @_;

    if (!$credName) {
        die "Cred name is mandatory to get credential reference...\n";
    }
    my $xpath           = $ec->getFullCredential($credName);
    my $existingCredRef = undef;
    eval {$existingCredRef = $xpath->findvalue("//credentialReference")->string_value();};

    return $existingCredRef;
}

sub createConfigurationPropertySheet {
    my ($configPropertySheet) = @_;

    ## load option list from procedure parameters
    my $ec = ElectricCommander->new;
    $ec->abortOnError(0);
    my $x       = $ec->getJobDetails($ENV{COMMANDER_JOBID});
    my $nodeset = $x->find('//actualParameter');
    my $opts    = getActualParameters();

    print "Got actual parameters\n";
    if (!defined $opts->{config} || "$opts->{config}" eq "") {
        die "config parameter must exist and be non-blank\n";
    }

    # check to see if a config with this name already exists before we do anything else
    my $xpath    = $ec->getProperty("/myProject/$configPropertySheet/$opts->{config}");
    my $property = $xpath->findvalue("//response/property/propertyName");

    if (defined $property && "$property" ne "") {
        my $errMsg = "A configuration named '$opts->{config}' already exists.";
        $ec->setProperty("/myJob/configError", $errMsg);
        die $errMsg;
    }

    my $table_path = "/myProject/$configPropertySheet";
    my $cfg        = new ElectricCommander::PropDB($ec, $table_path);

    # add all the options as properties
    foreach my $key (keys %{$opts}) {
        if ("$key" eq "config" || $key =~ m/_?credential_ref$/s) {
            next;
        }

        my $t = $opts->{"$key" . "_ref"};
        if ("$key" =~ m/credential$/s && $t) {
            $opts->{$key} = $t;
        }
        setColAdvanced($ec, $table_path, "$opts->{config}", "$key", "$opts->{$key}");
        # $cfg->setCol("$opts->{config}", "$key", "$opts->{$key}");
    }
} ## end sub createConfigurationPropertySheet

sub gen_credential_name {
    my ($config_name, $credential_name) = @_;

    if ($credential_name eq 'credential') {
        return $config_name;
    }

    return $config_name . '_' . $credential_name;
}

sub setColAdvanced {
    my ($ec, $path, $row, $col, $value) = @_;

    my $full_path = $path . "/$row/$col";
    $ec->setProperty($full_path, $value, {expandable => 0});
    return $value;
}

## === createConfiguration template ends ===
## === createConfiguration ends ===
# Please do not edit this file


text:
class Api::V1::GroupResource < JSONAPI::Resource
  attributes :about,
             :banner_url,
             :meet_details,
             :name,
             :profile_picture_url,
             :short_description,
             :slug,
             :target_audience

  attribute :created_at, format: :iso8601

  has_many :posts

  filter :slug

  def self.apply_filter(records, filter, value, options)
    case filter
    when :slug
      records.where(slug: value)
    else
      return super(records, filter, value, options)
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 83: 48 (2002)

#### Original name
Omphalina velutipes P.D. Orton, 1960

### Remarks
null


text:
require 'spec_helper'

describe 'spree:migrations:copy_shipped_shipments_to_cartons' do
  before do
    Rails.application.load_tasks
    task.reenable
  end

  describe 'up' do
    let(:task) do
      Rake::Task['spree:migrations:copy_shipped_shipments_to_cartons:up']
    end

    # should generate a carton
    let!(:shipped_shipment) { shipped_order.shipments.first }
    # should not generate a carton because it's not shipped
    let!(:unshipped_shipment) { create(:shipment) }
    # should not generate a carton because it has no inventory units
    let!(:shipped_shipment_without_units) do
      shipped_order_without_units.shipments.first
    end
    # should not generate a carton because it already has a carton
    let!(:shipped_and_cartonized_shipment) do
      shipped_and_cartonized_order.shipments.first
    end

    let(:shipped_order) { create(:shipped_order, line_items_count: 1, with_cartons: false) }

    let(:shipped_order_without_units) do
      create(:shipped_order, line_items_count: 1) do |order|
        order.inventory_units.delete_all
      end
    end

    let(:shipped_and_cartonized_order) do
      create(:order_ready_to_ship, line_items_count: 1).tap do |order|
        order.shipping.ship_shipment(order.shipments.first)
      end
    end

    it 'creates the expected carton' do
      expect {
        task.invoke
      }.to change { Spree::Carton.count }.by(1)

      carton = Spree::Carton.last

      expect(carton).to be_valid

      expect(carton.imported_from_shipment_id).to eq shipped_shipment.id
      expect(carton.orders).to eq [shipped_order]

      expect(carton.number).to eq "C#{shipped_shipment.number}"
      expect(carton.stock_location).to eq shipped_shipment.stock_location
      expect(carton.address).to eq shipped_shipment.address
      expect(carton.shipping_method).to eq shipped_shipment.shipping_method
      expect(carton.tracking).to eq shipped_shipment.tracking
      expect(carton.shipped_at).to eq shipped_shipment.shipped_at
      expect(carton.created_at).to be_present
      expect(carton.updated_at).to be_present

      expect(carton.inventory_units).to match_array shipped_shipment.inventory_units
    end

    describe 'when run a second time' do
      before do
        task.invoke
        task.reenable
      end

      let!(:second_shipped_shipment) { second_shipped_order.shipments.first }

      let(:second_shipped_order) { create(:shipped_order, line_items_count: 1, with_cartons: false) }

      it 'creates only a carton for the second shipment' do
        expect {
          task.invoke
        }.to change { Spree::Carton.count }.by(1)

        carton = Spree::Carton.last

        expect(carton.imported_from_shipment_id).to eq second_shipped_shipment.id
        expect(carton.orders).to eq [second_shipped_order]
      end
    end
  end

  describe 'down' do
    let(:task) do
      Rake::Task['spree:migrations:copy_shipped_shipments_to_cartons:down']
    end

    let!(:migrated_carton) { create(:carton) }
    let!(:preexisting_carton) { create(:carton) }

    let!(:migrated_carton_inventory_units) { migrated_carton.inventory_units.to_a }
    let!(:preexisting_carton_inventory_units) { preexisting_carton.inventory_units.to_a }

    before do
      migrated_carton.update!(imported_from_shipment_id: migrated_carton.inventory_units.first.shipment_id)
    end

    it 'clears out the correct carton' do
      expect {
        task.invoke
      }.to change { Spree::Carton.count }.by(-1)

      expect(Spree::Carton.find_by(id: migrated_carton.id)).to be_nil

      expect(migrated_carton_inventory_units.map(&:reload).map(&:carton_id)).to all(be_nil)
      expect(preexisting_carton_inventory_units.map(&:reload).map(&:carton_id)).to all(eq preexisting_carton.id)
    end
  end
end


text:
module UsdaNutrientDatabase
  module Import
    class Foods < Base

      private

      def apply_typecasts(row)
        row[6] = row[6].present?
        row
      end

      def find_or_initialize(row)
        UsdaNutrientDatabase::Food.
          find_or_initialize_by(nutrient_databank_number: row[0])
      end

      def log_import_started
        UsdaNutrientDatabase.log 'Importing foods'
      end

      def filename
        'FOOD_DES.txt'
      end

      def columns
        [
          :nutrient_databank_number, :food_group_code, :long_description,
          :short_description, :common_names, :manufacturer_name, :survey,
          :refuse_description, :percentage_refuse, :nitrogen_factor,
          :protein_factor, :fat_factor, :carbohydrate_factor
        ]
      end
    end
  end
end


text:
package nl.knaw.dans.common.dbflib;

/**
 * Base class for all DANS DBF Library expections.
 *
 * @author Jan van Mansum
 */
public abstract class DbfLibException
    extends Exception
{
    private static final long serialVersionUID = -4541592758007418317L;

    protected DbfLibException(final String message)
    {
        super(message);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Monograph of Clavaria and allied Genera (Annals of Botany Memoirs No. 1) 360 (1950)

#### Original name
Asterophora candida Weinm.

### Remarks
null


text:
<?php

namespace BingoBundle\Controller;

// these import the "@Route", "@Method", "@ParamConverter" and "@Template" annotations...
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
//use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

// these import the "@View" annotations for FOS Rest Bundle...
use FOS\RestBundle\Controller\Annotations as Rest;

use BaseBundle\Controller\AbstractAdminController;
use BingoBundle\Propel\Game;
use BingoBundle\Propel\GameQuery;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Kernel;

/**
 * Class AdminGameController
 *
 * @package BingoBundle\Controller
 */
class AdminGameController extends AbstractAdminController
{
    /**
     * Methode zum Erstellen oder zum Bearbeiten eines Spiels.
     *
     * @Route("/admin/game", name="bingo_game")
     * @Route("/admin/rest/game", name="bingo_game_rest_post", defaults={ "_format" = "json" })
     * @Method("POST")
     * @Rest\View()
     * @param Request $request
     * @return array
     */
    public function postAction(Request $request)
    {
        $locale = 'de_DE';

        if ($request->request->has('locale')) {
            $locale = $request->request->get('locale');
        }

        $id = $request->request->get('id', null);
        $slug = $request->request->get('slug');
        $name = $request->request->get('name');

        if (!is_null($id) || !is_numeric($id)) {
            $gamesQuery = new GameQuery();
            $gamesQuery->joinWithI18n($locale);
            $game = $gamesQuery->findOneById($id);
        }

        if (is_null($game)) {
            $game = new Game();
        }

        $game->setSlug($slug);
        $game->setLocale($locale);
        $game->setName($name);
        $game->save();

        return array(
            'name' => 'FreakXoHBingo',
            'version' => Kernel::VERSION,
            'status' => true,
            'game' => $game
        );
    }
}


text:
extern "C" {

bool gdv_fn_like_utf8_utf8(int64_t ptr, const char* data, int data_len,
                           const char* pattern, int pattern_len);

int64_t gdv_fn_to_date_utf8_utf8_int32(int64_t context, int64_t ptr, const char* data,
                                       int data_len, bool in1_validity,
                                       const char* pattern, int pattern_len,
                                       bool in2_validity, int32_t suppress_errors,
                                       bool in3_validity, bool* out_valid);

void gdv_fn_context_set_error_msg(int64_t context_ptr, const char* err_msg);

uint8_t* gdv_fn_context_arena_malloc(int64_t context_ptr, int32_t data_len);

void gdv_fn_context_arena_reset(int64_t context_ptr);

bool in_expr_lookup_int32(int64_t ptr, int32_t value, bool in_validity);

bool in_expr_lookup_int64(int64_t ptr, int64_t value, bool in_validity);

bool in_expr_lookup_utf8(int64_t ptr, const char* data, int data_len, bool in_validity);
}

#endif  // GDV_FUNCTION_STUBS_H


text:
<?php

namespace OuterEdge\Menu\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;
use OuterEdge\Menu\Model\ResourceModel\Menu\CollectionFactory;

class Menu implements ArrayInterface
{
    /**
     * Returns an array of menus
     *
     * @param CollectionFactory $collectionFactory
     * @codeCoverageIgnore
     */
    public function __construct(
        CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * Options getter
     *
     * @return array
     */
    public function toOptionArray()
    {
        $data = [];
        $collection = $this->collectionFactory->create();
        foreach ($collection as $menu) {
            $data[] = [
                'value' => $menu->getId(),
                'label' => $menu->getName()
            ];
        }
        return $data;
    }
}


text:
Decoder::Decoder(VideoFile &file) {
	int error;
	AVDictionary *opts = NULL;

	codec = avcodec_find_decoder(AV_CODEC_ID_H264);
	ctx = file.ctx->streams[file.vstream]->codec;

	error = avcodec_open2(ctx, codec, &opts);
	if( error < 0 ) {
		throw LibavError(error);
	}
}

std::unique_ptr<Frame> Decoder::decode(RawFrame *input) {
	AVFrame *frame = avcodec_alloc_frame();
	int got_picture;
	int error;

	error = avcodec_decode_video2(ctx, frame, &got_picture, &input->packet);
	if( error < 0 ) {
		throw LibavError(error);
	}

	if( !got_picture ) {
		av_free(frame);
		return nullptr;
	}

	return std::unique_ptr<Frame>( new Frame(frame) );
}


text:
Ext.define('ExtThemeNeptune.menu.Menu', {
    override: 'Ext.menu.Menu',
    showSeparator: false
});


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Frontend Boilerplate</title>
    <link rel="stylesheet" href="/assets/dist/app.css">
</head>
<body>
hello world
<script src="/assets/dist/bundle.js"></script>
</body>
</html>


text:
<?php

namespace application\components\blog\controller;

use application\components\blog\model\AuthorModel;
use umi\hmvc\controller\BaseController;

/**
 * Контроллер отображения постов по авторам.
 */
class AuthorController extends BaseController
{
    /**
     * @var AuthorModel $authorModel модель компонента
     */
    protected $authorModel;

    /**
     * Конструктор.
     * @param AuthorModel $model
     */
    public function __construct(AuthorModel $model)
    {
        $this->authorModel = $model;
    }

    /**
     * {@inheritdoc}
     */
    public function __invoke()
    {
        $guid = $this->getRouteVar('id');

        $author = $this->authorModel->getAuthor($guid);

        return $this->createViewResponse(
            'author',
            [
                'author' => $author,
                'posts'  => $this->authorModel->getAuthorPosts($author)
            ]
        );
    }
}


text:
/*
Language: Java
Author: Vsevolod Solovyov <vsevolod.solovyov@gmail.com>
Category: common
*/

function(hljs) {
  var GENERIC_IDENT_RE = hljs.UNDERSCORE_IDENT_RE + '(<' + hljs.UNDERSCORE_IDENT_RE + '>)?';
  var KEYWORDS =
    'false synchronized int abstract float private char boolean static null if const ' +
    'for true while long throw strictfp finally protected import native final return void ' +
    'enum else break transient new catch instanceof byte super volatile case assert short ' +
    'package default double public try this switch continue throws protected public private';
  return {
    aliases: ['jsp'],
    keywords: KEYWORDS,
    illegal: /<\//,
    contains: [
      {
        className: 'javadoc',
        begin: '/\\*\\*', end: '\\*/',
        relevance: 0,
        contains: [{
          className: 'javadoctag', begin: '(^|\\s)@[A-Za-z]+'
        }]
      },
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'class',
        beginKeywords: 'class interface', end: /[{;=]/, excludeEnd: true,
        keywords: 'class interface',
        illegal: /[:"\[\]]/,
        contains: [
          {beginKeywords: 'extends implements'},
          hljs.UNDERSCORE_TITLE_MODE
        ]
      },
      {
        // this prevents 'new Name(...), or throw ...' from being recognized as a function definition
        beginKeywords: 'new throw', end: /\s/,
        relevance: 0
      },
      {
        className: 'function',
        begin: '(' + GENERIC_IDENT_RE + '\\s+)+' + hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/,
        excludeEnd: true,
        keywords: KEYWORDS,
        contains: [
          {
            begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true,
            contains: [hljs.UNDERSCORE_TITLE_MODE]
          },
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            keywords: KEYWORDS,
            contains: [
              hljs.APOS_STRING_MODE,
              hljs.QUOTE_STRING_MODE,
              hljs.C_NUMBER_MODE,
              hljs.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      hljs.C_NUMBER_MODE,
      {
        className: 'annotation', begin: '@[A-Za-z]+'
      }
    ]
  };
}