text:
<!doctype html>

    <meta charset="utf-8">
    <title>react-simple-jstree usage demo</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace comyii\user\components;

use Yii;
use yii\base\Component;

/**
 * Class Profile the user profile component for the module.
 *
 * @package comyii\user\components
 */
class Profile extends Component
{
    /**
     * @var bool whether the user profile is enabled for the module. Defaults to `true`.
     */
    public $enabled = true;

    /**
     * @var string the default file path where uploads will be stored. You can use Yii path
     * aliases for setting this. Defaults to '@webroot/uploads'.
     */
    public $basePath = '@webroot/uploads';

    /**
     * @var string the absolute baseUrl pointing to the uploads path. Defaults to '/uploads'.
     * You must set the full absolute url here to enable avatar URL to be parsed seamlessly across
     * both frontend and backend apps in yii2-app-advanced.
     */
    public $baseUrl = '/uploads';

    /**
     * @var string the filename for the default avatar located in the above path which will
     * be displayed when no profile image file is found. Defaults to `avatar.png`.
     */
    public $defaultAvatar = 'avatar.png';

    /**
     * @var array|bool the widget settings for FileInput widget to upload the avatar.
     * If this is set to `false`, no avatar / image upload will be enabled for the user.
     */
    private $avatar;

    /**
     * Get the Avatar widget
     * @return \yii\base\Widget
     */
    public function getAvatar()
    {
        if ($this->avatar === null) {
            $this->avatar = [
                'options' => ['accept' => 'image/*'],
                'pluginOptions' => [
                    'elErrorContainer' => '#user-avatar-errors',
                    'allowedFileExtensions' => ['jpg', 'gif', 'png'],
                    'maxFileSize' => 200,
                    'showCaption' => false,
                    'overwriteInitial' => true,
                    'browseLabel' => '',
                    'removeLabel' => '',
                    'removeIcon' => '',
                    'browseIcon' => '',
                    'showClose' => false,
                    'showUpload' => false,
                    'removeTitle' => Yii::t('user', 'Cancel or reset changes'),
                    'msgErrorClass' => 'alert alert-block alert-danger',
                    'previewSettings' => [
                        'image' => ['width' => 'auto', 'height' => '180px'],
                    ]
                ]
            ];
        }
        if (!($this->avatar) instanceof \yii\base\Widget) {
            $this->avatar = Yii::createObject($this->avatar['class'], $this->avatar);
        }
        return $this->avatar;
    }

}


text:
// FileZilla Server - a Windows ftp server

// Copyright (C) 2002-2004 - Tim Kosse <tim.kosse@gmx.de>

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

// MainFrm.cpp : Implementierung der Klasse CMainFrame
//

#include "stdafx.h"
#include "FileZilla server.h"
#include "misc/led.h"
#include "MainFrm.h"
#include "../iputils.h"
#include "../platform.h"
#include "statusview.h"
#include "usersdlg.h"
#include "GroupsDlg.h"
#include "options.h"
#include "usersview.h"
#include "userslistctrl.h"
#include "misc/systemtray.h"
#include "offlineaskdlg.h"
#include "../version.h"
#include "AdminSocket.h"
#include "OptionsDlg.h"
#include "ConnectDialog.h"
#include "mainfrm.h"
#include "../defs.h"
#include "OutputFormat.h"

#if defined(_DEBUG) && !defined(MMGR)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	ON_WM_SETFOCUS()
	ON_WM_SIZE()
	ON_WM_CLOSE()
	ON_COMMAND(ID_EDIT_SETTINGS, OnEditSettings)
	ON_COMMAND(ID_ACTIVE, OnActive)
	ON_UPDATE_COMMAND_UI(ID_ACTIVE, OnUpdateActive)
	ON_WM_SYSCOMMAND()
	ON_COMMAND(ID_TRAY_EXIT, OnTrayExit)
	ON_COMMAND(ID_TRAY_RESTORE, OnTrayRestore)
	ON_COMMAND(ID_LOCK, OnLock)
	ON_UPDATE_COMMAND_UI(ID_LOCK, OnUpdateLock)
	ON_WM_TIMER()
	ON_COMMAND(ID_USERS, OnMenuEditUsers)
	ON_COMMAND(ID_GROUPS, OnMenuEditGroups)
	ON_COMMAND(ID_FILE_CONNECT, OnFileConnect)
	ON_COMMAND(ID_FILE_DISCONNECT, OnFileDisconnect)
	ON_UPDATE_COMMAND_UI(ID_FILE_DISCONNECT, OnUpdateFileDisconnect)
	ON_UPDATE_COMMAND_UI(ID_EDIT_SETTINGS, OnUpdateEditSettings)
	ON_UPDATE_COMMAND_UI(ID_MENU_EDIT_USERS, OnUpdateMenuEditUsers)
	ON_UPDATE_COMMAND_UI(ID_MENU_EDIT_GROUPS, OnUpdateMenuEditGroups)
	ON_UPDATE_COMMAND_UI(ID_USERS, OnUpdateUsers)
	ON_UPDATE_COMMAND_UI(ID_GROUPS, OnUpdateGroups)
	ON_COMMAND(ID_MENU_EDIT_USERS, OnMenuEditUsers)
	ON_COMMAND(ID_MENU_EDIT_GROUPS, OnMenuEditGroups)
	ON_COMMAND(ID_USERLISTTOOLBAR_DISPLAYLOGICAL, OnDisplayLogicalNames)
	ON_COMMAND(ID_USERLISTTOOLBAR_DISPLAYPHYSICAL, OnDisplayPhysicalNames)
	ON_UPDATE_COMMAND_UI(ID_USERLISTTOOLBAR_DISPLAYLOGICAL, OnUpdateDisplayLogicalNames)
	ON_UPDATE_COMMAND_UI(ID_USERLISTTOOLBAR_DISPLAYPHYSICAL, OnUpdateDisplayPhysicalNames)
	ON_COMMAND(ID_USERLISTTOOLBAR_SORT, OnDisplaySortMenu)
	ON_NOTIFY(TBN_DROPDOWN, AFX_IDW_TOOLBAR, OnToolbarDropDown)
	ON_COMMAND(ID_DISPLAY_SORTBYUSERID, OnDisplaySortByUserid)
	ON_COMMAND(ID_DISPLAY_SORTBYACCOUNT, OnDisplaySortByAccount)
	ON_COMMAND(ID_DISPLAY_SORTBYIP, OnDisplaySortByIP)
	ON_UPDATE_COMMAND_UI(ID_DISPLAY_SORTBYUSERID, OnUpdateDisplaySortByUserid)
	ON_UPDATE_COMMAND_UI(ID_DISPLAY_SORTBYACCOUNT, OnUpdateDisplaySortByAccount)
	ON_UPDATE_COMMAND_UI(ID_DISPLAY_SORTBYIP, OnUpdateDisplaySortByIP)
	ON_WM_DESTROY()
	//}}AFX_MSG_MAP
	ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,		   // Statusleistenanzeige
	ID_INDICATOR_RECVCOUNT,
	ID_INDICATOR_RECVRATE,
	ID_INDICATOR_SENDCOUNT,
	ID_INDICATOR_SENDRATE,
	ID_INDICATOR_RECVLED,
	ID_INDICATOR_SENDLED,
	ID_SEPARATOR
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame Konstruktion/Zerstörung

CMainFrame::CMainFrame(COptions *pOptions)
{
	ASSERT(pOptions);
	s_winClassName = 0;
	nTrayNotificationMsg_ = RegisterWindowMessage(_T("FileZilla Server Tray Notification Message"));
	m_bQuit = FALSE;
	m_nSendCount = 0;
	m_nRecvCount = 0;
	m_lastchecktime = GetTickCount();
	m_lastreaddiff = 0;
	m_lastwritediff = 0;
	m_nOldRecvCount = 0;
	m_nOldSendCount = 0;
	m_pOptions = pOptions;
	m_pAdminSocket = NULL;
	m_nServerState = 0;
	m_nEdit = 0;

	m_pOptionsDlg = 0;
	m_pUsersDlg = 0;
	m_pGroupsDlg = 0;

	m_nReconnectTimerID = 0;
	m_nReconnectCount = 0;
}

CMainFrame::~CMainFrame()
{
	delete m_pOptions;
	m_pOptions = 0;
	CloseAdminSocket(false);
	delete [] s_winClassName; //Does seem to crash
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	SetupTrayIcon();

	if (!m_wndReBar.Create(this))
		return -1;

	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_ALIGN_TOP
		| CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Could not create Toolbar 1\n");
		return -1;	  // Fehler bei Erstellung
	}

	if (!m_wndUserListToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_ALIGN_TOP | CBRS_ALIGN_LEFT
		| CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndUserListToolBar.LoadToolBar(IDR_USERLISTTOOLBAR))
	{
		TRACE0("Could not create Toolbar 2\n");
		return -1;	  // Fehler bei Erstellung
	}
	m_wndUserListToolBar.GetToolBarCtrl().SetExtendedStyle(TBSTYLE_EX_DRAWDDARROWS);
	DWORD dwStyle = m_wndUserListToolBar.GetButtonStyle(m_wndUserListToolBar.CommandToIndex(ID_USERLISTTOOLBAR_SORT));
	dwStyle |= TBSTYLE_DROPDOWN;
	m_wndUserListToolBar.SetButtonStyle(m_wndUserListToolBar.CommandToIndex(ID_USERLISTTOOLBAR_SORT), dwStyle);

	m_wndReBar.AddBar(&m_wndToolBar);
	m_wndReBar.AddBar(&m_wndUserListToolBar);
	m_wndReBar.GetReBarCtrl().MinimizeBand(0);

	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Statusleiste konnte nicht erstellt werden\n");
		return -1;	  // Fehler bei Erstellung
	}

	// The last statusbar pane is a fake one, it has zero width.
	m_wndStatusBar.SetPaneInfo(7, 0, SBPS_NOBORDERS, 0);

	CRect rect;
	m_wndStatusBar.GetItemRect(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVLED), rect);

	//Create the first LED control
	m_RecvLed.Create(_T(""), WS_VISIBLE|WS_CHILD, rect, &m_wndStatusBar, m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVLED));
	m_RecvLed.SetLed( CLed::LED_COLOR_GREEN, CLed::LED_OFF, CLed::LED_ROUND);

	//Create the second LED control
	m_SendLed.Create(_T(""), WS_VISIBLE|WS_CHILD, rect, &m_wndStatusBar, m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDLED));
	m_SendLed.SetLed( CLed::LED_COLOR_RED, CLed::LED_OFF, CLed::LED_ROUND);

	m_wndStatusBar.GetItemRect(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDLED), &rect);
	m_wndStatusBar.SetPaneInfo(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVLED),ID_INDICATOR_RECVLED,SBPS_NOBORDERS,6);
	m_wndStatusBar.SetPaneInfo(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDLED),ID_INDICATOR_SENDLED,SBPS_NOBORDERS,6);

	ShowStatus(GetVersionString(), 0);
	ShowStatus(_T("Copyright 2001-2011 by Tim Kosse (tim.kosse@filezilla-project.org)"), 0);

	m_nTimerID = SetTimer(7777, 10000, 0);
	m_nRateTimerID = SetTimer(7778, 1000, 0);

	SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDCOUNT), _T("0 bytes sent"));
	SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVCOUNT), _T("0 bytes received"));
	SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVRATE), _T("0 B/s"));
	SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDRATE), _T("0 B/s"));

	CConnectDialog dlg(m_pOptions);
	if (!m_pOptions->GetOptionVal(IOPTION_ALWAYS) && dlg.DoModal() != IDOK)
		return 0;

	m_pAdminSocket = new CAdminSocket(this);
	ShowStatus("Connecting to server...", 0);
	DoConnect();

	return 0;
}

//////////////////
// Helper function to register a new window class based on an already
// existing window class, but with a different name and icon.
// Returns new name if successful; otherwise NULL.
//
static bool RegisterSimilarClass(LPCTSTR lpszNewClassName,
	LPCTSTR lpszOldClassName, UINT nIDResource)
{
	// Get class info for old class.
	//
	HINSTANCE hInst = AfxGetInstanceHandle();
	WNDCLASS wc;
	if (!::GetClassInfo(hInst, lpszOldClassName, &wc)) {
		TRACE("Can't find window class %s\n", lpszOldClassName);
		return false;
	}

	// Register new class with same info, but different name and icon.
	//
	wc.lpszClassName = lpszNewClassName;
	wc.hIcon = ::LoadIcon(hInst, MAKEINTRESOURCE(nIDResource));
	if (!AfxRegisterClass(&wc)) {
		TRACE("Unable to register window class%s\n", lpszNewClassName);
		return false;
	}
	return true;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;

	// ZU ERLEDIGEN: Ändern Sie hier die Fensterklasse oder das Erscheinungsbild, indem Sie
	//  CREATESTRUCT cs modifizieren.

	cs.lpszClass = AfxRegisterWndClass(0);

	cs.dwExStyle &= ~WS_EX_CLIENTEDGE;

	//Change the window class name
	if (!s_winClassName)
	{
		s_winClassName = new TCHAR[_tcslen(_T("FileZilla Server Main Window")) + 1];
		_tcscpy(s_winClassName, _T("FileZilla Server Main Window"));
		RegisterSimilarClass(s_winClassName, cs.lpszClass, IDR_MAINFRAME);
	}
	cs.lpszClass = s_winClassName;

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame Nachrichten-Handler
void CMainFrame::OnSetFocus(CWnd* pOldWnd)
{
	// Fokus an das Ansichtfenster weitergeben
}

BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
	// andernfalls die Standardbehandlung durchführen
	return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}

BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
	CRect rect;
	GetClientRect(rect);

	// Unterteiltes Fenster erstellen
	if (!m_wndSplitter.CreateStatic(this, 2, 1))
		return FALSE;
	if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CStatusView), CSize(1, rect.Height() - 150), pContext))
	{
		m_wndSplitter.DestroyWindow();
		return FALSE;
	}
	m_pStatusPane = (CStatusView*)m_wndSplitter.GetPane(0, 0);

	if (!m_wndSplitter.CreateView(1, 0, RUNTIME_CLASS(CUsersView), CSize(1, 150), pContext))
	{
		m_wndSplitter.DestroyWindow();
		return FALSE;
	}
	m_pUsersPane = (CUsersView*) m_wndSplitter.GetPane(1, 0);

	// Filename display option.
	GetUsersPane()->m_pListCtrl->SetDisplayPhysicalNames(m_pOptions->GetOptionVal(IOPTION_FILENAMEDISPLAY) != 0);

	// Set layout options.
	int sortInfo = (int)m_pOptions->GetOptionVal(IOPTION_USERSORTING);
	GetUsersPane()->m_pListCtrl->SetSortColumn(sortInfo & 0x0F, sortInfo >> 4);

	return CFrameWnd::OnCreateClient(lpcs, pContext);
}

CStatusView* CMainFrame::GetStatusPane()
{
	return m_pStatusPane;
}

CUsersView* CMainFrame::GetUsersPane()
{
	return m_pUsersPane;
}

void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
	if (m_wndStatusBar.GetSafeHwnd())
	{
		if (nType!=SIZE_MAXIMIZED)
			m_wndStatusBar.SetPaneInfo(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDLED),ID_INDICATOR_SENDLED,SBPS_NOBORDERS,0);
		else
			m_wndStatusBar.SetPaneInfo(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDLED),ID_INDICATOR_SENDLED,SBPS_NOBORDERS,10);
	}

	if (m_wndSplitter.GetSafeHwnd())
	{
		//Hide the queue if visible
		m_wndSplitter.HideRow(1, 0);
	}
	//Now only the main splitter gets resized
	CFrameWnd::OnSize(nType, cx, cy);
	if (m_wndSplitter.GetSafeHwnd())
	{
		//Restore the queue
		m_wndSplitter.ShowRow(1);
	}

	if (m_wndStatusBar.GetSafeHwnd())
	{
		RECT rc;

		m_wndStatusBar.GetItemRect(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVLED), &rc);

		// Reposition the first LED correctly!
		m_RecvLed.SetWindowPos(&wndTop, rc.left, rc.top+1, rc.right - rc.left,
			rc.bottom - rc.top, 0);

		m_wndStatusBar.GetItemRect(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDLED), &rc);

		// Reposition the second LED correctly!
		m_SendLed.SetWindowPos(&wndTop, rc.left, rc.top+1, rc.right - rc.left,
				rc.bottom - rc.top, 0);
	}
}

void CMainFrame::OnClose()
{
	CFrameWnd::OnClose();
}

void CMainFrame::OnEditSettings()
{
	if (m_nEdit)
	{
		MessageBeep(MB_OK);
		return;
	}
	m_nEdit |= 0x04;
	SendCommand(5, 0, 0);
	ShowStatus(_T("Retrieving settings, please wait..."), 0);
}

void CMainFrame::OnActive()
{
	if (m_nServerState & STATE_ONLINE && !(m_nServerState & STATE_MASK_GOOFFLINE))
	{
		if (!GetUsersPane()->m_pListCtrl->GetItemCount())
		{
			if (AfxMessageBox(_T("Do you really want to take the server offline?"), MB_YESNO | MB_ICONQUESTION) != IDYES)
				return;
			int nServerState = m_nServerState | STATE_GOOFFLINE_NOW;
			unsigned char buffer[2];
			buffer[0] = nServerState / 256;
			buffer[1] = nServerState % 256;
			SendCommand(2, buffer, 2);
			ShowStatus(_T("Server is going offline..."), 0);
			return;
		}
		else
		{
			COfflineAskDlg dlg;
			if (dlg.DoModal() != IDOK)
				return;
			if (dlg.m_nRadio == 2)
			{
				int nServerState = m_nServerState | STATE_GOOFFLINE_WAITTRANSFER;
				unsigned char buffer[2];
				buffer[0] = nServerState / 256;
				buffer[1] = nServerState % 256;
				SendCommand(2, buffer, 2);
				ShowStatus(_T("Server is going offline..."), 0);
				return;
			}
			if (dlg.m_nRadio == 1)
			{
				int nServerState = m_nServerState | STATE_GOOFFLINE_LOGOUT;
				unsigned char buffer[2];
				buffer[0] = nServerState / 256;
				buffer[1] = nServerState % 256;
				SendCommand(2, buffer, 2);
				ShowStatus(_T("Server is going offline..."), 0);
				return;
			}
			else
			{
				int nServerState = m_nServerState | STATE_GOOFFLINE_NOW;
				unsigned char buffer[2];
				buffer[0] = nServerState / 256;
				buffer[1] = nServerState % 256;
				SendCommand(2, buffer, 2);
				ShowStatus(_T("Server is going offline..."), 0);
				return;
			}
		}
	}
	else
	{
		int nServerState = 1 + (m_nServerState & STATE_LOCKED);
		unsigned char buffer[2];
		buffer[0] = nServerState / 256;
		buffer[1] = nServerState % 256;
		SendCommand(2, buffer, 2);
	}
}

void CMainFrame::OnUpdateActive(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected());
	pCmdUI->SetCheck(m_nServerState & STATE_ONLINE && !(m_nServerState & STATE_MASK_GOOFFLINE));
}

void CMainFrame::OnSysCommand(UINT nID, LPARAM lParam)
{
	CFrameWnd::OnSysCommand(nID, lParam);
	if (nID == SC_MINIMIZE)
		ShowWindow(SW_HIDE);
	else if (nID == SC_RESTORE)
		ShowWindow(SW_SHOW);
}

//// SetupTrayIcon /////////////////////////////////////////////////////
// If we're minimized, create an icon in the systray.  Otherwise, remove
// the icon, if one is present.

void CMainFrame::SetupTrayIcon()
{
	m_TrayIcon.Create(0, nTrayNotificationMsg_, _T("FileZilla Server"),
		0, IDR_SYSTRAY_MENU);
	m_TrayIcon.SetIcon(IDI_UNKNOWN);
}

//// SetupTaskBarButton ////////////////////////////////////////////////
// Show or hide the taskbar button for this app, depending on whether
// we're minimized right now or not.

void CMainFrame::OnTrayExit()
{
	if (!m_bQuit)
		OnClose();
}

void CMainFrame::OnTrayRestore()
{
	ShowWindow(SW_RESTORE);
	ShowWindow(SW_SHOW);
}

void CMainFrame::SetIcon()
{
	if (!m_pAdminSocket || !m_pAdminSocket->IsConnected())
	{
		m_TrayIcon.StopAnimation();
		m_TrayIcon.SetIcon(IDI_UNKNOWN);
	}
	else if (!(m_nServerState & STATE_ONLINE) || m_nServerState & STATE_MASK_GOOFFLINE)
	{
		if (!GetUsersPane()->m_pListCtrl->GetItemCount())
		{
			m_TrayIcon.StopAnimation();
			m_TrayIcon.SetIcon(IDI_RED);
		}
		else
		{
			m_TrayIcon.SetIconList(IDI_GREEN, IDI_RED);
			m_TrayIcon.Animate(500);
		}
	}
	else if (m_nServerState & STATE_LOCKED)
	{
		if (GetUsersPane()->m_pListCtrl->GetItemCount())
		{
			m_TrayIcon.SetIconList(IDI_GREEN, IDI_YELLOW);
			m_TrayIcon.Animate(300);
		}
		else
		{
			m_TrayIcon.SetIconList(IDI_YELLOW, IDI_RED);
			m_TrayIcon.Animate(500);
		}

	}
	else
	{
		m_TrayIcon.StopAnimation();
		m_TrayIcon.SetIcon(GetUsersPane()->m_pListCtrl->GetItemCount()?IDI_GREEN:IDI_YELLOW);
	}

}

void CMainFrame::OnLock()
{
	if (!(m_nServerState & STATE_ONLINE) || m_nServerState & STATE_MASK_GOOFFLINE)
		return;
	if (m_nServerState & STATE_LOCKED)
	{
		int nServerState = m_nServerState & ~STATE_LOCKED;
		unsigned char buffer[2];
		buffer[0] = nServerState / 256;
		buffer[1] = nServerState % 256;
		SendCommand(2, buffer, 2);
	}
	else
	{
		if (AfxMessageBox(_T("Do you really want to lock the server? No new connenctions will be accepted while locked."), MB_YESNO|MB_ICONQUESTION)!=IDYES)
			return;
		int nServerState = m_nServerState | STATE_LOCKED;
		unsigned char buffer[2];
		buffer[0] = nServerState / 256;
		buffer[1] = nServerState % 256;
		SendCommand(2, buffer, 2);
		ShowStatus("Server locked", 0);
	}
}

void CMainFrame::OnUpdateLock(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected() && m_nServerState & STATE_ONLINE && !(m_nServerState & STATE_MASK_GOOFFLINE));
	pCmdUI->SetCheck((m_nServerState & STATE_LOCKED) ? 1 : 0);

}

CString FormatSpeed(__int64 diff, const int span)
{
	diff = (__int64)((double)diff * 1000 / span);

	CString str = _T("");
	CString digit;

	int shift = 0;
	while (diff >= 10000)
	{
		diff /= 10;
		shift++;
	}

	while (diff)
	{
		digit = (TCHAR)('0' + static_cast<TCHAR>(diff % 10));
		str = digit + str;
		diff /= 10;
	}

	if (str == _T(""))
		str = _T("0");

	if (shift % 3)
		str = str.Left((shift % 3) + 1) + "," + str.Right(str.GetLength() - (shift % 3) - 1);
	shift += 2;
	shift /= 3;
	if (!shift)
		str += _T(" B/s");
	else if (shift == 1)
		str += _T(" KB/s");
	else if (shift == 2)
		str += _T(" MB/s");
	else if (shift == 3)
		str += _T(" GB/s");
	else if (shift == 4)
		str += _T(" TB/s");
	else
		str = _T("n/a"); //If this happens, you really have a fast connection
	return str;
}

void CMainFrame::OnTimer(UINT_PTR nIDEvent)
{
	if (!nIDEvent)
		return;
	else if (nIDEvent == m_nTimerID)
	{
		SendCommand(8);
		m_TrayIcon.RefreshIcon();
	}
	else if (nIDEvent == m_nRateTimerID)
	{
		const int span = GetTickCount() - m_lastchecktime;
		m_lastchecktime=GetTickCount();

		__int64 diff = m_nSendCount - m_nOldSendCount;
		m_nOldSendCount = m_nSendCount;

		if (m_lastwritediff && diff)
		{
			__int64 tmp = diff;
			diff = (diff + m_lastwritediff) / 2;
			m_lastwritediff = tmp;
		}
		else
			m_lastwritediff = diff;

		CString writeSpeed = FormatSpeed(diff, span);
		SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDRATE), writeSpeed);

		diff = m_nRecvCount - m_nOldRecvCount;
		m_nOldRecvCount = m_nRecvCount;

		if (m_lastreaddiff && diff)
		{
			__int64 tmp = diff;
			diff = (diff + m_lastreaddiff) / 2;
			m_lastreaddiff = tmp;
		}
		else
			m_lastreaddiff = diff;

		CString readSpeed = FormatSpeed(diff, span);
		SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVRATE), readSpeed);
	}
	else if (nIDEvent == m_nReconnectTimerID)
	{
		KillTimer(m_nReconnectTimerID);
		m_nReconnectTimerID = 0;

		if (m_pAdminSocket)
			return;

		m_pAdminSocket = new CAdminSocket(this);
		ShowStatus("Reconnecting to server...", 0);
		DoConnect();
	}

	CFrameWnd::OnTimer(nIDEvent);
}

void CMainFrame::SetStatusbarText(int nIndex,CString str)
{
	m_wndStatusBar.GetStatusBarCtrl().SetText(str,nIndex,0);
	HFONT hFont = (HFONT)m_wndStatusBar.SendMessage(WM_GETFONT);
	if (str=="")
	{
		str.LoadString(m_wndStatusBar.GetItemID(nIndex));
	}
	CClientDC dcScreen(NULL);
	HGDIOBJ hOldFont = NULL;
	if (hFont != NULL)
	hOldFont = dcScreen.SelectObject(hFont);
	int cx=dcScreen.GetTextExtent(str).cx;
	int cxold;
	unsigned int nID,nStyle;
	m_wndStatusBar.GetPaneInfo(nIndex,nID,nStyle,cxold);
	if (cx!=cxold)
	{
		if (cx<cxold)
			cx=cxold;
		m_wndStatusBar.SetPaneInfo(nIndex,nID,nStyle,cx);

	}
	if (hOldFont != NULL)
		dcScreen.SelectObject(hOldFont);

}

void CMainFrame::OnMenuEditUsers()
{
	if (m_nEdit)
	{
		MessageBeep(MB_OK);
		return;
	}
	m_nEdit |= 1;
	SendCommand(6, 0, 0);
	ShowStatus(_T("Retrieving account settings, please wait..."), 0);
}

void CMainFrame::OnMenuEditGroups()
{
	if (m_nEdit)
	{
		MessageBeep(MB_OK);
		return;
	}
	m_nEdit |= 2;
	SendCommand(6, 0, 0);
	ShowStatus(_T("Retrieving account settings, please wait..."), 0);
}

void CMainFrame::ShowStatus(const CString& status, int nType)
{
	CStatusView *view = GetStatusPane();
	view->ShowStatus(status, nType);
}

void CMainFrame::ShowStatusRaw(const char *status, int nType)
{
#ifdef _UNICODE
	CString msg(ConvFromNetwork(status));
#else
	CString msg(ConvToLocal(ConvFromNetwork(status)));
#endif
	ShowStatus(msg, nType);
}

void CMainFrame::ParseReply(int nReplyID, unsigned char *pData, int nDataLength)
{
	switch(nReplyID)
	{
	case 0:
		{
			ShowStatus(_T("Logged on"), 0);
			SendCommand(2);
			unsigned char buffer = USERCONTROL_GETLIST;
			SendCommand(3, &buffer, 1);
		}
		break;
	case 1:
		{
			char *pBuffer = new char[nDataLength];
			memcpy(pBuffer, pData+1, nDataLength-1);
			pBuffer[nDataLength-1] = 0;
			ShowStatusRaw(pBuffer, *pData);
			delete [] pBuffer;
		}
		break;
	case 2:
		m_nServerState = *pData*256 + pData[1];
		SetIcon();
		break;
	case 3:
		{
			if (nDataLength<2)
			{
				ShowStatus(_T("Protocol error: Unexpected data length"), 1);
				return;
			}
			else if (!GetUsersPane()->m_pListCtrl->ParseUserControlCommand(pData, nDataLength))
				ShowStatus(_T("Protocol error: Invalid data"), 1);
		}
		break;
	case 5:
		if (nDataLength == 1)
		{
			if (*pData == 0)
				ShowStatus(_T("Done sending settings."), 0);
			else if (*pData == 1)
				ShowStatus(_T("Could not change settings"), 1);
			break;
		}
		ShowStatus(_T("Done retrieving settings"), 0);
		if (nDataLength<2)
			ShowStatus(_T("Protocol error: Unexpected data length"), 1);
		else
		{
			if ((m_nEdit & 0x1C) == 0x04)
			{
				m_pOptionsDlg = new COptionsDlg(m_pOptions, m_pAdminSocket->IsLocal());
				m_nEdit |= 0x08;
				if (!m_pOptionsDlg->Init(pData, nDataLength))
				{
					ShowStatus(_T("Protocol error: Invalid data"), 1);
					delete m_pOptionsDlg;
					m_pOptionsDlg = 0;
					m_nEdit = 0;
				}
				else if (!PostMessage(WM_APP))
				{
					ShowStatus(_T("Can't send window message"), 1);
					delete m_pOptionsDlg;
					m_pOptionsDlg = 0;
					m_nEdit = 0;
				}
			}
		}
		break;
	case 6:
		if (nDataLength == 1)
		{
			if (*pData == 0)
				ShowStatus(_T("Done sending account settings."), 0);
			else if (*pData == 1)
				ShowStatus(_T("Could not change account settings"), 1);
			break;
		}
		ShowStatus(_T("Done retrieving account settings"), 0);
		if (nDataLength<2)
			ShowStatus(_T("Protocol error: Unexpected data length"), 1);
		else
		{
			if ((m_nEdit & 0x19) == 0x01)
			{
				m_pUsersDlg = new CUsersDlg(this, m_pAdminSocket->IsLocal());
				m_nEdit |= 0x08;
				if (!m_pUsersDlg->Init(pData, nDataLength))
				{
					ShowStatus(_T("Protocol error: Invalid data"), 1);
					delete m_pUsersDlg;
					m_pUsersDlg = 0;
					m_nEdit = 0;
					break;
				}
				else if (!PostMessage(WM_APP))
				{
					ShowStatus(_T("Can't send window message"), 1);
					delete m_pUsersDlg;
					m_pUsersDlg = 0;
					m_nEdit = 0;
				}
			}
			if ((m_nEdit & 0x1A) == 0x02)
			{
				m_pGroupsDlg = new CGroupsDlg(this, m_pAdminSocket->IsLocal());
				m_nEdit |= 0x08;
				if (!m_pGroupsDlg->Init(pData, nDataLength))
				{
					ShowStatus(_T("Protocol error: Invalid data"), 1);
					delete m_pGroupsDlg;
					m_pGroupsDlg = 0;
					m_nEdit = 0;
					break;
				}
				else if (!PostMessage(WM_APP))
				{
					ShowStatus(_T("Can't send window message"), 1);
					delete m_pGroupsDlg;
					m_pGroupsDlg = 0;
					m_nEdit = 0;
				}
			}
		}
		break;
	case 8:
		break;
	default:
		{
			CString str;
			str.Format(_T("Protocol error: Unexpected reply id (%d)."), nReplyID);
			ShowStatus(str, 1);
			break;
		}
	}
}

void CMainFrame::ParseStatus(int nStatusID, unsigned char *pData, int nDataLength)
{
	switch(nStatusID)
	{
	case 1:
		{
			char *pBuffer = new char[nDataLength];
			memcpy(pBuffer, pData+1, nDataLength-1);
			pBuffer[nDataLength-1] = 0;
			ShowStatusRaw(pBuffer, *pData);
			delete [] pBuffer;
		}
		break;
	case 2:
		m_nServerState = *pData*256 + pData[1];
		SetIcon();
		break;
	case 3:
		{
			if (nDataLength<2)
			{
				ShowStatus(_T("Protocol error: Unexpected data length"), 1);
				return;
			}
			else if (!GetUsersPane()->m_pListCtrl->ParseUserControlCommand(pData, nDataLength))
				ShowStatus(_T("Protocol error: Invalid data"), 1);
		}
		break;
	case 4:
		{
			if (nDataLength < 10)
			{
				ShowStatus(_T("Protocol error: Unexpected data length"), 1);
				return;
			}

			CString msg;

			char *buffer = new char[nDataLength - 9 + 1];
			unsigned char *p = pData + 9;
			char *q = buffer;
			int pos = 0;
			while ((pos + 9) < nDataLength)
			{
				if (*p == '-')
				{
					*q = 0;
					msg = ConvFromNetwork(buffer);
					q = buffer;

					DWORD timeHigh = GET32(pData + 1);
					DWORD timeLow = GET32(pData + 5);

					FILETIME fFileTime;
					fFileTime.dwHighDateTime = timeHigh;
					fFileTime.dwLowDateTime = timeLow;

					SYSTEMTIME sFileTime;
					FileTimeToSystemTime(&fFileTime, &sFileTime);

					TCHAR datetime[200];
					int res = GetDateFormat(
							LOCALE_USER_DEFAULT,	// locale for which date is to be formatted
							DATE_SHORTDATE,			// flags specifying function options
							&sFileTime,				// date to be formatted
							0,						// date format string
							datetime,				// buffer for storing formatted string
							200						// size of buffer
						);

					if (res)
					{
						msg += datetime;
						msg += ' ';
					}

					res = GetTimeFormat(
							LOCALE_USER_DEFAULT,	// locale for which date is to be formatted
							TIME_FORCE24HOURFORMAT,	// flags specifying function options
							&sFileTime,				// date to be formatted
							0,						// date format string
							datetime,				// buffer for storing formatted string
							200						// size of buffer
						);

					if (res)
					{
						msg += datetime;
						msg += ' ';
					}

					if ((nDataLength - pos - 9) > 0)
					{
						memcpy(q, p, nDataLength - pos - 9);
						q += nDataLength - pos - 9;
					}
					break;
				}
				else
					*(q++) = *(p++);

				pos++;
			}
			*q = 0;
			if (q != buffer)
				msg += ConvFromNetwork(buffer);
			if (msg != _T(""))
				ShowStatus(msg, *pData);
			delete [] buffer;
		}
		break;
	case 7:
		if (nDataLength != 5)
			ShowStatus(_T("Protocol error: Invalid data"), 1);
		else
		{
			int nType = *pData;
			int size = (int)GET32(pData + 1);

			if (!nType)
			{
				m_nRecvCount += size;
				m_RecvLed.Ping(100);
				CString str;
				str.Format(_T("%s bytes received"), makeUserFriendlyString(m_nRecvCount).GetString());
				SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_RECVCOUNT), str);
			}
			else
			{
				m_nSendCount += size;
				m_SendLed.Ping(100);
				CString str;
				str.Format(_T("%s bytes sent"), makeUserFriendlyString(m_nSendCount).GetString());
				SetStatusbarText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_SENDCOUNT), str);
			}

		}
		break;
	default:
		{
			CString str;
			str.Format(_T("Protocol error: Unexpected status id (%d)."), nStatusID);
			ShowStatus(str, 1);
		}
		break;

	}
}

BOOL CMainFrame::SendCommand(int nType)
{
	if (!m_pAdminSocket)
		return FALSE;
	if (!m_pAdminSocket->SendCommand(nType))
	{
		CloseAdminSocket();
		ShowStatus("Error: Connection to server lost...", 1);
		return FALSE;
	}
	return TRUE;
}

BOOL CMainFrame::SendCommand(int nType, void *pData, int nDataLength)
{
	if (!m_pAdminSocket)
		return FALSE;
	if (!m_pAdminSocket->SendCommand(nType, pData, nDataLength))
	{
		CloseAdminSocket();
		ShowStatus("Error: Connection to server lost...", 1);
		return FALSE;
	}
	return TRUE;
}

void CMainFrame::CloseAdminSocket(bool shouldReconnect /*=true*/)
{
	if (m_pAdminSocket)
	{
		m_pAdminSocket->DoClose();
		delete m_pAdminSocket;
		m_pAdminSocket = NULL;
		SetIcon();

		CString title;
		title.LoadString(IDR_MAINFRAME);
		SetWindowText(title + _T(" (disconnected)"));
	}
	m_nEdit = 0;

	if (!shouldReconnect)
	{
		if (m_nReconnectTimerID)
		{
			KillTimer(m_nReconnectTimerID);
			m_nReconnectTimerID = 0;
		}
	}
	else
	{
		if (!m_nReconnectTimerID)
		{
			m_nReconnectCount++;
			if (m_nReconnectCount < 15)
			{
				ShowStatus("Trying to reconnect in 5 seconds", 0);
				m_nReconnectTimerID = SetTimer(7779, 5000, 0);
			}
			else
				m_nReconnectCount = 0;
		}
	}
}

void CMainFrame::OnFileConnect()
{
	if (m_nReconnectTimerID)
	{
		KillTimer(m_nReconnectTimerID);
		m_nReconnectTimerID = 0;
	}
	if (m_pAdminSocket)
		if (AfxMessageBox(_T("Do you really want to close the current connection?"), MB_ICONQUESTION|MB_YESNO) != IDYES)
			return;
	CConnectDialog dlg(m_pOptions);
	if (dlg.DoModal() == IDOK)
	{
		CloseAdminSocket(false);
		m_pAdminSocket = new CAdminSocket(this);
		ShowStatus("Connecting to server...", 0);
		DoConnect();
	}
}

void CMainFrame::OnFileDisconnect()
{
	CloseAdminSocket(false);
}

void CMainFrame::OnUpdateFileDisconnect(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket?TRUE:FALSE);
}

void CMainFrame::OnUpdateEditSettings(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected());
}

void CMainFrame::OnUpdateMenuEditUsers(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected());
}

void CMainFrame::OnUpdateMenuEditGroups(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected());
}

void CMainFrame::OnUpdateUsers(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected());
}

void CMainFrame::OnUpdateGroups(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(m_pAdminSocket && m_pAdminSocket->IsConnected());
}

// this function gets called whenever the user decides to quit the app
// (by pressing the 'x' for example
void CMainFrame::OnDestroy()
{
	m_pOptions->SetOption(IOPTION_USERSORTING, GetUsersPane()->m_pListCtrl->GetSortColumn() + (GetUsersPane()->m_pListCtrl->GetSortDirection() << 4));
	CloseAdminSocket(false);
	CFrameWnd::OnDestroy();
}

BOOL CMainFrame::OnEraseBkgnd(CDC* pDC)
{
	return TRUE;
}

LRESULT CMainFrame::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	if (message == WM_APP)
	{
		if ((m_nEdit & 0x1C) == 0x0C)
		{
			m_nEdit |= 0x10;
			if (m_pOptionsDlg->Show())
			{
				char *pBuffer;
				DWORD dwBufferLength;
				if (m_pOptionsDlg->GetAsCommand(&pBuffer, &dwBufferLength))
				{
					SendCommand(5, pBuffer, dwBufferLength);
					ShowStatus(_T("Sending settings, please wait..."), 0);
					delete [] pBuffer;
				}
				else
					ShowStatus(_T("Could not serialize settings, too much data."), 1);
			}
			delete m_pOptionsDlg;
			m_pOptionsDlg = 0;
			m_nEdit = 0;
		}
		else if ((m_nEdit & 0x19) == 0x09)
		{
			m_nEdit |= 0x10;
			if (m_pUsersDlg->DoModal() == IDOK)
			{
				char *pBuffer;
				DWORD dwBufferLength;
				if (m_pUsersDlg->GetAsCommand(&pBuffer, &dwBufferLength))
				{
					SendCommand(6, pBuffer, dwBufferLength);
					ShowStatus(_T("Sending account settings, please wait..."), 0);
					delete [] pBuffer;
				}
			}
			delete m_pUsersDlg;
			m_pUsersDlg = 0;
			m_nEdit = 0;
		}
		else if ((m_nEdit & 0x1A) == 0x0A)
		{
			m_nEdit |= 0x10;
			if (m_pGroupsDlg->DoModal() == IDOK)
			{
				char *pBuffer;
				DWORD dwBufferLength;
				if (m_pGroupsDlg->GetAsCommand(&pBuffer, &dwBufferLength))
				{
					SendCommand(6, pBuffer, dwBufferLength);
					ShowStatus(_T("Sending account settings, please wait..."), 0);
					delete [] pBuffer;
				}
			}
			delete m_pGroupsDlg;
			m_pGroupsDlg = 0;
			m_nEdit = 0;
		}
	}
	else if (message == WM_APP + 1)
		OnAdminInterfaceClosed();

	return CFrameWnd::DefWindowProc(message, wParam, lParam);
}

void CMainFrame::OnAdminInterfaceConnected()
{
	m_nReconnectCount = 0;

	CString title;
	title.LoadString(IDR_MAINFRAME);
	CString ip;
	UINT port;
	if (m_pAdminSocket->GetPeerName(ip, port))
	{
		if (ip.Find(':') != -1)
			ip = GetIPV6ShortForm(ip);
		SetWindowText(title + _T(" (") + ip + _T(")"));
	}
}

void CMainFrame::OnAdminInterfaceClosed()
{
	if (m_pAdminSocket && m_pAdminSocket->IsClosed())
	{
		CloseAdminSocket();
	}
}

void CMainFrame::OnDisplayLogicalNames()
{
	GetUsersPane()->m_pListCtrl->SetDisplayPhysicalNames(false);
	m_pOptions->SetOption(IOPTION_FILENAMEDISPLAY, 0);
}

void CMainFrame::OnDisplayPhysicalNames()
{
	GetUsersPane()->m_pListCtrl->SetDisplayPhysicalNames(true);
	m_pOptions->SetOption(IOPTION_FILENAMEDISPLAY, 1);
}

void CMainFrame::OnUpdateDisplayLogicalNames(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(!GetUsersPane()->m_pListCtrl->GetDisplayPhysicalNames());
}

void CMainFrame::OnUpdateDisplayPhysicalNames(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(GetUsersPane()->m_pListCtrl->GetDisplayPhysicalNames());
}

void CMainFrame::OnDisplaySortMenu()
{
	// load and display popup menu
	CMenu menu;
	menu.LoadMenu(IDR_SORTMENU);
	CMenu* pPopup = menu.GetSubMenu(0);
	ASSERT(pPopup);

	CRect rc;
	m_wndUserListToolBar.GetItemRect(m_wndUserListToolBar.CommandToIndex(ID_USERLISTTOOLBAR_SORT), &rc);
	m_wndUserListToolBar.ClientToScreen(&rc);

	pPopup->TrackPopupMenu( TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_VERTICAL,
		rc.left, rc.bottom, this, &rc);
}

void CMainFrame::OnToolbarDropDown(NMHDR* pnmh, LRESULT* plRes)
{
	NMTOOLBAR* pnmtb = (NMTOOLBAR*)pnmh;
	if (pnmtb->iItem == ID_USERLISTTOOLBAR_SORT)
		OnDisplaySortMenu();
}

void CMainFrame::OnDisplaySortByUserid()
{
	GetUsersPane()->m_pListCtrl->SetSortColumn(0);
}

void CMainFrame::OnDisplaySortByAccount()
{
	GetUsersPane()->m_pListCtrl->SetSortColumn(1);
}

void CMainFrame::OnDisplaySortByIP()
{
	GetUsersPane()->m_pListCtrl->SetSortColumn(2);
}

void CMainFrame::OnUpdateDisplaySortByUserid(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(GetUsersPane()->m_pListCtrl->GetSortColumn() == 0);
}

void CMainFrame::OnUpdateDisplaySortByAccount(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(GetUsersPane()->m_pListCtrl->GetSortColumn() == 1);
}

void CMainFrame::OnUpdateDisplaySortByIP(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(GetUsersPane()->m_pListCtrl->GetSortColumn() == 3);
}

void CMainFrame::DoConnect()
{
	int family;
	if (!GetIPV6LongForm(m_pOptions->GetOption(IOPTION_LASTSERVERADDRESS)).IsEmpty())
		family = AF_INET6;
	else
		family = AF_INET;

	m_pAdminSocket->Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, family);

	m_pAdminSocket->m_Password = m_pOptions->GetOption(IOPTION_LASTSERVERPASS);
	if (!m_pAdminSocket->Connect(m_pOptions->GetOption(IOPTION_LASTSERVERADDRESS), (UINT)m_pOptions->GetOptionVal(IOPTION_LASTSERVERPORT)) && WSAGetLastError() != WSAEWOULDBLOCK)
	{
		ShowStatus(_T("Error, could not connect to server"), 1);
		CloseAdminSocket();
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import getpass
from time import sleep

from sqlalchemy import Column, Index, Integer, String, and_, or_
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm.session import make_transient

from airflow.configuration import conf
from airflow import executors, models
from airflow.exceptions import (
    AirflowException,
)
from airflow.models.base import Base, ID_LEN
from airflow.settings import Stats
from airflow.utils import helpers, timezone
from airflow.utils.db import create_session, provide_session
from airflow.utils.helpers import convert_camel_to_snake
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.utils.net import get_hostname
from airflow.utils.sqlalchemy import UtcDateTime
from airflow.utils.state import State

class BaseJob(Base, LoggingMixin):
    """
    Abstract class to be derived for jobs. Jobs are processing items with state
    and duration that aren't task instances. For instance a BackfillJob is
    a collection of task instance runs, but should have its own state, start
    and end time.
    """

    __tablename__ = "job"

    id = Column(Integer, primary_key=True)
    dag_id = Column(String(ID_LEN),)
    state = Column(String(20))
    job_type = Column(String(30))
    start_date = Column(UtcDateTime())
    end_date = Column(UtcDateTime())
    latest_heartbeat = Column(UtcDateTime())
    executor_class = Column(String(500))
    hostname = Column(String(500))
    unixname = Column(String(1000))

    __mapper_args__ = {
        'polymorphic_on': job_type,
        'polymorphic_identity': 'BaseJob'
    }

    __table_args__ = (
        Index('job_type_heart', job_type, latest_heartbeat),
        Index('idx_job_state_heartbeat', state, latest_heartbeat),
    )
    heartrate = conf.getfloat('scheduler', 'JOB_HEARTBEAT_SEC')

    def __init__(
            self,
            executor=None,
            heartrate=None,
            *args, **kwargs):
        self.hostname = get_hostname()
        self.executor = executor or executors.get_default_executor()
        self.executor_class = executor.__class__.__name__
        self.start_date = timezone.utcnow()
        self.latest_heartbeat = timezone.utcnow()
        if heartrate is not None:
            self.heartrate = heartrate
        self.unixname = getpass.getuser()
        self.max_tis_per_query = conf.getint('scheduler', 'max_tis_per_query')
        super(BaseJob, self).__init__(*args, **kwargs)

    @classmethod
    @provide_session
    def most_recent_job(cls, session=None):
        """
        Return the most recent job of this type, if any, based on last
        heartbeat received.

        This method should be called on a subclass (i.e. on SchedulerJob) to
        return jobs of that type.

        :param session: Database session
        :rtype: BaseJob or None
        """
        return session.query(cls).order_by(cls.latest_heartbeat.desc()).limit(1).first()

    def is_alive(self, grace_multiplier=2.1):
        """
        Is this job currently alive.

        We define alive as in a state of RUNNING, and having sent a heartbeat
        within a multiple of the heartrate (default of 2.1)

        :param grace_multiplier: multiplier of heartrate to require heart beat
            within
        :type grace_multiplier: number
        :rtype: boolean
        """
        return (
            self.state == State.RUNNING and
            (timezone.utcnow() - self.latest_heartbeat).total_seconds() < self.heartrate * grace_multiplier
        )

    @provide_session
    def kill(self, session=None):
        job = session.query(BaseJob).filter(BaseJob.id == self.id).first()
        job.end_date = timezone.utcnow()
        try:
            self.on_kill()
        except Exception as e:
            self.log.error('on_kill() method failed: %s', str(e))
        session.merge(job)
        session.commit()
        raise AirflowException("Job shut down externally.")

    def on_kill(self):
        """
        Will be called when an external kill command is received
        """

    def heartbeat_callback(self, session=None):
        pass

    def heartbeat(self):
        """
        Heartbeats update the job's entry in the database with a timestamp
        for the latest_heartbeat and allows for the job to be killed
        externally. This allows at the system level to monitor what is
        actually active.

        For instance, an old heartbeat for SchedulerJob would mean something
        is wrong.

        This also allows for any job to be killed externally, regardless
        of who is running it or on which machine it is running.

        Note that if your heartbeat is set to 60 seconds and you call this
        method after 10 seconds of processing since the last heartbeat, it
        will sleep 50 seconds to complete the 60 seconds and keep a steady
        heart rate. If you go over 60 seconds before calling it, it won't
        sleep at all.
        """
        previous_heartbeat = self.latest_heartbeat

        try:
            with create_session() as session:
                # This will cause it to load from the db
                session.merge(self)
                previous_heartbeat = self.latest_heartbeat

            if self.state == State.SHUTDOWN:
                self.kill()

            is_unit_test = conf.getboolean('core', 'unit_test_mode')
            if not is_unit_test:
                # Figure out how long to sleep for
                sleep_for = 0
                if self.latest_heartbeat:
                    seconds_remaining = self.heartrate - \
                        (timezone.utcnow() - self.latest_heartbeat)\
                        .total_seconds()
                    sleep_for = max(0, seconds_remaining)

                sleep(sleep_for)

            # Update last heartbeat time
            with create_session() as session:
                # Make the sesion aware of this object
                session.merge(self)
                self.latest_heartbeat = timezone.utcnow()
                session.commit()
                # At this point, the DB has updated.
                previous_heartbeat = self.latest_heartbeat

                self.heartbeat_callback(session=session)
                self.log.debug('[heartbeat]')
        except OperationalError:
            Stats.incr(
                convert_camel_to_snake(self.__class__.__name__) + '_heartbeat_failure', 1,
                1)
            self.log.exception("%s heartbeat got an exception", self.__class__.__name__)
            # We didn't manage to heartbeat, so make sure that the timestamp isn't updated
            self.latest_heartbeat = previous_heartbeat

    def run(self):
        Stats.incr(self.__class__.__name__.lower() + '_start', 1, 1)
        # Adding an entry in the DB
        with create_session() as session:
            self.state = State.RUNNING
            session.add(self)
            session.commit()
            id_ = self.id
            make_transient(self)
            self.id = id_

            try:
                self._execute()
                # In case of max runs or max duration
                self.state = State.SUCCESS
            except SystemExit:
                # In case of ^C or SIGTERM
                self.state = State.SUCCESS
            except Exception:
                self.state = State.FAILED
                raise
            finally:
                self.end_date = timezone.utcnow()
                session.merge(self)
                session.commit()

        Stats.incr(self.__class__.__name__.lower() + '_end', 1, 1)

    def _execute(self):
        raise NotImplementedError("This method needs to be overridden")

    @provide_session
    def reset_state_for_orphaned_tasks(self, filter_by_dag_run=None, session=None):
        """
        This function checks if there are any tasks in the dagrun (or all)
        that have a scheduled state but are not known by the
        executor. If it finds those it will reset the state to None
        so they will get picked up again.
        The batch option is for performance reasons as the queries are made in
        sequence.

        :param filter_by_dag_run: the dag_run we want to process, None if all
        :type filter_by_dag_run: airflow.models.DagRun
        :return: the TIs reset (in expired SQLAlchemy state)
        :rtype: list[airflow.models.TaskInstance]
        """
        from airflow.jobs.backfill_job import BackfillJob

        queued_tis = self.executor.queued_tasks
        # also consider running as the state might not have changed in the db yet
        running_tis = self.executor.running

        resettable_states = [State.SCHEDULED, State.QUEUED]
        TI = models.TaskInstance
        DR = models.DagRun
        if filter_by_dag_run is None:
            resettable_tis = (
                session
                .query(TI)
                .join(
                    DR,
                    and_(
                        TI.dag_id == DR.dag_id,
                        TI.execution_date == DR.execution_date))
                .filter(
                    DR.state == State.RUNNING,
                    DR.run_id.notlike(BackfillJob.ID_PREFIX + '%'),
                    TI.state.in_(resettable_states))).all()
        else:
            resettable_tis = filter_by_dag_run.get_task_instances(state=resettable_states,
                                                                  session=session)
        tis_to_reset = []
        # Can't use an update here since it doesn't support joins
        for ti in resettable_tis:
            if ti.key not in queued_tis and ti.key not in running_tis:
                tis_to_reset.append(ti)

        if len(tis_to_reset) == 0:
            return []

        def query(result, items):
            filter_for_tis = ([and_(TI.dag_id == ti.dag_id,
                                    TI.task_id == ti.task_id,
                                    TI.execution_date == ti.execution_date)
                               for ti in items])
            reset_tis = (
                session
                .query(TI)
                .filter(or_(*filter_for_tis), TI.state.in_(resettable_states))
                .with_for_update()
                .all())
            for ti in reset_tis:
                ti.state = State.NONE
                session.merge(ti)
            return result + reset_tis

        reset_tis = helpers.reduce_in_chunks(query,
                                             tis_to_reset,
                                             [],
                                             self.max_tis_per_query)

        task_instance_str = '\n\t'.join(
            [repr(x) for x in reset_tis])
        session.commit()

        self.log.info(
            "Reset the following %s TaskInstances:\n\t%s",
            len(reset_tis), task_instance_str
        )
        return reset_tis


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

using AutoMapper;
using AutoMapper.QueryableExtensions;

using JobMatcher.Data.Contracts;
using JobMatcher.Models;
using JobMatcher.Service.ViewModels;

namespace JobMatcher.Service.Controllers
{
    public class DislikeController : BaseController
    {
        public DislikeController(IJobMatcherData data)
            : base(data)
        {
        }

        [HttpGet]
        public IHttpActionResult Get()
        {
            var dislikes = this.data.Dislikes.All()
                .Where(x => !x.IsDeleted)
                .ToList();

            return this.Ok(dislikes);
        }

        [HttpPost]
        public IHttpActionResult Add(AddDislikeViewModel model)
        {
            if (model.JobSeekerProfileId == 0 && model.DislikeInitiatorType == ProfileType.JobSeeker)
            {
                model.JobSeekerProfileId =
                    this.data.JobSeekerProfiles.All().Where(x => !x.IsDeleted)
                        .First(x => x.UserId == this.CurrentUserId)
                        .JobSeekerProfileId;
            }

            if (model.RecruiterProfileId == 0 && model.DislikeInitiatorType == ProfileType.Recruiter)
            {
                model.RecruiterProfileId =
                    this.data.RecruiterProfiles.All().Where(x => !x.IsDeleted)
                        .First(x => x.UserId == this.CurrentUserId)
                        .RecruiterProfileId;
            }

            if (model.RecruiterProfileId == 0 || model.JobSeekerProfileId == 0)
            {
                return this.BadRequest("Id can't be 0.");
            }

            var existingDislike =
                this.data.Dislikes.All().Where(x => !x.IsDeleted)
                    .FirstOrDefault(
                        x =>
                            x.RecruiterProfileId == model.RecruiterProfileId &&
                            x.JobSeekerProfileId == model.JobSeekerProfileId &&
                            x.DislikeInitiatorType == model.DislikeInitiatorType);

            if (existingDislike == null)
            {
                var dislike = AutoMapper.Mapper.Map<Dislike>(model);
                dislike.JobOfferId = dislike.JobOfferId == 0 ? null : dislike.JobOfferId;
                dislike.CreatedOn = DateTime.Now;

                var existingLike =
                this.data.Likes.All().Where(x => !x.IsDeleted)
                    .FirstOrDefault(
                        x =>
                            x.RecruiterProfileId == model.RecruiterProfileId &&
                            x.JobSeekerProfileId == model.JobSeekerProfileId &&
                            x.LikeInitiatorType == model.DislikeInitiatorType &&
                            ((model.JobOfferId != 0 && x.JobOfferId == model.JobOfferId) || model.JobOfferId == 0));

                if (existingLike != null)
                {
                    this.data.Likes.Delete(existingLike);
                }

                this.data.Dislikes.Add(dislike);
                this.data.SaveChanges();

                model.Id = dislike.Id;

                this.data.SaveChanges();
                return Ok(dislike);
            }

            return this.BadRequest("You've already disliked that one.");
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

        <TITLE>Authorization Management Service Overview</TITLE>

        This document describes the source code of the CollectionSpace
        Authorization Management Service, a.k.a (Roles and Permissions Management)

        It includes the classes and interfaces for the following.

        - Java XML bindings for role, permission, roles_permissions, users_roles
        - Service side source including RESTful web service resources for role,
          permission, roles_permissions, users_roles and their persistence management


text:
set -eo pipefail

# Always run the cleanup script, regardless of the success of bouncing into
# the container.

function cleanup() {
    chmod +x "${KOKORO_GFILE_DIR}"/trampoline_cleanup.sh
    "${KOKORO_GFILE_DIR}"/trampoline_cleanup.sh
    echo -e "Trampoline cleanup";
}
trap cleanup EXIT

python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py"


text:
#include <cprocessing/cprocessing.hpp>
using namespace cprocessing;

/**
 * Logical Operators.
 *
 * The logical operators for AND (&&) and OR (||) are used to
 * combine simple relational statements into more complex expressions.
 * The NOT (!) operator is used to negate a boolean statement.
 */

void setup() {
    size(640, 360);
    background(126);
}

void draw() {
    boolean test = false;

    for (int i = 5; i <= height; i += 5) {
      // Logical AND
      stroke(0);
      if((i > 35) && (i < 100)) {
        line(width/4, i, width/2, i);
        test = false;
      }

      // Logical OR
      stroke(76);
      if ((i <= 35) || (i >= 100)) {
        line(width/2, i, width, i);
        test = true;
      }

      // Testing if a boolean value is "true"
      // The expression "if(test)" is equivalent to "if(test == true)"
      if (test) {
        stroke(0);
        point(width/3, i);
      }

      // Testing if a boolean value is "false"
      // The expression "if(!test)" is equivalent to "if(test == false)"
      if (!test) {
        stroke(255);
        point(width/4, i);
      }
    }
}


text:
import { IHandler, IEvents } from './event/registry';
export interface IMeta {
    owner?: Instance;
}
export declare class Instance {
    [index: number]: HTMLElement;
    length: number;
    events: IEvents;
    private meta;
    constructor(qry: string | HTMLElement, ctx?: Element, meta?: IMeta);
    get(key: number): HTMLElement;
    first(): Instance;
    find(qry: string): Instance;
    closest(qry: string): Instance;
    each(cb: (el: HTMLElement) => void): this;
    css(obj: {
        [index: string]: string;
    }): this;
    attr(obj: {
        [index: string]: string;
    } | string): string;
    hasClass(str: string): boolean;
    addClass(str: string): this;
    removeClass(str: string): this;
    toggleClass(str: string): this;
    on(ev: string, op1: string | IHandler, op2?: IHandler): this;
    off(ev: string): this;
    val(val?: string): string;
    text(val?: string): string;
    data(key: string, val?: string): string;
    html(val?: string): string;
    append(item: string | Node | HTMLElement): this;
    prepend(item: string | Node | HTMLElement): this;
    empty(): this;
    remove(): void;
    toArray(): HTMLElement[];
}
export declare namespace TSDom {
    type Init = (qry: string | HTMLElement, ctx?: Element, meta?: IMeta) => Instance;
    class Object extends Instance {
    }
}
declare const _default: (qry: string | HTMLElement, ctx?: HTMLElement) => Instance;
export default _default;


text:
package com.facebook.buck.jvm.java;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.model.Either;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;

import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class JavacOptionsTest {

  @Test
  public void buildsAreDebugByDefault() {
    JavacOptions options = createStandardBuilder().build();

    assertOptionFlags(options, hasItem("g"));
  }

  @Test
  public void productionBuildsCanBeEnabled() {
    JavacOptions options = createStandardBuilder()
        .setProductionBuild(true)
        .build();

    assertOptionFlags(options, not(hasItem("g")));
  }

  @Test
  public void testDoesNotSetBootclasspathByDefault() {
    JavacOptions options = createStandardBuilder().build();

    assertOptionsHasNoKey(options, "bootclasspath");
  }

  @Test
  public void canSetBootclasspath() {
    JavacOptions options = createStandardBuilder()
        .setBootclasspath("foo:bar")
        .build();

    assertOptionsHasKeyValue(options, "bootclasspath", "foo:bar");
  }

  @Test
  public void shouldSetTheAnnotationSource() {
    AnnotationProcessingParams params = new AnnotationProcessingParams.Builder()
        .addAllProcessors(Collections.singleton("processor"))
        .setProcessOnly(true)
        .build();

    JavacOptions options = createStandardBuilder()
        .setAnnotationProcessingParams(params)
        .build();

    assertOptionFlags(options, hasItem("proc:only"));
  }

  @Test
  public void shouldAddAllAddedAnnotationProcessors() {
    AnnotationProcessingParams params = new AnnotationProcessingParams.Builder()
        .addAllProcessors(Lists.newArrayList("myproc", "theirproc"))
        .setProcessOnly(true)
        .build();

    JavacOptions options = createStandardBuilder()
        .setAnnotationProcessingParams(params)
        .build();

    assertOptionsHasKeyValue(options, "processor", "myproc,theirproc");
  }

  @Test
  public void shouldSetSourceAndTargetLevels() {
    JavacOptions original = createStandardBuilder()
        .setSourceLevel("7")
        .setTargetLevel("5")
        .build();

    JavacOptions copy = JavacOptions.builder(original).build();
    assertOptionsHasKeyValue(copy, "source", "7");
    assertOptionsHasKeyValue(copy, "target", "5");
  }

  @Test
  public void shouldAddABootClasspathIfTheMapContainsOne() {
    JavacOptions options = createStandardBuilder()
        .setSourceLevel("5")
        .putSourceToBootclasspath("5", "some-magic.jar:also.jar")
        .build();

    assertOptionsHasKeyValue(options, "bootclasspath", "some-magic.jar:also.jar");
  }

  @Test
  public void shouldNotOverrideTheBootclasspathIfOneIsSet() {
    String expectedBootClasspath = "some-magic.jar:also.jar";
    JavacOptions options = createStandardBuilder()
        .setBootclasspath(expectedBootClasspath)
        .setSourceLevel("5")
        .putSourceToBootclasspath("5", "not-the-right-path.jar")
        .build();

    assertOptionsHasKeyValue(options, "bootclasspath", expectedBootClasspath);
  }

  @Test
  public void shouldNotOverrideTheBootclasspathIfSourceLevelHasNoMapping() {
    JavacOptions options = createStandardBuilder()
        .setBootclasspath("cake.jar")
        .setSourceLevel("6")
        .putSourceToBootclasspath("5", "some-magic.jar:also.jar")
        .build();

    assertOptionsHasKeyValue(options, "bootclasspath", "cake.jar");
  }

  @Test
  public void shouldCopyMapOfSourceLevelToBootclassPathWhenBuildingNewJavacOptions() {
    JavacOptions original = createStandardBuilder()
        .setSourceLevel("5")
        .putSourceToBootclasspath("5", "some-magic.jar:also.jar")
        .build();

    JavacOptions copy = JavacOptions.builder(original).build();
    assertOptionsHasKeyValue(copy, "bootclasspath", "some-magic.jar:also.jar");
  }

  @Test
  public void shouldIncoporateExtraOptionsInOutput() {
    JavacOptions options = createStandardBuilder()
        .addExtraArguments("-Xfoobar")
        .build();

    assertOptionsHasExtra(options, "-Xfoobar");
  }

  @Test
  public void externalJavacVersionIsReadFromStderrBecauseThatIsWhereJavacWritesIt()
      throws IOException {
    Platform current = Platform.detect();
    Assume.assumeTrue(current != Platform.WINDOWS && current != Platform.UNKNOWN);

    Path tempPath = Files.createTempFile("javac", "spoof");
    File tempFile = tempPath.toFile();
    tempFile.deleteOnExit();
    assertTrue(tempFile.setExecutable(true));
    // We could use the "-n" syntax, but that doesn't work on all variants of echo. Play it safe.
    Files.write(tempPath, "echo \"cover-version\" 1>&2".getBytes(UTF_8));

    JavacOptions options = createStandardBuilder()
        .setJavacPath(Either.ofLeft(tempPath))
        .build();

    Javac javac = options.getJavac();
    assertTrue(javac instanceof ExternalJavac);

    JavacVersion seen = javac.getVersion();
    assertEquals(seen.toString(), JavacVersion.of("cover-version"), seen);
  }

  @Test
  public void getInputs() {
    Path javacPath = Paths.get("javac");
    FakeSourcePath javacJarPath = new FakeSourcePath("javac_jar");

    JavacOptions options = createStandardBuilder()
        .setJavacPath(Either.ofLeft(javacPath))
        .setJavacJarPath(javacJarPath)
        .build();

    SourcePathResolver resolver = new SourcePathResolver(
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())
     );
    assertThat(
        options.getInputs(resolver),
        Matchers.containsInAnyOrder(javacJarPath));
  }

  private JavacOptions.Builder createStandardBuilder() {
    return JavacOptions.builderForUseInJavaBuckConfig()
        .setSourceLevel("5")
        .setTargetLevel("5");
  }

  private void assertOptionFlags(JavacOptions options, Matcher<Iterable<? super String>> matcher) {
    assertThat(visitOptions(options).flags, matcher);
  }

  private OptionAccumulator visitOptions(JavacOptions options) {
    OptionAccumulator optionsConsumer = new OptionAccumulator();
    options.appendOptionsTo(optionsConsumer, Functions.identity());
    return optionsConsumer;
  }

  private void assertOptionsHasNoKey(JavacOptions options, String optionKey) {
    assertThat(visitOptions(options).keyVals, not(hasKey(optionKey)));
  }

  private void assertOptionsHasExtra(JavacOptions options, String extra) {
    assertThat(visitOptions(options).extras, hasItem(extra));
  }

  private void assertOptionsHasKeyValue(
      JavacOptions options,
      String optionName,
      String optionValue) {
    assertThat(visitOptions(options).keyVals, hasEntry(optionName, optionValue));
  }
}


text:
package org.apache.gearpump.streaming.hadoop.lib.rotation

import java.time.Instant

import org.scalacheck.Gen
import org.scalatest.prop.PropertyChecks
import org.scalatest.{Matchers, PropSpec}
import org.apache.gearpump.Time.MilliSeconds

class FileSizeRotationSpec extends PropSpec with PropertyChecks with Matchers {

  val timestampGen = Gen.chooseNum[Long](0L, 1000L)
  val fileSizeGen = Gen.chooseNum[Long](1, Long.MaxValue)

  property("FileSize rotation rotates on file size") {
    forAll(timestampGen, fileSizeGen) { (timestamp: MilliSeconds, fileSize: Long) =>
      val rotation = new FileSizeRotation(fileSize)
      rotation.shouldRotate shouldBe false
      rotation.mark(Instant.ofEpochMilli(timestamp), rotation.maxBytes / 2)
      rotation.shouldRotate shouldBe false
      rotation.mark(Instant.ofEpochMilli(timestamp), rotation.maxBytes)
      rotation.shouldRotate shouldBe true
      rotation.rotate
      rotation.shouldRotate shouldBe false
    }
  }
}


text:
package spiffy

import (
	"fmt"
	"testing"

	assert "github.com/blendlabs/go-assert"
)

func TestInvocationErr(t *testing.T) {
	assert := assert.New(t)

	inv := &Invocation{err: fmt.Errorf("this is only a test")}
	assert.NotNil(inv.Err())
}

func TestInvocationLabels(t *testing.T) {
	assert := assert.New(t)

	inv := &Invocation{}
	inv = inv.WithLabel("test")
	assert.NotEmpty(inv.Label())
}

func TestInvocationPrepare(t *testing.T) {
	assert := assert.New(t)

	inv := &Invocation{err: fmt.Errorf("test")}
	_, err := inv.Prepare("select 'ok!'")
	assert.NotNil(err)
}


text:
package net.yorch.webocr;

import java.io.File;

public class Utils {
	/**
	 * OS Flag
	 */
	private static boolean IS_WINDOWS = false;

	/**
	 * Check Operating System
	 */
	public static void checkOS() {
		if (System.getProperty("os.name").contains("Windows"))
			Utils.IS_WINDOWS = true;
	}

	/**
	 * Validate if OS is Windows
	 *
	 * @return boolean
	 */
	public static boolean isWindows() {
		return Utils.IS_WINDOWS;
	}

	/**
	 * Gets tessdata path
	 *
	 * @return tessdata path
	 */
	public static String getTessPath() {
		File file = new File("");
		String currentPath = file.getAbsolutePath();
		String tessPath = currentPath + "\\tessdata\\";

		return tessPath;
	}

	/**
	 * Gets temporary directory
	 *
	 * @return temporary directory
	 */
	public static String getTempDir() {
		String tmpDir = "";

		if (Utils.IS_WINDOWS)
			tmpDir = System.getenv("TMP") + "\\";
		else
			tmpDir = "/tmp/";

		return tmpDir;
	}

	/**
	 * Gets extension of uploaded file
	 *
	 * @param contentType MIME content type
	 * @return extension
	 */
	public static String getExt(String contentType) {
		String[] aCt = contentType.split("/");
		String ext = aCt[1];

		return ext;
	}
}


text:
@interface UASQSChangeMessageVisibilityResponse : UASQSResponse

@end


text:
namespace juce
{

ResizableBorderComponent::Zone::Zone() noexcept {}
ResizableBorderComponent::Zone::Zone (int zoneFlags) noexcept  : zone (zoneFlags) {}
ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) noexcept  : zone (other.zone) {}

ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) noexcept
{
    zone = other.zone;
    return *this;
}

bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const noexcept      { return zone == other.zone; }
bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const noexcept      { return zone != other.zone; }

ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (Rectangle<int> totalSize,
                                                                                BorderSize<int> border,
                                                                                Point<int> position)
{
    int z = 0;

    if (totalSize.contains (position)
         && ! border.subtractedFrom (totalSize).contains (position))
    {
        auto minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));

        if (position.x < jmax (border.getLeft(), minW) && border.getLeft() > 0)
            z |= left;
        else if (position.x >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
            z |= right;

        auto minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));

        if (position.y < jmax (border.getTop(), minH) && border.getTop() > 0)
            z |= top;
        else if (position.y >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
            z |= bottom;
    }

    return Zone (z);
}

MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const noexcept
{
    auto mc = MouseCursor::NormalCursor;

    switch (zone)
    {
        case (left | top):      mc = MouseCursor::TopLeftCornerResizeCursor; break;
        case top:               mc = MouseCursor::TopEdgeResizeCursor; break;
        case (right | top):     mc = MouseCursor::TopRightCornerResizeCursor; break;
        case left:              mc = MouseCursor::LeftEdgeResizeCursor; break;
        case right:             mc = MouseCursor::RightEdgeResizeCursor; break;
        case (left | bottom):   mc = MouseCursor::BottomLeftCornerResizeCursor; break;
        case bottom:            mc = MouseCursor::BottomEdgeResizeCursor; break;
        case (right | bottom):  mc = MouseCursor::BottomRightCornerResizeCursor; break;
        default:                break;
    }

    return mc;
}

//==============================================================================
ResizableBorderComponent::ResizableBorderComponent (Component* componentToResize,
                                                    ComponentBoundsConstrainer* boundsConstrainer)
   : component (componentToResize),
     constrainer (boundsConstrainer),
     borderSize (5)
{
}

ResizableBorderComponent::~ResizableBorderComponent() = default;

//==============================================================================
void ResizableBorderComponent::paint (Graphics& g)
{
    getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
}

void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
{
    updateMouseZone (e);
}

void ResizableBorderComponent::mouseMove (const MouseEvent& e)
{
    updateMouseZone (e);
}

void ResizableBorderComponent::mouseDown (const MouseEvent& e)
{
    if (component == nullptr)
    {
        jassertfalse; // You've deleted the component that this resizer was supposed to be using!
        return;
    }

    updateMouseZone (e);

    originalBounds = component->getBounds();

    if (constrainer != nullptr)
        constrainer->resizeStart();
}

void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
{
    if (component == nullptr)
    {
        jassertfalse; // You've deleted the component that this resizer was supposed to be using!
        return;
    }

    auto newBounds = mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart());

    if (constrainer != nullptr)
    {
        constrainer->setBoundsForComponent (component, newBounds,
                                            mouseZone.isDraggingTopEdge(),
                                            mouseZone.isDraggingLeftEdge(),
                                            mouseZone.isDraggingBottomEdge(),
                                            mouseZone.isDraggingRightEdge());
    }
    else
    {
        if (auto* p = component->getPositioner())
            p->applyNewBounds (newBounds);
        else
            component->setBounds (newBounds);
    }
}

void ResizableBorderComponent::mouseUp (const MouseEvent&)
{
    if (constrainer != nullptr)
        constrainer->resizeEnd();
}

bool ResizableBorderComponent::hitTest (int x, int y)
{
    return ! borderSize.subtractedFrom (getLocalBounds()).contains (x, y);
}

void ResizableBorderComponent::setBorderThickness (BorderSize<int> newBorderSize)
{
    if (borderSize != newBorderSize)
    {
        borderSize = newBorderSize;
        repaint();
    }
}

BorderSize<int> ResizableBorderComponent::getBorderThickness() const
{
    return borderSize;
}

void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
{
    auto newZone = Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition());

    if (mouseZone != newZone)
    {
        mouseZone = newZone;
        setMouseCursor (newZone.getMouseCursor());
    }
}

} // namespace juce


text:
<?php
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @category    Phrekyll
 * @package     Phrekyll\Registry
 * @subpackage  Has
 * @author      Victor Farazdagi
 * @license     http://www.apache.org/licenses/LICENSE-2.0
 */

namespace Phrekyll\Registry\Has;

/**
 * Has values.
 *
 * @category    Phrekyll
 * @package     Phrekyll\Registry
 * @subpackage  Has
 * @author      Victor Farazdagi
 */
interface Values
{
    /**
     * Set values attribute.
     *
     * @param array $values Values attribute
     *
     * @return \Phrekyll\Has\Values
     */
    public function setValues($values);

    /**
     * Get values attribute.
     *
     * @return \Phrekyll\Has\Values
     */
    public function getValues();
}


text:
package com.hackmit.hierogifics;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;

/**
 * An activity representing a single Group detail screen. This activity is only
 * used on handset devices. On tablet-size devices, item details are presented
 * side-by-side with a list of items in a {@link GroupListActivity}.
 * <p>
 * This activity is mostly just a 'shell' activity containing nothing more than
 * a {@link GroupDetailFragment}.
 */
public class GroupDetailActivity extends FragmentActivity
implements GroupDetailFragment.Callbacks
{

    private boolean mTwoPane;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);

        // Show the Up button in the action bar.
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // savedInstanceState is non-null when there is fragment state
        // saved from previous configurations of this activity
        // (e.g. when rotating the screen from portrait to landscape).
        // In this case, the fragment will automatically be re-added
        // to its container so we don't need to manually add it.
        // For more information, see the Fragments API guide at:
        //
        // http://developer.android.com/guide/components/fragments.html
        //
        if (savedInstanceState == null) {
            // Create the detail fragment and add it to the activity
            // using a fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(GroupDetailFragment.ARG_ITEM_ID, getIntent()
                    .getStringExtra(GroupDetailFragment.ARG_ITEM_ID));
            GroupDetailFragment fragment = new GroupDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.group_detail_container, fragment).commit();
        }

        if (findViewById(R.id.link_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-large and
            // res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            // In two-pane mode, list items should be given the
            // 'activated' state when touched.
            ((GroupListFragment) getSupportFragmentManager().findFragmentById(
                    R.id.group_detail_container)).setActivateOnItemClick(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpTo(this, new Intent(this,
                    GroupListActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected(String id)
    {
        if (mTwoPane) {
            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(LinkDetailFragment.ARG_ITEM_ID, id);
            LinkDetailFragment fragment = new LinkDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.link_detail_container, fragment).commit();

        } else {
            // In single-pane mode, simply start the detail activity
            // for the selected item ID.
            System.out.println("Registering click");
            Intent detailIntent = new Intent(this, LinkDetailActivity.class);
            detailIntent.putExtra(LinkDetailFragment.ARG_ITEM_ID, id); // Pass url here
            startActivity(detailIntent);
        }
    }
}


text:
package main

import (
	"regexp"

	"github.com/layeh/gumble/gumble"
)

var imgurPattern *regexp.Regexp

const imgurLinkPattern = `https?://(?:www|i\.)?(?:imgur\.com/)([[:alnum:]]+)`

func handleImgur(e gumble.TextMessageEvent) bool {
	re := regexp.MustCompile(`imgur.com/r/.+?/`)
	if re.MatchString(e.Message) {
		e.Message = re.ReplaceAllString(e.Message, "imgur.com/")
	}

	imgurMatches := imgurPattern.FindStringSubmatch(e.Message)
	if len(imgurMatches) == 2 {
		go handleImgurLink(e.Client, e.Sender.Name, imgurMatches[1])
		return true
	}
	return false
}

func handleImgurLink(client *gumble.Client, who, id string) {
	linkURL := "http://imgur.com/" + id
	imgURL := "http://i.imgur.com/" + id + "m.png"
	title := getTitle(linkURL)
	postLinkToReddit(client, title, "image", who, linkURL)
	msg := `<b>Imgur</b><br/><center><a href="` + linkURL + `"><img width="250" src="` + imgURL + `"></img><br/>` + title + `</center></a>`
	sendMumbleMsg(client, msg)
	sendSlackMsg(who + " posted " + linkURL)
}


text:
<!DOCTYPE html>
<html>

<head>
  <title>machines-table-sk</title>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body class="body-sk">
  <!-- A machines-table-sk instance will be inserted here dynamically. -->
</body>

</html>


text:
describe ActiveGraph::Node do
  before(:each) do
    stub_node_class('Person') do
      include ActiveGraph::UndeclaredProperties
      property :name, type: String
    end
  end

  def get_value_from_db(node, prop)
    node.class.where(id: node.id).first[prop]
  end

  describe '.new' do
    it 'undeclared properties are found' do
      expect(Person.new(foo: 123)[:foo]).to eq(123)
      expect(Person.new(foo: 123)['foo']).to eq(123)
    end
  end

  describe '.create' do
    it 'does allow to set undeclared properties using create' do
      expect { Person.create(foo: 43) }.not_to raise_error
    end

    it 'stores undefined attributes' do
      person = Person.create(name: 'Jim', foo: 123)
      expect(person[:foo]).to eq(123)
      expect(person['foo']).to eq(123)
      expect(get_value_from_db(person, :foo)).to eq(123)
    end
  end

  describe 'save' do
    it 'does not raise ActiveGraph::Shared::UnknownAttributeError if trying to set undeclared property' do
      expect { Person.new[:foo] = 42 }.not_to raise_error
    end

    it 'saves undeclared the properties that has been changed with []= operator' do
      person = Person.new
      person[:foo] = 123
      person.save
      expect(person[:foo]).to eq(123)
      expect(get_value_from_db(person, :foo)).to eq(123)
    end
  end

  describe '#save!' do
    it 'returns true on success' do
      person = Person.new
      person[:name] = 'Jim'
      person[:foo] = 123
      expect(person.save!).to be true
    end
  end

  describe 'update_attributes' do
    let(:person) do
      Person.create(name: 'Jim', foo: 123)
    end

    it 'updates given declared and udeclared property' do
      person.update_attributes(name: 'Joe', foo: 456)
      expect(get_value_from_db(person, :name)).to eq('Joe')
      expect(get_value_from_db(person, :foo)).to eq(456)
    end

    it 'does delete undeclared property' do
      person.update_attributes(foo: nil)
      expect(get_value_from_db(person, :foo)).to be_nil
    end
  end

  describe 'update_attribute' do
    let(:person) do
      Person.create(name: 'Jim')
    end

    it 'updates given udeclared property' do
      person.update_attribute(:foo, 123)
      expect(get_value_from_db(person, :foo)).to eq(123)
    end

    it 'does delete undeclared property' do
      person.update_attribute(:foo, 123)
      person.update_attribute(:foo, nil)
      expect(get_value_from_db(person, :foo)).to be_nil
    end
  end

  describe 'update_attribute!' do
    let(:person) do
      Person.create(name: 'Jim')
    end

    it 'updates given property' do
      person.update_attribute!(:foo, 123)
      expect(get_value_from_db(person, :foo)).to eq(123)
    end
  end
end


text:
package com.aranga.repository;

import com.aranga.domain.User;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by nanara0 on 5/01/2015.
 */
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository
{

    @PersistenceContext
    private EntityManager em;

    @Override
    public User find(long id)
    {
        final User u = em.find(User.class,id);
        return u;
    }

    public User selectByLogin(String login)
    {
        try
        {
            final List<User> list = em.createNamedQuery("User.selectByLogin", User.class).setParameter("login", login).getResultList();

            if (list.size() == 1) {
                return list.get(0);
            }
        }catch (Throwable e)
        {
            e.printStackTrace();;
        }

        return null;
    }

    @Override
    public List<User> selectAll()
    {

          final List<User> list = em.createNamedQuery("User.selectAll", User.class).getResultList();
          return list;

    }
}


text:
document.addEventListener("DOMContentLoaded", function() {

	console.log('👻');
	App.init(document.getElementById('container'));

});


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="venue_list_adapter_image_width">150dp</dimen>
    <dimen name="venue_list_adapter_image_height">150dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>
</resources>


text:
type OrderedMap<T> = T;

declare module "prosemirror-model" {
  export class ContentMatch {
    matchNode(node: ProsemirrorNode): ContentMatch
    matchType(type: NodeType, attrs?: Object, marks?: Mark[]): ContentMatch
    matchFragment(fragment: Fragment, from?: number, to?: number): ContentMatch | boolean
    matchToEnd(fragment: Fragment, start?: number, end?: number): boolean
    validEnd(): boolean
    fillBefore(after: Fragment, toEnd: boolean, startIndex?: number): Fragment
    allowsMark(markType: MarkType): boolean
    findWrapping(target: NodeType, targetAttrs?: Object, targetMarks?: Mark[]): { type: NodeType, attrs: Object }[]
    findWrappingFor(node: ProsemirrorNode): { type: NodeType, attrs: Object }[]

  }
  export class Fragment {
    append(other: Fragment): Fragment
    cut(from: number, to?: number): Fragment
    replaceChild(index: number, node: ProsemirrorNode): Fragment
    eq(other: Fragment): boolean
    firstChild?: ProsemirrorNode;
    lastChild?: ProsemirrorNode;
    childCount: number;
    child(index: number): ProsemirrorNode
    offsetAt(index: number): number
    maybeChild(index: number): ProsemirrorNode
    forEach(f: (node: ProsemirrorNode, offset: number, index: number) => void): void
    findDiffStart(other: Fragment): number
    findDiffEnd(other: ProsemirrorNode): { a: number, b: number } | void
    toString(): string
    toJSON(): Object | void
    static fromJSON(schema: Schema, value?: Object): Fragment
    static fromArray(array: ProsemirrorNode[]): Fragment
    static from(nodes?: Fragment | ProsemirrorNode | ProsemirrorNode[]): Fragment
    static empty: Fragment;

  }
  export interface ParseRule {
    tag?: string;
    style?: string;
    context?: string;
    node?: string;
    mark?: string;
    priority?: number;
    ignore?: boolean;
    skip?: boolean;
    attrs?: Object;
    getAttrs?(p: Node | string): boolean | Object
    contentElement?: string;
    getContent?(p: Node): Fragment
    preserveWhitespace?: boolean;

  }
  export class DOMParser {
    constructor(schema: Schema, rules: ParseRule[])
    schema: Schema;
    rules: ParseRule[];
    parse(dom: Node, options?: { preserveWhitespace?: boolean, findPositions?: { node: Node, offset: number }[], from?: number, to?: number, topNode?: ProsemirrorNode, topStart?: number, context?: ResolvedPos }): ProsemirrorNode
    parseSlice(dom: Node, options?: Object): Slice
    static schemaRules(schema: Schema): ParseRule[]
    static fromSchema(schema: Schema): DOMParser

  }
  export class Mark {
    type: MarkType;
    attrs: Object;
    addToSet(set: Mark[]): Mark[]
    removeFromSet(set: Mark[]): Mark[]
    isInSet(set: Mark[]): boolean
    eq(other: Mark): boolean
    toJSON(): Object
    static fromJSON(schema: Schema, json: Object): Mark
    static sameSet(a: Mark[], b: Mark[]): boolean
    static setFrom(marks?: Mark | Mark[]): Mark[]
    static none: Mark[];

  }
  export class ProsemirrorNode {
    type: NodeType;
    attrs: Object;
    content: Fragment;
    marks: Mark[];
    text?: string;
    nodeSize: number;
    childCount: number;
    child(index: number): ProsemirrorNode
    maybeChild(index: number): ProsemirrorNode
    forEach(f: (node: ProsemirrorNode, offset: number, index: number) => void): void
    nodesBetween(from: number |  void, to: number |  void, f: (node: ProsemirrorNode, pos: number, parent: ProsemirrorNode, index: number) => void): void
    descendants(f: (node: ProsemirrorNode, pos: number, parent: ProsemirrorNode) => void): void
    textContent: string;
    textBetween(from: number, to: number, blockSeparator?: string, leafText?: string): string
    firstChild?: ProsemirrorNode;
    lastChild?: ProsemirrorNode;
    eq(other: ProsemirrorNode): boolean
    sameMarkup(other: ProsemirrorNode): boolean
    hasMarkup(type: NodeType, attrs?: Object, marks?: Mark[]): boolean
    copy(content?: Fragment): ProsemirrorNode
    mark(marks: Mark[]): ProsemirrorNode
    cut(from: number, to?: number): ProsemirrorNode
    slice(from: number, to?: number): Slice
    replace(from: number, to: number, slice: Slice): ProsemirrorNode
    nodeAt(pos: number): ProsemirrorNode
    childAfter(pos: number): { node?: ProsemirrorNode, index: number, offset: number }
    childBefore(pos: number): { node?: ProsemirrorNode, index: number, offset: number }
    resolve(pos: number): ResolvedPos
    rangeHasMark(from: number |  void, to: number |  void, type: MarkType): boolean
    isBlock: boolean;
    isTextblock: boolean;
    isInline: boolean;
    isText: boolean;
    isLeaf: boolean;
    isAtom: boolean;
    toString(): string
    contentMatchAt(index: number): ContentMatch
    canReplace(from: number, to: number, replacement?: Fragment, start?: number, end?: number): boolean
    canReplaceWith(from: number, to: number, type: NodeType, attrs?: Mark[]): boolean
    canAppend(other: ProsemirrorNode): boolean
    check(): void
    toJSON(): Object
    static fromJSON(schema: Schema, json: Object): ProsemirrorNode

  }
  export class ReplaceError extends Error {

  }
  export class Slice {
    constructor(content: Fragment, openLeft: number, openRight: number)
    content: Fragment;
    openLeft: number;
    openRight: number;
    size: number;
    toJSON(): Object | void
    static fromJSON(schema: Schema, json?: Object): Slice
    static maxOpen(fragment: Fragment): Slice
    static empty: Slice;

  }
  export class ResolvedPos {
    pos: number;
    depth: number;
    parentOffset: number;
    parent: ProsemirrorNode;
    node(depth?: number): ProsemirrorNode
    index(depth?: number): number
    indexAfter(depth?: number): number
    start(depth?: number): number
    end(depth?: number): number
    before(depth?: number): number
    after(depth?: number): number
    textOffset: number;
    nodeAfter?: ProsemirrorNode;
    nodeBefore?: ProsemirrorNode;
    marks(after?: boolean): Mark[]
    sharedDepth(pos: number): number
    blockRange(other?: ResolvedPos, pred?: (p: ProsemirrorNode) => boolean): NodeRange
    sameParent(other: ResolvedPos): boolean

  }
  export class NodeRange {
    $from: ResolvedPos;
    $to: ResolvedPos;
    depth: number;
    start: number;
    end: number;
    parent: ProsemirrorNode;
    startIndex: number;
    endIndex: number;

  }
  export class NodeType {
    name: string;
    schema: Schema;
    spec: NodeSpec;
    isBlock: boolean;
    isText: boolean;
    isInline: boolean;
    isTextblock: boolean;
    isLeaf: boolean;
    isAtom: boolean;
    create(attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode
    createChecked(attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode
    createAndFill(attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode
    validContent(content: Fragment, attrs?: Object): boolean

  }
  export class MarkType {
    name: string;
    schema: Schema;
    spec: MarkSpec;
    create(attrs?: Object): Mark
    removeFromSet(set: Mark[]): Mark[]
    isInSet(set: Mark[]): Mark
    excludes: MarkType;

  }
  export interface SchemaSpec {
    nodes: Object | OrderedMap<NodeSpec>;
    marks?: Object | OrderedMap<MarkSpec>;
    topNode?: string;

  }
  export interface NodeSpec {
    content?: string;
    group?: string;
    inline?: boolean;
    atom?: boolean;
    attrs?: Object;
    selectable?: boolean;
    draggable?: boolean;
    code?: boolean;
    defining?: boolean;
    toDOM?(p: ProsemirrorNode): DOMOutputSpec
    parseDOM?: ParseRule[];

  }
  export interface MarkSpec {
    attrs?: Object;
    inclusiveRight?: boolean;
    excludes?: string;
    group?: string;
    toDOM?(mark: Mark): DOMOutputSpec
    parseDOM?: ParseRule[];

  }
  export interface AttributeSpec {
    default?: any;
    compute?(): any

  }
  export class Schema {
    constructor(spec: SchemaSpec)
    spec: SchemaSpec;
    nodes: Object;
    marks: Object;
    cached: Object;
    topNodeType: NodeType;
    node(type: string | NodeType, attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode
    text(text: string, marks?: Mark[]): ProsemirrorNode
    mark(type: string | MarkType, attrs?: Object): Mark
    nodeFromJSON(json: Object): ProsemirrorNode
    markFromJSON(json: Object): Mark

  }
  export interface DOMOutputSpec {

  }
  export class DOMSerializer {
    constructor(nodes: Object, marks: Object)
    nodes: Object;
    marks: Object;
    serializeFragment(fragment: Fragment, options?: Object): DocumentFragment
    serializeNode(node: ProsemirrorNode, options?: Object): Node
    static renderSpec(doc: Document, structure: DOMOutputSpec): { dom: Node, contentDOM?: Node }
    static fromSchema(schema: Schema): DOMSerializer
    static nodesFromSchema(schema: Schema): Object
    static marksFromSchema(schema: Schema): Object

  }

}