text:
///////////////////////////////////////////////////////////////////////////////
//
// File Driver.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Base class for Drivers
//
///////////////////////////////////////////////////////////////////////////////

#include <SolverUtils/Driver.h>

namespace Nektar
{
namespace SolverUtils
{

std::string Driver::evolutionOperatorLookupIds[6] = {
    LibUtilities::SessionReader::RegisterEnumValue(
            "EvolutionOperator","Nonlinear"      ,eNonlinear),
    LibUtilities::SessionReader::RegisterEnumValue(
            "EvolutionOperator","Direct"         ,eDirect),
    LibUtilities::SessionReader::RegisterEnumValue(
            "EvolutionOperator","Adjoint"        ,eAdjoint),
    LibUtilities::SessionReader::RegisterEnumValue(
            "EvolutionOperator","TransientGrowth",eTransientGrowth),
    LibUtilities::SessionReader::RegisterEnumValue(
            "EvolutionOperator","SkewSymmetric"  ,eSkewSymmetric),
    LibUtilities::SessionReader::RegisterEnumValue(
            "EvolutionOperator","AdaptiveSFD"    ,eAdaptiveSFD)
};
std::string Driver::evolutionOperatorDef =
    LibUtilities::SessionReader::RegisterDefaultSolverInfo(
            "EvolutionOperator","Nonlinear");
std::string Driver::driverDefault =
    LibUtilities::SessionReader::RegisterDefaultSolverInfo(
            "Driver",           "Standard");

DriverFactory& GetDriverFactory()
{
    typedef Loki::SingletonHolder<DriverFactory,
    Loki::CreateUsingNew,
    Loki::NoDestroy,
    Loki::SingleThreaded> Type;
    return Type::Instance();
}

/**
 *
 */
Driver::Driver(const LibUtilities::SessionReaderSharedPtr pSession)
    : m_comm(pSession->GetComm()),
      m_session(pSession)
{
}

Driver::~Driver()

{
}

/**
 *
 */
void Driver::v_InitObject(ostream &out)
{
    try
    {
        // Retrieve the equation system to solve.
        ASSERTL0(m_session->DefinesSolverInfo("EqType"),
                 "EqType SolverInfo tag must be defined.");
        std::string vEquation = m_session->GetSolverInfo("EqType");
        if (m_session->DefinesSolverInfo("SolverType"))
        {
            vEquation = m_session->GetSolverInfo("SolverType");
        }

        // Check such a module exists for this equation.
        ASSERTL0(GetEquationSystemFactory().ModuleExists(vEquation),
                 "EquationSystem '" + vEquation + "' is not defined.\n"
                 "Ensure equation name is correct and module is compiled.\n");

        // Retrieve the type of evolution operator to use
        /// @todo At the moment this is Navier-Stokes specific - generalise?
        m_EvolutionOperator =
            m_session->GetSolverInfoAsEnum<EvolutionOperatorType>(
                    "EvolutionOperator");

        m_nequ = ((m_EvolutionOperator == eTransientGrowth ||
                   m_EvolutionOperator == eAdaptiveSFD) ? 2 : 1);

        m_equ = Array<OneD, EquationSystemSharedPtr>(m_nequ);

        // Set the AdvectiveType tag and create EquationSystem objects.
        switch (m_EvolutionOperator)
        {
            case eNonlinear:
                m_session->SetTag("AdvectiveType","Convective");
                m_equ[0] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);
                break;
            case eDirect:
                m_session->SetTag("AdvectiveType","Linearised");
                m_equ[0] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);
                break;
            case eAdjoint:
                m_session->SetTag("AdvectiveType","Adjoint");
                m_equ[0] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);
                break;
            case eTransientGrowth:
                //forward timestepping
                m_session->SetTag("AdvectiveType","Linearised");
                m_equ[0] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);

                //backward timestepping
                m_session->SetTag("AdvectiveType","Adjoint");
                m_equ[1] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);
                break;
            case eSkewSymmetric:
                m_session->SetTag("AdvectiveType","SkewSymmetric");
                m_equ[0] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);
                break;
            case eAdaptiveSFD:
            {
                // Coupling SFD method and Arnoldi algorithm
                // For having 2 equation systems defined into 2 different
                // session files (with the mesh into a file named 'session'.gz)
                string          meshfile;
                string          LinNSCondFile;
                vector<string>  LinNSFilename;
                meshfile = m_session->GetFilenames()[0];
                LinNSCondFile = m_session->GetSessionName();
                LinNSCondFile += "_LinNS.xml";
                LinNSFilename.push_back(meshfile);
                LinNSFilename.push_back(LinNSCondFile);
                session_LinNS = LibUtilities::SessionReader::CreateInstance(
                                0, NULL, LinNSFilename, m_session->GetComm());

                //For running stability analysis
                session_LinNS->SetTag("AdvectiveType","Linearised");
                m_equ[0] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, session_LinNS);

                //For running the SFD method on the nonlinear problem
                m_session->SetTag("AdvectiveType","Convective");
                m_equ[1] = GetEquationSystemFactory().CreateInstance(
                                    vEquation, m_session);
            }
                break;
            default:
                ASSERTL0(false, "Unrecognised evolution operator.");

        }
    }
    catch (int e)
    {
        ASSERTL0(e == -1, "No such class class defined.");
        out << "An error occurred during driver initialisation." << endl;
    }
}

Array<OneD, NekDouble> Driver::v_GetRealEvl(void)
{
    ASSERTL0(false,"This routine is not valid in this class");
    return NullNekDouble1DArray;
}

Array<OneD, NekDouble> Driver::v_GetImagEvl(void)
{
    ASSERTL0(false,"This routine is not valid in this class");
    return NullNekDouble1DArray;
}

}
}


text:
class RemoveAwsKeysFromProviderAccounts < ActiveRecord::Migration
  def self.up
    remove_column :provider_accounts, :aws_access_key
    remove_column :provider_accounts, :aws_secret_key
  end

  def self.down
    add_column :provider_accounts, :aws_access_key, :string
    add_column :provider_accounts, :aws_secret_key, :string
  end
end

redpajama_set_name: RedPajamaGithub


text:
title: Query and Visualize data from Cassandra
name: Cassandra
logo: /assets/images/integrations/cassandra.png
path: /data-sources/cassandra
---


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>ibeis.tests.test_sql_numpy — ibeis 1.5.2 documentation</title>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="ibeis 1.5.2 documentation" href="../../../index.html"/>
        <link rel="up" title="ibeis" href="../../ibeis.html"/>

             ibeis

                1.5.2

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

ibeis package

        ibeis

Docs »

Module code »

ibeis »

ibeis.tests.test_sql_numpy

Source code for ibeis.tests.test_sql_numpy

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from six.moves import range
import numpy as np
import utool
from ibeis.control import SQLDatabaseControl as sqldbc
from ibeis.control._sql_helpers import _results_gen
from os.path import join
print, print_, printDBG, rrr, profile = utool.inject(__name__, '[TEST_SQL_NUMPY] ')

# list of 10,000 chips with 3,000 features apeice.

[docs]def grab_numpy_testdata(shape=(3e3, 128), dtype=np.uint8):
    ndata = utool.get_argval('--ndata', type_=int, default=2)
    print('[TEST] build ndata=%d numpy arrays with shape=%r' % (ndata, shape))
    print(' * expected_memory(table_list) = %s' % utool.byte_str2(ndata * np.product(shape)))
    table_list = [np.empty(shape, dtype=dtype) for i in range(ndata)]
    print(' * memory+overhead(table_list) = %s' % utool.byte_str2(utool.get_object_size(table_list)))
    return table_list

[docs]def TEST_SQL_NUMPY():
    sqldb_fname = 'temp_test_sql_numpy.sqlite3'
    sqldb_dpath = utool.util_cplat.get_app_resource_dir('ibeis', 'testfiles')
    utool.ensuredir(sqldb_dpath)
    utool.util_path.remove_file(join(sqldb_dpath, sqldb_fname), dryrun=False)
    db = sqldbc.SQLDatabaseController(sqldb_dpath=sqldb_dpath,
                                      sqldb_fname=sqldb_fname)

    db.add_table('temp',    [
        ('temp_id',      'INTEGER PRIMARY KEY'),
        ('temp_hash',    'NUMPY'),
    ])

    tt = utool.tic()
    feats_list = grab_numpy_testdata(shape=(3e3, 128), dtype=np.uint8)
    print(' * numpy.new time=%r sec' % utool.toc(tt))

    print('[TEST] insert numpy arrays')
    tt = utool.tic()
    feats_iter = ((feats, ) for feats in feats_list)
    db.executemany(operation='''
        INSERT
        INTO temp
        (
            temp_hash
        )
        VALUES (?)
        ''', params_iter=feats_iter)
    print(' * execute insert time=%r sec' % utool.toc(tt))

    print('[TEST] save sql database')
    tt = utool.tic()
    #db.cur.commit()
    db.connection.commit()
    print(' * commit time=%r sec' % utool.toc(tt))

    print('[TEST] read from sql database')

    tt = utool.tic()
    db.cur.execute('SELECT temp_hash FROM temp', [])
    print(' * execute select time=%r sec' % utool.toc(tt))

    tt = utool.tic()
    result_list = _results_gen(db.cur)
    print(' * iter results time=%r sec' % utool.toc(tt))
    print(' * memory(result_list) = %s' % utool.byte_str2(utool.get_object_size(result_list)))
    del result_list
    #print('[TEST] result_list=%r' % result_list)

    print('[TEST] dump sql database')
    tt = utool.tic()
    db.dump('temp.dump.txt')
    print(' * dump time=%r sec' % utool.toc(tt))
    #with open('temp.dump.txt') as file_:
    #    print(file_.read())
    return locals()

if __name__ == '__main__':
    import multiprocessing
    multiprocessing.freeze_support()  # For win32
    test_locals = utool.run_test(TEST_SQL_NUMPY)
    execstr = utool.execstr_dict(test_locals, 'test_locals')
    exec(execstr)

        © Copyright 2016, Jon Crall.

  Built with Sphinx using a theme provided by Read the Docs.


text:
using UnityEngine;
using UnityEngine.UI;
using System.Reflection;
using System;

namespace Klak.UI
{
    public static class DefaultControls
    {
        const float kWidth = 80;

        // Retrieve and invoke a private method "DefaultControls.CreateUIElementRoot".
        static GameObject CreateUIElementRoot(string name, Vector2 size)
        {
            var type = Type.GetType("UnityEngine.UI.DefaultControls,UnityEngine.UI");
            var flags = BindingFlags.NonPublic | BindingFlags.Static;
            var method = type.GetMethod("CreateUIElementRoot", flags);
            return (GameObject)method.Invoke(null, new System.Object[]{ name, size });
        }

        // Retrieve and invoke a private method "DefaultControls.CreateUIObject".
        static GameObject CreateUIObject(string name, GameObject parent)
        {
            var type = Type.GetType("UnityEngine.UI.DefaultControls,UnityEngine.UI");
            var flags = BindingFlags.NonPublic | BindingFlags.Static;
            var method = type.GetMethod("CreateUIObject", flags);
            return (GameObject)method.Invoke(null, new System.Object[]{ name, parent });
        }

        static void SetDefaultColorTransitionValues(Selectable selectable, bool whiteOnPress)
        {
            var colors = selectable.colors;
            colors.normalColor = new Color32(72, 72, 72, 255);
            colors.highlightedColor = new Color32(72, 72, 72, 255);
            if (whiteOnPress)
                colors.pressedColor = Color.white;
            else
                colors.pressedColor = new Color32(72, 72, 72, 255);
            colors.disabledColor = new Color32(20, 20, 20, 128);
            colors.fadeDuration = 0.03f;
            selectable.colors = colors;
        }

        static void FitToParent(GameObject go, Vector2 offset)
        {
            var rt = go.GetComponent<RectTransform>();
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.sizeDelta = Vector2.zero;
            rt.offsetMin = new Vector2(offset.x, 0);
            rt.offsetMax = new Vector2(0, offset.y);
        }

        // Actual controls

        // Knob
        public static GameObject CreateKnob(Material material, Sprite sprite, Font font)
        {
            // UI hierarchy
            var root = CreateUIElementRoot("Knob", Vector2.one * kWidth);
            var graphic = CreateUIObject("Graphic", root);
            var label = CreateUIObject("Label", root);

            // Stretch settings
            FitToParent(graphic, Vector2.zero);
            FitToParent(label, new Vector2(4, 15));

            // Graphic
            var image = graphic.AddComponent<Image>();
            image.material = material;
            image.sprite = sprite;
            image.color = Color.white;

            // Label
            var text = label.AddComponent<Text>();
            text.text = "Knob";
            text.alignment = TextAnchor.UpperLeft;
            text.font = font;

            // Knob
            var knob = root.AddComponent<Knob>();
            SetDefaultColorTransitionValues(knob, false);
            knob.targetGraphic = image;
            knob.graphic = image;

            return root;
        }

        // Button
        public static GameObject CreateButton(Sprite sprite, Font font)
        {
            // UI hierarchy
            var root = CreateUIElementRoot("Button", Vector2.one * kWidth);
            var label = CreateUIObject("Label", root);

            // Stretch settings
            FitToParent(label, new Vector2(4, 15));

            // Graphic
            var image = root.AddComponent<Image>();
            image.sprite = sprite;
            image.color = Color.white;

            // Label
            var text = label.AddComponent<Text>();
            text.text = "Button";
            text.alignment = TextAnchor.UpperLeft;
            text.font = font;

            // Button
            var button = root.AddComponent<Button>();
            SetDefaultColorTransitionValues(button, true);

            return root;
        }

        // Toggle
        public static GameObject CreateToggle(Sprite bgSprite, Sprite fillSprite, Font font)
        {
            // UI hierarchy
            var root = CreateUIElementRoot("Toggle", Vector2.one * kWidth);
            var background = CreateUIObject("Background", root);
            var checkmark = CreateUIObject("Checkmark", background);
            var label = CreateUIObject("Label", root);

            // Stretch settings
            FitToParent(background, Vector2.zero);
            FitToParent(checkmark, Vector2.zero);
            FitToParent(label, new Vector2(4, 15));

            // Background image
            var bgImage = background.AddComponent<Image>();
            bgImage.sprite = bgSprite;
            bgImage.color = Color.white;

            // Checkmark image
            var ckImage = checkmark.AddComponent<Image>();
            ckImage.sprite = fillSprite;
            ckImage.color = new Color32(240, 240, 240, 255);

            // Label
            var text = label.AddComponent<Text>();
            text.text = "Toggle";
            text.alignment = TextAnchor.UpperLeft;
            text.font = font;

            // Toggle
            var toggle = root.AddComponent<Toggle>();
            SetDefaultColorTransitionValues(toggle, true);
            toggle.targetGraphic = bgImage;
            toggle.graphic = ckImage;

            return root;
        }
    }
}


text:
module SuppliesHelper
end


text:
<?php
/**
 */
class DmRedirectTable extends PluginDmRedirectTable
{

}


text:
require 'spec_helper'

describe SparkPostRails::DeliveryMethod do

  before(:each) do
    SparkPostRails.configuration.set_defaults
    @delivery_method = SparkPostRails::DeliveryMethod.new
  end

  context "Open Tracking" do
    it "handles open tracking enabled in the configuration" do
      SparkPostRails.configure do |c|
        c.track_opens = true
      end

      test_email = Mailer.test_email

      @delivery_method.deliver!(test_email)

      expect(@delivery_method.data[:options][:open_tracking]).to eq(true)
    end

    it "handles open tracking enabled on an individual message" do
      test_email = Mailer.test_email sparkpost_data: {track_opens: true}

      @delivery_method.deliver!(test_email)

      expect(@delivery_method.data[:options][:open_tracking]).to eq(true)
    end

    it "handles the value on an individual message overriding configuration" do
      SparkPostRails.configure do |c|
        c.track_opens = true
      end

      test_email = Mailer.test_email sparkpost_data: {track_opens: false}

      @delivery_method.deliver!(test_email)

      expect(@delivery_method.data[:options][:open_tracking]).to eq(false)
    end

    it "handles a default setting of 'false'" do
      test_email = Mailer.test_email

      @delivery_method.deliver!(test_email)

      expect(@delivery_method.data[:options][:open_tracking]).to eq(false)
    end

  end
end


text:
<?php

defined('_JEXEC') or die();
if ($viewData['include_amazon_css']) {
	$doc = JFactory::getDocument()->addStyleSheet(JURI::root(true) . '/plugins/vmpayment/amazon/assets/css/amazon.css');
}
$success = $viewData["success"];
$order = $viewData["order"];

?>

 <?php echo vmText::_('VMPAYMENT_AMAZON_THANK_YOU'); ?>

		<?php echo vmText::_('VMPAYMENT_AMAZON_ORDER_ID'); ?>
		 <?php echo $viewData["amazonOrderId"]; ?>

	<?php if ($success) { ?>

			<a class="vm-button-correct" href="<?php echo JRoute::_('index.php?option=com_virtuemart&view=orders&layout=details&order_number=' . $viewData["order"]['details']['BT']->order_number . '&order_pass=' . $viewData["order"]['details']['BT']->order_pass, false) ?>"><?php echo vmText::_('COM_VIRTUEMART_ORDER_VIEW_ORDER'); ?>

	<?php } ?>


text:
#include <controller.h>
#include <itemlist_formaction.h>
#include <view.h>
#include <config.h>
#include <logger.h>
#include <exceptions.h>
#include <utils.h>
#include <formatstring.h>
#include <listformatter.h>

#include <cassert>
#include <sstream>

#include <langinfo.h>

#define FILTER_UNREAD_ITEMS "unread != \"no\""

namespace newsbeuter {

itemlist_formaction::itemlist_formaction(view * vv, std::string formstr)
	: formaction(vv,formstr), apply_filter(false), update_visible_items(true), show_searchresult(false),
		search_dummy_feed(new rss_feed(v->get_ctrl()->get_cache())),
		set_filterpos(false), filterpos(0), rxman(0), old_width(0), old_itempos(-1) {
	assert(true==m.parse(FILTER_UNREAD_ITEMS));
	old_sort_order = "";
}

itemlist_formaction::~itemlist_formaction() { }

void itemlist_formaction::process_operation(operation op, bool automatic, std::vector<std::string> * args) {
	bool quit = false;
	bool hardquit = false;

	/*
	 * most of the operations go like this:
	 *   - extract the current position
	 *   - if an item was selected, then fetch it and do something with it
	 */

	std::string itemposname = f->get("itempos");
	unsigned int itempos = utils::to_u(itemposname);

	switch (op) {
		case OP_OPEN: {
				LOG(LOG_INFO, "itemlist_formaction: opening item at pos `%s'", itemposname.c_str());
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					visible_items[itempos].first->set_unread(false); // set article as read
					v->get_ctrl()->mark_article_read(visible_items[itempos].first->guid(), true);
					old_itempos = itempos;
					v->push_itemview(feed, visible_items[itempos].first->guid(), show_searchresult ? searchphrase : "");
					do_redraw = true;
				} else {
					v->show_error(_("No item selected!")); // should not happen
				}
			}
			break;
		case OP_DELETE: {
				scope_measure m1("OP_DELETE");
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					// mark as read
					v->get_ctrl()->mark_article_read(visible_items[itempos].first->guid(), true);
					visible_items[itempos].first->set_unread(false);
					// mark as deleted
					visible_items[itempos].first->set_deleted(!visible_items[itempos].first->deleted());
					v->get_ctrl()->mark_deleted(visible_items[itempos].first->guid(), visible_items[itempos].first->deleted());
					if (itempos < visible_items.size()-1)
						f->set("itempos", utils::strprintf("%u", itempos + 1));
					do_redraw = true;
				} else {
					v->show_error(_("No item selected!")); // should not happen
				}
			}
			break;
		case OP_PURGE_DELETED: {
				scope_measure m1("OP_PURGE_DELETED");
				feed->purge_deleted_items();
				update_visible_items = true;
				do_redraw = true;
			}
			break;
		case OP_OPENBROWSER_AND_MARK: {
				LOG(LOG_INFO, "itemlist_formaction: opening item at pos `%s'", itemposname.c_str());
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					if (itempos < visible_items.size()) {
						visible_items[itempos].first->set_unread(false);
						if (itempos < visible_items.size()-1) {
							f->set("itempos", utils::strprintf("%u", itempos + 1));
						}
						v->open_in_browser(visible_items[itempos].first->link());
						do_redraw = true;
					}
				} else {
					v->show_error(_("No item selected!")); // should not happen
				}
			}
			break;
		case OP_OPENINBROWSER: {
				LOG(LOG_INFO, "itemlist_formaction: opening item at pos `%s'", itemposname.c_str());
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					if (itempos < visible_items.size()) {
						v->open_in_browser(visible_items[itempos].first->link());
						do_redraw = true;
					}
				} else {
					v->show_error(_("No item selected!")); // should not happen
				}
			}
			break;
		case OP_TOGGLEITEMREAD: {
				LOG(LOG_INFO, "itemlist_formaction: toggling item read at pos `%s'", itemposname.c_str());
				if (itemposname.length() > 0) {
					v->set_status(_("Toggling read flag for article..."));
					try {
						if (automatic && args->size() > 0) {
							if ((*args)[0] == "read") {
								visible_items[itempos].first->set_unread(false);
							} else if ((*args)[0] == "unread") {
								visible_items[itempos].first->set_unread(true);
							}
							v->set_status("");
						} else {
							visible_items[itempos].first->set_unread(!visible_items[itempos].first->unread());
							v->set_status("");
						}
					} catch (const dbexception& e) {
						v->set_status(utils::strprintf(_("Error while toggling read flag: %s"), e.what()));
					}
					if (itempos < visible_items.size()-1)
						f->set("itempos", utils::strprintf("%u", itempos + 1));
					do_redraw = true;
				}
			}
			break;
		case OP_SHOWURLS:
			if (itemposname.length() > 0 && visible_items.size() != 0) {
				if (itempos < visible_items.size()) {
					std::vector<linkpair> links;
					std::vector<std::string> lines;
					htmlrenderer rnd(80);
					std::string baseurl = visible_items[itempos].first->get_base() != "" ? visible_items[itempos].first->get_base() : visible_items[itempos].first->link();
					rnd.render(visible_items[itempos].first->description(), lines, links, baseurl);
					if (links.size() > 0) {
						v->push_urlview(links);
					} else {
						v->show_error(_("URL list empty."));
					}
				}
			} else {
				v->show_error(_("No item selected!")); // should not happen
			}
			break;
		case OP_BOOKMARK: {
				LOG(LOG_INFO, "itemlist_formaction: bookmarking item at pos `%s'", itemposname.c_str());
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					if (itempos < visible_items.size()) {
						if (automatic) {
							qna_responses.clear();
							qna_responses.push_back(visible_items[itempos].first->title());
							qna_responses.push_back(visible_items[itempos].first->link());
							qna_responses.push_back(args->size() > 0 ? (*args)[0] : "");
							this->finished_qna(OP_INT_BM_END);
						} else {
							this->start_bookmark_qna(visible_items[itempos].first->title(), visible_items[itempos].first->link(), "");
						}
					}
				} else {
					v->show_error(_("No item selected!")); // should not happen
				}
			}
			break;
		case OP_EDITFLAGS: {
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					if (itempos < visible_items.size()) {
						if (automatic) {
							if (args->size() > 0) {
								qna_responses.clear();
								qna_responses.push_back((*args)[0]);
								finished_qna(OP_INT_EDITFLAGS_END);
							}
						} else {
							std::vector<qna_pair> qna;
							qna.push_back(qna_pair(_("Flags: "), visible_items[itempos].first->flags()));
							this->start_qna(qna, OP_INT_EDITFLAGS_END);
						}
					}
				} else {
					v->show_error(_("No item selected!")); // should not happen
				}
			}
			break;
		case OP_SAVE:
			{
				LOG(LOG_INFO, "itemlist_formaction: saving item at pos `%s'", itemposname.c_str());
				if (itemposname.length() > 0 && visible_items.size() != 0) {
					std::string filename ;
					if (automatic) {
						if (args->size() > 0) {
							filename = (*args)[0];
						}
					} else {
						filename = v->run_filebrowser(FBT_SAVE,v->get_filename_suggestion(visible_items[itempos].first->title()));
					}
					save_article(filename, visible_items[itempos].first);
				} else {
					v->show_error(_("Error: no item selected!"));
				}
			}
			break;
		case OP_HELP:
			v->push_help();
			break;
		case OP_RELOAD:
			if (!show_searchresult) {
				LOG(LOG_INFO, "itemlist_formaction: reloading current feed");
				v->get_ctrl()->reload(pos);
				update_visible_items = true;
				do_redraw = true;
			} else {
				v->show_error(_("Error: you can't reload search results."));
			}
			break;
		case OP_QUIT:
			LOG(LOG_INFO, "itemlist_formaction: quitting");
			v->feedlist_mark_pos_if_visible(pos);
			feed->purge_deleted_items();
			feed->unload();
			quit = true;
			break;
		case OP_HARDQUIT:
			LOG(LOG_INFO, "itemlist_formaction: hard quitting");
			v->feedlist_mark_pos_if_visible(pos);
			feed->purge_deleted_items();
			hardquit = true;
			break;
		case OP_NEXTUNREAD:
			LOG(LOG_INFO, "itemlist_formaction: jumping to next unread item");
			if (!jump_to_next_unread_item(false)) {
				if (!v->get_next_unread(this)) {
					v->show_error(_("No unread items."));
				}
			}
			break;
		case OP_PREVUNREAD:
			LOG(LOG_INFO, "itemlist_formaction: jumping to previous unread item");
			if (!jump_to_previous_unread_item(false)) {
				if (!v->get_previous_unread(this)) {
					v->show_error(_("No unread items."));
				}
			}
			break;
		case OP_NEXT:
			LOG(LOG_INFO, "itemlist_formaction: jumping to next item");
			if (!jump_to_next_item(false)) {
				if (!v->get_next(this)) {
					v->show_error(_("Already on last item."));
				}
			}
			break;
		case OP_PREV:
			LOG(LOG_INFO, "itemlist_formaction: jumping to previous item");
			if (!jump_to_previous_item(false)) {
				if (!v->get_previous(this)) {
					v->show_error(_("Already on first item."));
				}
			}
			break;
		case OP_RANDOMUNREAD:
			if (!jump_to_random_unread_item()) {
				if (!v->get_random_unread(this)) {
					v->show_error(_("No unread items."));
				}
			}
			break;
		case OP_NEXTUNREADFEED:
			if (!v->get_next_unread_feed(this)) {
				v->show_error(_("No unread feeds."));
			}
			break;
		case OP_PREVUNREADFEED:
			if (!v->get_prev_unread_feed(this)) {
				v->show_error(_("No unread feeds."));
			}
			break;
		case OP_NEXTFEED:
			if (!v->get_next_feed(this)) {
				v->show_error(_("Already on last feed."));
			}
			break;
		case OP_PREVFEED:
			if (!v->get_prev_feed(this)) {
				v->show_error(_("Already on first feed."));
			}
			break;
		case OP_MARKFEEDREAD:
			LOG(LOG_INFO, "itemlist_formaction: marking feed read");
			v->set_status(_("Marking feed read..."));
			try {
				if (feed->rssurl() != "") {
					v->get_ctrl()->mark_all_read(pos);
				} else {
					{
						scope_mutex lock(&feed->item_mutex);
						LOG(LOG_DEBUG, "itemlist_formaction: oh, it looks like I'm in a pseudo-feed (search result, query feed)");
						for (std::vector<std::tr1::shared_ptr<rss_item> >::iterator it=feed->items().begin();it!=feed->items().end();++it) {
							(*it)->set_unread_nowrite_notify(false, true);
						}
					}
					v->get_ctrl()->catchup_all(feed);
				}
				do_redraw = true;
				v->set_status("");
			} catch (const dbexception& e) {
				v->show_error(utils::strprintf(_("Error: couldn't mark feed read: %s"), e.what()));
			}
			break;
		case OP_TOGGLESHOWREAD:
			m.parse(FILTER_UNREAD_ITEMS);
			LOG(LOG_DEBUG, "itemlist_formaction: toggling show-read-articles");
			if (v->get_cfg()->get_configvalue_as_bool("show-read-articles")) {
				v->get_cfg()->set_configvalue("show-read-articles", "no");
				apply_filter = true;
			} else {
				v->get_cfg()->set_configvalue("show-read-articles", "yes");
				apply_filter = false;
			}
			save_filterpos();
			update_visible_items = true;
			do_redraw = true;
			break;
		case OP_PIPE_TO:
			if(visible_items.size() != 0) {
				std::vector<qna_pair> qna;
				if (automatic) {
					if (args->size() > 0) {
						qna_responses.clear();
						qna_responses.push_back((*args)[0]);
						finished_qna(OP_PIPE_TO);
					}
				} else {
					qna.push_back(qna_pair(_("Pipe article to command: "), ""));
					this->start_qna(qna, OP_PIPE_TO, &cmdlinehistory);
				}
			} else {
				v->show_error(_("No item selected!"));
			}
			break;
		case OP_SEARCH: {
				std::vector<qna_pair> qna;
				if (automatic) {
					if (args->size() > 0) {
						qna_responses.clear();
						qna_responses.push_back((*args)[0]);
						finished_qna(OP_INT_START_SEARCH);
					}
				} else {
					qna.push_back(qna_pair(_("Search for: "), ""));
					this->start_qna(qna, OP_INT_START_SEARCH, &searchhistory);
				}
			}
			break;
		case OP_EDIT_URLS:
			v->get_ctrl()->edit_urls_file();
			break;
		case OP_SELECTFILTER:
			if (v->get_ctrl()->get_filters().size() > 0) {
				std::string newfilter;
				if (automatic) {
					if (args->size() > 0)
						newfilter = (*args)[0];
				} else {
					newfilter = v->select_filter(v->get_ctrl()->get_filters().get_filters());
					LOG(LOG_DEBUG,"itemlist_formaction::run: newfilters = %s", newfilter.c_str());
				}
				if (newfilter != "") {
					filterhistory.add_line(newfilter);
					if (newfilter.length() > 0) {
						if (!m.parse(newfilter)) {
							v->show_error(utils::strprintf(_("Error: couldn't parse filter command `%s': %s"), newfilter.c_str(), m.get_parse_error().c_str()));
							m.parse(FILTER_UNREAD_ITEMS);
						} else {
							apply_filter = true;
							update_visible_items = true;
							do_redraw = true;
							save_filterpos();
						}
					}
				}
			} else {
				v->show_error(_("No filters defined."));
			}

			break;
		case OP_SETFILTER:
			if (automatic) {
				if (args->size() > 0) {
					qna_responses.clear();
					qna_responses.push_back((*args)[0]);
					this->finished_qna(OP_INT_END_SETFILTER);
				}
			} else {
				std::vector<qna_pair> qna;
				qna.push_back(qna_pair(_("Filter: "), ""));
				this->start_qna(qna, OP_INT_END_SETFILTER, &filterhistory);
			}
			break;
		case OP_CLEARFILTER:
			apply_filter = false;
			update_visible_items = true;
			do_redraw = true;
			save_filterpos();
			break;
		case OP_SORT: {
				char c = v->confirm(_("Sort by (d)ate/(t)itle/(f)lags/(a)uthor/(l)ink/(g)uid?"), _("dtfalg"));
				if (!c) break;
				std::string result(1, c);
				if (result == _("d")) {
					v->get_cfg()->set_configvalue("article-sort-order", "date-asc");
				} else if (result == _("t")) {
					v->get_cfg()->set_configvalue("article-sort-order", "title-asc");
				} else if (result == _("f")) {
					v->get_cfg()->set_configvalue("article-sort-order", "flags-asc");
				} else if (result == _("a")) {
					v->get_cfg()->set_configvalue("article-sort-order", "author-asc");
				} else if (result == _("l")) {
					v->get_cfg()->set_configvalue("article-sort-order", "link-asc");
				} else if (result == _("g")) {
					v->get_cfg()->set_configvalue("article-sort-order", "guid-asc");
				}
			}
			break;
		case OP_REVSORT: {
				char c = v->confirm(_("Reverse Sort by (d)ate/(t)itle/(f)lags/(a)uthor/(l)ink/(g)uid?"), _("dtfalg"));
				if (!c) break;
				std::string result(1, c);
				if (result == _("d")) {
					v->get_cfg()->set_configvalue("article-sort-order", "date-desc");
				} else if (result == _("t")) {
					v->get_cfg()->set_configvalue("article-sort-order", "title-desc");
				} else if (result == _("f")) {
					v->get_cfg()->set_configvalue("article-sort-order", "flags-desc");
				} else if (result == _("a")) {
					v->get_cfg()->set_configvalue("article-sort-order", "author-desc");
				} else if (result == _("l")) {
					v->get_cfg()->set_configvalue("article-sort-order", "link-desc");
				} else if (result == _("g")) {
					v->get_cfg()->set_configvalue("article-sort-order", "guid-desc");
				}
			}
			break;
		case OP_INT_RESIZE:
			do_redraw = true;
			break;
		default:
			break;
	}
	if (hardquit) {
		while (v->formaction_stack_size() > 0) {
			v->pop_current_formaction();
		}
	} else if (quit) {
		v->pop_current_formaction();
	}
}

void itemlist_formaction::finished_qna(operation op) {
	formaction::finished_qna(op); // important!

	switch (op) {
		case OP_INT_END_SETFILTER:
			qna_end_setfilter();
			break;

		case OP_INT_EDITFLAGS_END:
			qna_end_editflags();
			break;

		case OP_INT_START_SEARCH:
			qna_start_search();
			break;

		case OP_PIPE_TO: {
				std::string itemposname = f->get("itempos");
				unsigned int itempos = utils::to_u(itemposname);
				if (itemposname.length() > 0) {
					std::string cmd = qna_responses[0];
					std::ostringstream ostr;
					v->get_ctrl()->write_item(visible_items[itempos].first, ostr);
					v->push_empty_formaction();
					stfl::reset();
					FILE * f = popen(cmd.c_str(), "w");
					if (f) {
						std::string data = ostr.str();
						fwrite(data.c_str(), data.length(), 1, f);
						pclose(f);
					}
					v->pop_current_formaction();
				}
			}
			break;

		default:
			break;
	}
}

void itemlist_formaction::qna_end_setfilter() {
	std::string filtertext = qna_responses[0];
	filterhistory.add_line(filtertext);

	if (filtertext.length() > 0) {

		if (!m.parse(filtertext)) {
			v->show_error(_("Error: couldn't parse filter command!"));
			return;
		}

		apply_filter = true;
		update_visible_items = true;
		do_redraw = true;
		save_filterpos();
	}
}

void itemlist_formaction::qna_end_editflags() {
	std::string itemposname = f->get("itempos");
	if (itemposname.length() == 0) {
		v->show_error(_("No item selected!")); // should not happen
		return;
	}

	std::istringstream posname(itemposname);
	unsigned int itempos = 0;
	posname >> itempos;
	if (itempos < visible_items.size()) {
		visible_items[itempos].first->set_flags(qna_responses[0]);
		v->get_ctrl()->update_flags(visible_items[itempos].first);
		v->set_status(_("Flags updated."));
		LOG(LOG_DEBUG, "itemlist_formaction::finished_qna: updated flags");
		do_redraw = true;
	}
}

void itemlist_formaction::qna_start_search() {
	searchphrase = qna_responses[0];
	if (searchphrase.length() == 0)
		return;

	v->set_status(_("Searching..."));
	searchhistory.add_line(searchphrase);
	std::vector<std::tr1::shared_ptr<rss_item> > items;
	try {
		std::string utf8searchphrase = utils::convert_text(searchphrase, "utf-8", nl_langinfo(CODESET));
		if (show_searchresult) {
			items = v->get_ctrl()->search_for_items(utf8searchphrase, "");
		} else {
			items = v->get_ctrl()->search_for_items(utf8searchphrase, feed->rssurl());
		}
	} catch (const dbexception& e) {
		v->show_error(utils::strprintf(_("Error while searching for `%s': %s"), searchphrase.c_str(), e.what()));
		return;
	}

	if (items.size() == 0) {
		v->show_error(_("No results."));
		return;
	}

	{
	    scope_mutex lock(&search_dummy_feed->item_mutex);
	    search_dummy_feed->items() = items;
	}

	if (show_searchresult) {
		v->pop_current_formaction();
	}
	v->push_searchresult(search_dummy_feed, searchphrase);
}

void itemlist_formaction::do_update_visible_items() {
	if (!update_visible_items)
		return;

	update_visible_items = false;

	scope_mutex lock(&feed->item_mutex);
	std::vector<std::tr1::shared_ptr<rss_item> >& items = feed->items();

	visible_items.clear();

	/*
	 * this method doesn't redraw, all it does is to go through all
	 * items of a feed, and fill the visible_items vector by checking
	 * (if applicable) whether an items matches the currently active filter.
	 */

	unsigned int i=0;
	for (std::vector<std::tr1::shared_ptr<rss_item> >::iterator it = items.begin(); it != items.end(); ++it, ++i) {
		(*it)->set_index(i+1);
		if (!apply_filter || m.matches(it->get())) {
			visible_items.push_back(itemptr_pos_pair(*it, i));
		}
	}

	LOG(LOG_DEBUG, "itemlist_formaction::do_update_visible_items: size = %u", visible_items.size());

	do_redraw = true;
}

void itemlist_formaction::prepare() {
	scope_mutex mtx(&redraw_mtx);

	std::string sort_order = v->get_cfg()->get_configvalue("article-sort-order");
	if (sort_order != old_sort_order) {
		feed->sort(sort_order);
		old_sort_order = sort_order;
		update_visible_items = true;
		do_redraw = true;
	}

	do_update_visible_items();

	if (v->get_cfg()->get_configvalue_as_bool("mark-as-read-on-hover")) {
		std::string itemposname = f->get("itempos");
		if (itemposname.length() > 0) {
			unsigned int itempos = utils::to_u(itemposname);
			if (visible_items[itempos].first->unread()) {
				visible_items[itempos].first->set_unread(false);
				v->get_ctrl()->mark_article_read(visible_items[itempos].first->guid(), true);
				do_redraw = true;
			}
		}
	}

	unsigned int width = utils::to_u(f->get("items:w"));

	if (old_width != width) {
		do_redraw = true;
		old_width = width;
	}

	if (!do_redraw)
		return;
	do_redraw = false;

	listformatter listfmt;

	std::string datetimeformat = v->get_cfg()->get_configvalue("datetime-format");
	std::string itemlist_format = v->get_cfg()->get_configvalue("articlelist-format");

	for (std::vector<itemptr_pos_pair>::iterator it = visible_items.begin(); it != visible_items.end(); ++it) {
		std::string tmp_itemlist_format = itemlist_format;
		fmtstr_formatter fmt;

		fmt.register_fmt('i', utils::strprintf("%u",it->second + 1));
		fmt.register_fmt('f', gen_flags(it->first));
		fmt.register_fmt('D', gen_datestr(it->first->pubDate_timestamp(), datetimeformat.c_str()));
		if (feed->rssurl() != it->first->feedurl() && it->first->get_feedptr() != NULL) {
			fmt.register_fmt('T', utils::replace_all(it->first->get_feedptr()->title(), "<", "<>"));
		}
		fmt.register_fmt('t', utils::replace_all(it->first->title(), "<", "<>"));
		fmt.register_fmt('a', utils::replace_all(it->first->author(), "<", "<>"));
		fmt.register_fmt('L', it->first->length());

		if (rxman) {
			int id;
			if ((id = rxman->article_matches(it->first.get())) != -1) {
				tmp_itemlist_format = utils::strprintf("<%d>%s</>", id, itemlist_format.c_str());
			}
		}

		listfmt.add_line(fmt.do_format(tmp_itemlist_format, width), it->second);
	}

	f->modify("items","replace_inner", listfmt.format_list(rxman, "articlelist"));

	set_head(feed->title(),feed->unread_item_count(),feed->items().size(), feed->rssurl());

	prepare_set_filterpos();
}

void itemlist_formaction::init() {
	f->set("itempos","0");
	f->set("msg","");
	do_redraw = true;
	set_keymap_hints();
	apply_filter = !(v->get_cfg()->get_configvalue_as_bool("show-read-articles"));
	update_visible_items = true;
	do_update_visible_items();
	if (v->get_cfg()->get_configvalue_as_bool("goto-first-unread")) {
		jump_to_next_unread_item(true);
	}
	f->run(-3); // FRUN - compute all widget dimensions
}

void itemlist_formaction::set_head(const std::string& s, unsigned int unread, unsigned int total, const std::string &url) {
	/*
	 * Since the itemlist_formaction is also used to display search results, we always need to set the right title
	 */
	std::string title;
	fmtstr_formatter fmt;

	std::string listwidth = f->get("items:w");
	std::istringstream is(listwidth);
	unsigned int width;
	is >> width;

	fmt.register_fmt('N', PROGRAM_NAME);
	fmt.register_fmt('V', PROGRAM_VERSION);

	fmt.register_fmt('u', utils::to_s(unread));
	fmt.register_fmt('t', utils::to_s(total));

	fmt.register_fmt('T', s);
	fmt.register_fmt('U', utils::censor_url(url));

	if (!show_searchresult) {
		title = fmt.do_format(v->get_cfg()->get_configvalue("articlelist-title-format"));
	} else {
		title = fmt.do_format(v->get_cfg()->get_configvalue("searchresult-title-format"));
	}
	f->set("head", title);
}

bool itemlist_formaction::jump_to_previous_unread_item(bool start_with_last) {
	int itempos;
	std::istringstream is(f->get("itempos"));
	is >> itempos;
	for (int i=(start_with_last?itempos:(itempos-1));i>=0;--i) {
		LOG(LOG_DEBUG, "itemlist_formaction::jump_to_previous_unread_item: visible_items[%u] unread = %s", i, visible_items[i].first->unread() ? "true" : "false");
		if (visible_items[i].first->unread()) {
			f->set("itempos", utils::to_s(i));
			return true;
		}
	}
	for (int i=visible_items.size()-1;i>=itempos;--i) {
		if (visible_items[i].first->unread()) {
			f->set("itempos", utils::to_s(i));
			return true;
		}
	}
	return false;

}

bool itemlist_formaction::jump_to_random_unread_item() {
	bool has_unread_available = false;
	for (unsigned int i=0;i<visible_items.size();++i) {
		if (visible_items[i].first->unread()) {
			has_unread_available = true;
			break;
		}
	}
	if (has_unread_available) {
		for (;;) {
			unsigned int pos = utils::get_random_value(visible_items.size());
			if (visible_items[pos].first->unread()) {
				f->set("itempos", utils::to_s(pos));
				break;
			}
		}
	}
	return has_unread_available;
}

bool itemlist_formaction::jump_to_next_unread_item(bool start_with_first) {
	unsigned int itempos;
	std::istringstream is(f->get("itempos"));
	is >> itempos;
	LOG(LOG_DEBUG, "itemlist_formaction::jump_to_next_unread_item: itempos = %u visible_items.size = %u", itempos, visible_items.size());
	for (unsigned int i=(start_with_first?itempos:(itempos+1));i<visible_items.size();++i) {
		LOG(LOG_DEBUG, "itemlist_formaction::jump_to_next_unread_item: i = %u", i);
		if (visible_items[i].first->unread()) {
			f->set("itempos", utils::to_s(i));
			return true;
		}
	}
	for (unsigned int i=0;i<=itempos;++i) {
		LOG(LOG_DEBUG, "itemlist_formaction::jump_to_next_unread_item: i = %u", i);
		if (visible_items[i].first->unread()) {
			f->set("itempos", utils::to_s(i));
			return true;
		}
	}
	return false;
}

bool itemlist_formaction::jump_to_previous_item(bool start_with_last) {
	int itempos;
	std::istringstream is(f->get("itempos"));
	is >> itempos;
	for (int i=(start_with_last?itempos:(itempos-1));i>=0;--i) {
		LOG(LOG_DEBUG, "itemlist_formaction::jump_to_previous_item: visible_items[%u]", i);
		f->set("itempos", utils::to_s(i));
		return true;
	}
	return false; // not sure if we should exit here or continue
	// wrap to last item
	for (int i=visible_items.size()-1;i>=itempos;--i) {
		f->set("itempos", utils::to_s(i));
		return true;
	}
	return false;

}

bool itemlist_formaction::jump_to_next_item(bool start_with_first) {
	unsigned int itempos;
	std::istringstream is(f->get("itempos"));
	is >> itempos;
	LOG(LOG_DEBUG, "itemlist_formaction::jump_to_next_item: itempos = %u visible_items.size = %u", itempos, visible_items.size());
	for (unsigned int i=(start_with_first?itempos:(itempos+1));i<visible_items.size();++i) {
		LOG(LOG_DEBUG, "itemlist_formaction::jump_to_next_item: i = %u", i);
		f->set("itempos", utils::to_s(i));
		return true;
	}
	return false; // not sure if we should exit here or continue
	// wrap to first item
	for (unsigned int i=0;i<=itempos;++i) {
		LOG(LOG_DEBUG, "itemlist_formaction::jump_to_next_item: i = %u", i);
		f->set("itempos", utils::to_s(i));
		return true;
	}
	return false;
}

std::string itemlist_formaction::get_guid() {
	unsigned int itempos;
	std::istringstream is(f->get("itempos"));
	is >> itempos;
	return visible_items[itempos].first->guid();
}

keymap_hint_entry * itemlist_formaction::get_keymap_hint() {
	static keymap_hint_entry hints[] = {
		{ OP_QUIT, _("Quit") },
		{ OP_OPEN, _("Open") },
		{ OP_SAVE, _("Save") },
		{ OP_RELOAD, _("Reload") },
		{ OP_NEXTUNREAD, _("Next Unread") },
		{ OP_MARKFEEDREAD, _("Mark All Read") },
		{ OP_SEARCH, _("Search") },
		{ OP_HELP, _("Help") },
		{ OP_NIL, NULL }
	};
	return hints;
}

void itemlist_formaction::handle_cmdline_num(unsigned int idx) {
	if (idx > 0 && idx <= visible_items[visible_items.size()-1].second + 1) {
		int i = get_pos(idx - 1);
		if (i == -1) {
			v->show_error(_("Position not visible!"));
		} else {
			f->set("itempos", utils::to_s(i));
		}
	} else {
		v->show_error(_("Invalid position!"));
	}
}

void itemlist_formaction::handle_cmdline(const std::string& cmd) {
	unsigned int idx = 0;
	if (1==sscanf(cmd.c_str(),"%u",&idx)) {
		handle_cmdline_num(idx);
	} else {
		std::vector<std::string> tokens = utils::tokenize_quoted(cmd);
		if (tokens.size() == 0)
			return;
		if (tokens[0] == "save" && tokens.size() >= 2) {
			std::string filename = utils::resolve_tilde(tokens[1]);
			std::string itemposname = f->get("itempos");
			LOG(LOG_INFO, "itemlist_formaction::handle_cmdline: saving item at pos `%s' to `%s'", itemposname.c_str(), filename.c_str());
			if (itemposname.length() > 0) {
				std::istringstream posname(itemposname);
				unsigned int itempos = 0;
				posname >> itempos;

				save_article(filename, visible_items[itempos].first);
			} else {
				v->show_error(_("Error: no item selected!"));
			}
		} else {
			formaction::handle_cmdline(cmd);
		}
	}
}

int itemlist_formaction::get_pos(unsigned int realidx) {
	for (unsigned int i=0;i<visible_items.size();++i) {
		if (visible_items[i].second == realidx)
			return i;
	}
	return -1;
}

void itemlist_formaction::recalculate_form() {
	formaction::recalculate_form();
	set_update_visible_items(true);

	std::string itemposname = f->get("itempos");
	unsigned int itempos = utils::to_u(itemposname);

	// If the old position was set and it is less than the itempos, use it for the feed's itempos
	// Correct the problem when you open itemview and jump to next then exit to itemlist and the itempos is wrong
	// This only applies when "show-read-articles" is set to false
	if ( (old_itempos != -1) && itempos > (unsigned int)old_itempos
		&& ! v->get_cfg()->get_configvalue_as_bool("show-read-articles") )
	{
		f->set("itempos", utils::strprintf("%u", old_itempos));
		old_itempos = -1; // Reset
	}
}

void itemlist_formaction::save_article(const std::string& filename, std::tr1::shared_ptr<rss_item> item) {
	if (filename == "") {
		v->show_error(_("Aborted saving."));
	} else {
		try {
			v->get_ctrl()->write_item(item, filename);
			v->show_error(utils::strprintf(_("Saved article to %s"), filename.c_str()));
		} catch (...) {
			v->show_error(utils::strprintf(_("Error: couldn't save article to %s"), filename.c_str()));
		}
	}
}

void itemlist_formaction::save_filterpos() {
	std::istringstream is(f->get("itempos"));
	unsigned int i;
	is >> i;
	if (i<visible_items.size()) {
		filterpos = visible_items[i].second;
		set_filterpos = true;
	}
}

void itemlist_formaction::set_regexmanager(regexmanager * r) {
	rxman = r;
	std::vector<std::string>& attrs = r->get_attrs("articlelist");
	unsigned int i=0;
	std::string attrstr;
	for (std::vector<std::string>::iterator it=attrs.begin();it!=attrs.end();++it,++i) {
		attrstr.append(utils::strprintf("@style_%u_normal:%s ", i, it->c_str()));
		attrstr.append(utils::strprintf("@style_%u_focus:%s ", i, it->c_str()));
	}
	std::string textview = utils::strprintf("{list[items] .expand:vh style_normal[listnormal]: style_focus[listfocus]:fg=yellow,bg=blue,attr=bold pos_name[itemposname]: pos[itempos]:0 %s richtext:1}", attrstr.c_str());
	f->modify("items", "replace", textview);
}

std::string itemlist_formaction::gen_flags(std::tr1::shared_ptr<rss_item> item) {
	std::string flags;
	if (item->deleted()) {
		flags.append("D");
	} else if (item->unread()) {
		flags.append("N");
	} else {
		flags.append(" ");
	}
	if (item->flags().length() > 0) {
		flags.append("!");
	} else {
		flags.append(" ");
	}
	return flags;
}

std::string itemlist_formaction::gen_datestr(time_t t, const char * datetimeformat) {
	char datebuf[64];
	struct tm * stm = localtime(&t);
	strftime(datebuf,sizeof(datebuf), datetimeformat, stm);
	return datebuf;
}

void itemlist_formaction::prepare_set_filterpos() {
	if (set_filterpos) {
		set_filterpos = false;
		unsigned int i=0;
		for (std::vector<itemptr_pos_pair>::iterator it=visible_items.begin();it!=visible_items.end();++it, ++i) {
			if (it->second == filterpos) {
				f->set("itempos", utils::to_s(i));
				return;
			}
		}
		f->set("itempos", "0");
	}
}

void itemlist_formaction::set_feed(std::tr1::shared_ptr<rss_feed> fd) {
	LOG(LOG_DEBUG, "itemlist_formaction::set_feed: fd pointer = %p title = `%s'", fd.get(), fd->title().c_str());
	feed = fd;
	feed->load();
	update_visible_items = true;
	do_update_visible_items();
}

std::string itemlist_formaction::title() {
	if (feed->rssurl() == "") {
		return utils::strprintf(_("Search Result - '%s'"), searchphrase.c_str());
	} else {
		if (feed->rssurl().substr(0,6) == "query:")
			return utils::strprintf(_("Query Feed - %s"), feed->rssurl().substr(6,feed->rssurl().length()-6).c_str());
		else
			return utils::strprintf(_("Article List - %s"), feed->title().c_str());
	}
}

}


text:
module ApiVkCom
  class LikesGetList < VkMethod
    @method_name = 'likes.getList'
    PARAMS = { 'count' => 1000 }

    def self.exec(params)
      user_ids, attempt = [], 0

      response = get_users_list(params)
      count = response['count'].to_i
      user_ids.concat(response['users'])
      until user_ids.size >= count
        sleep 0.2
        response = get_users_list(params, attempt += 1)
        user_ids.concat(response['users']).uniq!
      end
      user_ids
    rescue => e
      puts e
      nil
    end

    private

    def self.get_users_list(params, offset = 0)
      params.merge!('offset' => offset * 1000)
      JSON.parse(send_request(params.merge(PARAMS)).body)['response']
    end

  end
end


text:
package org.molasdin.wbase.transaction.exceptions;

/**
 * Created by dbersenev on 15.10.2014.
 */
public class TransactionInterruptedException extends TransactionException  {
}


text:
<!--
  Author:       Sam Ruby (http://intertwingly.net/) and Mark Pilgrim (http://diveintomark.org/)
  Copyright:    Copyright (c) 2003 Sam Ruby and Mark Pilgrim
-->

<!--
  Description:  invalid modified date (date must have hyphens)
  Expect:       InvalidRFC3339Date{parent:feed,element:updated}
-->

<feed xmlns="http://www.w3.org/2005/Atom">
<updated>20021231T19:20:30.45+01:00</updated>
</feed>


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace EnCor.ModuleLoader
{
    public enum ModuleStatus
    {
        New = 0,
        Initialized = 1,
        Start = 8,
        Stop = 16
    }
}


text:
tinystack
=========

C & Python implementations of some different OSI layers protocols,
for building custom communication stacks. Intended for small
embedded systems.

General aims
------------
- Minimal packet overhead

C implementation aims
---------------------
- No dynamic memory use
- Low code space requirement

Dev requirements
================
- python 2.x
- doit: http://pydoit.org/

Credits
=======
- COBS python & c implementation courtesy of Craig McQueen
 - https://pypi.python.org/pypi/cobs
 - https://bitbucket.org/cmcqueen1975/cobs-c/wiki/Home

- Unity C unit test harness from Unity:
 - https://github.com/ThrowTheSwitch/Unity


text:
using System.ComponentModel;

namespace EncompassRest.Loans.Enums
{
    /// <summary>
    /// TypeOfStructure
    /// </summary>
    public enum TypeOfStructure
    {
        /// <summary>
        /// Conventional Construction
        /// </summary>
        [Description("Conventional Construction")]
        Conventional = 0,
        /// <summary>
        /// Singlewide M/H
        /// </summary>
        [Description("Singlewide M/H")]
        Singlewide = 1,
        /// <summary>
        /// Doublewide M/H
        /// </summary>
        [Description("Doublewide M/H")]
        Doublewide = 2,
        /// <summary>
        /// M/H Lot Only
        /// </summary>
        [Description("M/H Lot Only")]
        LotOnly = 3,
        /// <summary>
        /// Prefabricated Home
        /// </summary>
        [Description("Prefabricated Home")]
        PrefabricatedHome = 4,
        /// <summary>
        /// Condominium Conversion
        /// </summary>
        [Description("Condominium Conversion")]
        Condominium = 5
    }
}


text:
using CleanArchitecture.Core.Entities;
using CleanArchitecture.Core.Interfaces;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;

namespace CleanArchitecture.Web.Pages.ToDoRazorPage
{
    public class IndexModel : PageModel
    {
        private readonly IRepository _repository;

        public List<ToDoItem> ToDoItems { get; set; }

        public IndexModel(IRepository repository)
        {
            _repository = repository;
        }

        public void OnGet()
        {
            ToDoItems = _repository.List<ToDoItem>();
        }
    }
}


text:
package org.apache.jena.riot.system;

import org.apache.jena.datatypes.RDFDatatype;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.riot.tokens.Token;
import org.apache.jena.sparql.core.Quad;

/**
 * {@code ParserProfile} is specific to parsing, providing the operations needed by a parser to
 * create IRIs/Nodes/Triples/Quads at the point in the parsing process when the line and
 * column are available to put in error messages.
 * <p>
 * {@code ParserProfile} uses a {@link FactoryRDF} to create items in the parsing
 * process. A {@code ParserProfile} adds handling the position in the parsing stream,
 * and URI processing (prefix mapping and base URI).
 *
 * @see FactoryRDF
 */
public interface ParserProfile {
    /** Resolve a URI, returning a string */
    public String resolveIRI(String uriStr, long line, long col);

    /* Reset the base for IRI resolution. */
    public void setBaseIRI(String baseIRI);

    /** Create a triple */
    public Triple createTriple(Node subject, Node predicate, Node object, long line, long col);

    /** Create a quad */
    public Quad createQuad(Node graph, Node subject, Node predicate, Node object, long line, long col);

    /** Create a URI Node */
    public Node createURI(String uriStr, long line, long col);

    /** Create a literal for a string+datatype */
    public Node createTypedLiteral(String lexical, RDFDatatype datatype, long line, long col);

    /** Create a literal for a string+language */
    public Node createLangLiteral(String lexical, String langTag, long line, long col);

    /** Create a literal for a string */
    public Node createStringLiteral(String lexical, long line, long col);

    /** Create a fresh blank node based on scope and label */
    public Node createBlankNode(Node scope, String label, long line, long col);

    /** Create a fresh blank node */
    public Node createBlankNode(Node scope, long line, long col);

    /** Create a triple node (RDF-star) */
    public Node createTripleNode(Node subject, Node predicate, Node object, long line, long col);

    /** Create a triple node (RDF-star) */
    public Node createTripleNode(Triple triple, long line, long col);

    /** Create a graph node. This is an N3-formula and not named graphs */
    public Node createGraphNode(Graph graph, long line, long col);

    /**
     * Make a node from a token - called after all else has been tried to handle
     * special cases Return null for "no special node recognized"
     */
    public Node createNodeFromToken(Node scope, Token token, long line, long col);

    /** Make any node from a token as appropriate */
    public Node create(Node currentGraph, Token token);

    /** Is this in strict mode? */
    public boolean isStrictMode();

    /* Return the prefix map, if any, used for mapping tokens into Nodes. */
    public PrefixMap getPrefixMap();

    /** Get the {@link ErrorHandler error handler} used by this {@code ParserProfile} */
    public ErrorHandler getErrorHandler();

    /** Get the {@link FactoryRDF factory for RDF terms, triples and quads} */
    public FactoryRDF getFactorRDF();
}


text:
package featureflag

import (
	"github.com/cloudfoundry/cli/cf/api/feature_flags"
	"github.com/cloudfoundry/cli/cf/command_registry"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/simonleung8/flags"
)

type ListFeatureFlags struct {
	ui       terminal.UI
	config   core_config.ReadWriter
	flagRepo feature_flags.FeatureFlagRepository
}

func init() {
	command_registry.Register(&ListFeatureFlags{})
}

func (cmd *ListFeatureFlags) MetaData() command_registry.CommandMetadata {
	return command_registry.CommandMetadata{
		Name:        "feature-flags",
		Description: T("Retrieve list of feature flags with status of each flag-able feature"),
		Usage:       T("CF_NAME feature-flags"),
	}
}

func (cmd *ListFeatureFlags) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) {
	if len(fc.Args()) != 0 {
		cmd.ui.Failed(T("Incorrect Usage. No argument required\n\n") + command_registry.Commands.CommandUsage("feature-flags"))
	}

	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}
	return reqs, err
}

func (cmd *ListFeatureFlags) SetDependency(deps command_registry.Dependency, pluginCall bool) command_registry.Command {
	cmd.ui = deps.Ui
	cmd.config = deps.Config
	cmd.flagRepo = deps.RepoLocator.GetFeatureFlagRepository()
	return cmd
}

func (cmd *ListFeatureFlags) Execute(c flags.FlagContext) {
	cmd.ui.Say(T("Retrieving status of all flagged features as {{.Username}}...", map[string]interface{}{
		"Username": terminal.EntityNameColor(cmd.config.Username())}))

	flags, err := cmd.flagRepo.List()
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	cmd.ui.Ok()
	cmd.ui.Say("")

	table := terminal.NewTable(cmd.ui, []string{T("Features"), T("State")})

	for _, flag := range flags {
		table.Add(
			flag.Name,
			cmd.flagBoolToString(flag.Enabled),
		)
	}

	table.Print()
	return
}

func (cmd ListFeatureFlags) flagBoolToString(enabled bool) string {
	if enabled {
		return "enabled"
	}
	return "disabled"
}


text:
package com.heliosphere.demeter.base.resource;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.commons.io.FilenameUtils;

/**
 * Provides an abstract implementation of a resource.
 *

 * @author Resse Christophe - Heliosphere
 * @version 1.0.0
 */
public abstract class AbstractResource implements IResource
{
	/**
	 * Default serialization identifier.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Underlying file object.
	 */
	private File file = null;

	/**
	 * Creates a new abstract resource given a pathname.
	 *

	 * @param pathname Resource pathname.
	 * @throws ResourceException Thrown in case an error occurred while trying to access the resource.
	 */
	@SuppressWarnings("nls")
	public AbstractResource(String pathname) throws ResourceException
	{
		if (!loadAbsolute(pathname))
		{
			if (!loadRelative(pathname))
			{
				if (!loadRelativeSeparator(pathname))
				{
					throw new ResourceException(String.format("The resource specified by the path name: %1s can not be found", pathname));
				}
			}
		}
	}

	@Override
	public File getFile()
	{
		return file;
	}

	/**
	 * Loads the file considering its pathname is absolute.
	 *

	 * @param pathname Resource path name.
	 * @return {@code True} if the resource can be loaded, {@code false} otherwise.
	 */
	@SuppressWarnings("unused")
	private final boolean loadAbsolute(String pathname)
	{
		this.file = new File(pathname);
		if (!file.exists())
		{
			try
			{
				file.createNewFile();
			}
			catch (IOException ioe)
			{
				return false;
			}
		}

		return this.file.exists();
	}

	/**
	 * Loads the file considering its pathname is relative.
	 *

	 * @param pathname Resource path name.
	 * @return {@code True} if the resource can be loaded, {@code false} otherwise.
	 */
	@SuppressWarnings("unused")
	private final boolean loadRelative(String pathname)
	{
		URL url = null;

		try
		{
			// Maybe the file pathname is relative.
			url = Thread.currentThread().getContextClassLoader().getResource(pathname);

			this.file = new File(url.toURI());
			if (!file.exists())
			{
				try
				{
					file.createNewFile();
				}
				catch (IOException ioe)
				{
					return false;
				}
			}
		}
		catch (Exception e)
		{
			// Try to get the parent directory of the file ... maybe the file does not exist!
			file = new File(pathname);
			String name = FilenameUtils.getName(pathname);
			File directory = file.getParentFile();
			try
			{
				url = Thread.currentThread().getContextClassLoader().getResource(file.getParent());

				try
				{
					file = new File(url.toURI());
					if (directory.exists() && directory.isDirectory())
					{
						// OK, found the parent directory, then create the file as it does not exist.
						file = new File(directory.getAbsolutePath() + File.separator + name);
						try
						{
							file.createNewFile();
						}
						catch (IOException e1)
						{
							return false;
						}
					}
				}
				catch (URISyntaxException urie)
				{
					return false;
				}
			}
			catch (Exception e2)
			{
				return false;
			}
		}

		return this.file.exists();
	}

	/**
	 * Loads the file considering its pathname is relative.
	 *

	 * @param pathname Resource path name.
	 * @return {@code True} if the resource can be loaded, {@code false} otherwise.
	 */
	@SuppressWarnings({ "nls", "unused" })
	private final boolean loadRelativeSeparator(String pathname)
	{
		URL url = null;

		// Try to remove the leading file separator, if one exist.
		if (pathname.startsWith(File.separator))
		{
			try
			{
				// Maybe the file pathname is relative.
				url = Thread.currentThread().getContextClassLoader().getResource(pathname.replaceFirst(File.separator, ""));
				this.file = new File(url.toURI());
				if (!file.exists())
				{
					try
					{
						file.createNewFile();
					}
					catch (IOException ioe)
					{
						return false;
					}
				}
			}
			catch (Exception e)
			{
				// Try to get the parent directory of the file ... maybe the file does not exist!
				file = new File(pathname);
				String name = FilenameUtils.getName(pathname);
				File directory = file.getParentFile();
				try
				{
					url = Thread.currentThread().getContextClassLoader().getResource(file.getParent().replaceFirst(File.separator, ""));

					try
					{
						directory = new File(url.toURI());
						if (directory.getAbsoluteFile().exists() && directory.getAbsoluteFile().isDirectory())
						{
							// OK, found the parent directory, then create the file as it does not exist.
							file = new File(directory.getAbsolutePath() + File.separator + name);
							try
							{
								file.createNewFile();
							}
							catch (IOException e1)
							{
								return false;
							}
						}
					}
					catch (URISyntaxException urie)
					{
						return false;
					}
				}
				catch (Exception e2)
				{
					return false;
				}
			}
		}

		if (file == null)
		{
			return false;
		}

		return this.file.exists();
	}
}


text:
package sk.tomsik68.particleworkshop.impl;

import org.bukkit.entity.Player;

import sk.tomsik68.particleworkshop.ParticleWorkshopPlugin;
import sk.tomsik68.particleworkshop.api.ICostCalculator;
import sk.tomsik68.particleworkshop.api.QuotaManager;

import com.avaje.ebean.EbeanServer;

public class DatabaseQuotaManager extends QuotaManager {

    private EbeanServer db;

    public DatabaseQuotaManager(ICostCalculator cc) {
        super(cc);
    }

    @Override
    public float getFreeQuota(Player player) {
        QuotaData playerData = findPlayerData(player);
        return playerData.getFreeQuota();
    }

    private QuotaData findPlayerData(Player player) {
        return db.find(QuotaData.class).where().ieq("playerID", player.getUniqueId().toString()).findUnique();
    }

    @Override
    public void setFreeQuota(Player player, float quota) {
        QuotaData playerData = findPlayerData(player);
        playerData.setFreeQuota(quota);
        db.update(playerData);
    }

    @Override
    public void loadData(ParticleWorkshopPlugin plugin) {
        db = plugin.getDatabase();
        try {
            db.find(QuotaData.class).findRowCount();
        } catch (Exception e) {
            ParticleWorkshopPlugin.log.info("Installing DB due to first time usage...");
            plugin.installDDL();
            db.find(QuotaData.class).findRowCount();
        }
    }

    @Override
    public void saveData(ParticleWorkshopPlugin plugin) {
    }

    @Override
    public void addQuota(Player player, float add) {
        setFreeQuota(player, getFreeQuota(player) + add);
    }

    @Override
    public void removeQuota(Player player, float remove) {
        // fix values less than 0
        setFreeQuota(player, Math.max(getFreeQuota(player) - remove, 0));
    }

}


text:
PerspectiveCameraController::PerspectiveCameraController()
: m_fovy( 60.0 )
, m_aspect( 1.0 )
, m_theta_cam( PI<GLdouble> / 3.0 )
, m_phi_cam( PI<GLdouble> / 4.0 )
, m_rho_cam( 3.0 )
, m_cam_lookat( Eigen::Matrix<GLdouble,3,1>::Zero() )
, m_cam_psn( Eigen::Matrix<GLdouble,3,1>::Zero() )
, m_up_orientation( Eigen::Quaternion<GLdouble>::Identity() )
{
  updatePositionAndFrame();
}

void PerspectiveCameraController::positionCamera()
{
  {
    Eigen::Matrix<GLdouble,4,4> rotation{ Eigen::Matrix<GLdouble,4,4>::Identity() };
    rotation.block<1,3>(0,0) = m_cam_y;
    rotation.block<1,3>(1,0) = m_cam_x;
    rotation.block<1,3>(2,0) = -m_cam_z;

    assert( ( rotation.block<3,3>(0,0) * rotation.block<3,3>(0,0).transpose() - Eigen::Matrix<GLdouble,3,3>::Identity() ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );

    glMultMatrixd( rotation.data() );
  }

  {
    const Eigen::Matrix<GLdouble,3,1> camera_psn{ m_cam_lookat + m_cam_psn };
    glTranslated( -camera_psn.x(), -camera_psn.y(), -camera_psn.z() );
  }
}

void PerspectiveCameraController::setPerspective( const int width, const int height )
{
  const GLdouble fovy{ 54.43 };
  const GLdouble aspect{ GLdouble( width ) / GLdouble( height ) };
  const GLdouble z_near{ 0.1 };
  const GLdouble z_far{ 1000.0 };

  glViewport( 0, 0, width, height );

  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();

  // TODO: Off by a factor of 2?
  const GLdouble top{ tan( fovy / 360.0 * PI<GLdouble> ) * z_near };
  const GLdouble right{ top * aspect };
  glFrustum( -right, right, -top, top, z_near, z_far );
  m_fovy = fovy;
  m_aspect = aspect;
}

void PerspectiveCameraController::setCamera( const Eigen::Matrix<GLdouble,3,1>& up, const GLdouble& theta, const GLdouble& phi, const GLdouble& rho, const Eigen::Matrix<GLdouble,3,1>& lookat )
{
  m_up_orientation = Eigen::Quaternion<GLdouble>::FromTwoVectors( Eigen::Matrix<GLdouble,3,1>::UnitY(), up );
  assert( fabs( m_up_orientation.norm() - 1.0 ) < 1.0e-6 );
  m_theta_cam = theta;
  m_phi_cam = phi;
  assert( rho > 0.0 );
  m_rho_cam = rho;
  m_cam_lookat = lookat;

  updatePositionAndFrame();
}

void PerspectiveCameraController::centerCameraAtSphere( const Eigen::Matrix<GLdouble,3,1>& center, const GLdouble& radius )
{
  m_cam_lookat = center;

  const GLdouble degrees_to_radians{ PI<GLdouble> / 180.0 };
  const GLdouble d1{ radius / sin( 0.5 * m_fovy * degrees_to_radians ) };
  const GLdouble d2{ radius / sin( 0.5 * m_aspect * m_fovy * degrees_to_radians ) };

  m_rho_cam = std::max( d1, d2 );

  updatePositionAndFrame();
}

void PerspectiveCameraController::addToDistFromCenter( const GLdouble& dst_amnt )
{
  m_rho_cam = std::max( m_rho_cam + dst_amnt, 0.1 );
  updatePositionAndFrame();
}

const GLdouble& PerspectiveCameraController::getDistFromCenter() const
{
  return m_rho_cam;
}

void PerspectiveCameraController::addToZenithAngle( const GLdouble& znth_amnt )
{
  m_theta_cam += znth_amnt;
  if( m_theta_cam < 0.0 )
  {
    m_theta_cam = 0.0;
  }
  if( m_theta_cam > PI<GLdouble> )
  {
    m_theta_cam = PI<GLdouble>;
  }
  updatePositionAndFrame();
}

void PerspectiveCameraController::addToAzimuthAngle( const GLdouble& azmth_amnt )
{
  m_phi_cam += azmth_amnt;
  updatePositionAndFrame();
}

void PerspectiveCameraController::trackCameraHorizontal( const GLdouble& hrz_amnt  )
{
  m_cam_lookat += hrz_amnt * m_cam_y;
}

void PerspectiveCameraController::trackCameraVertical( const GLdouble& vrt_amnt  )
{
  m_cam_lookat += vrt_amnt * m_cam_x;
}

void PerspectiveCameraController::updatePositionAndFrame()
{
  assert( fabs( m_up_orientation.norm() - 1.0 ) < 1.0e-6 );

  m_cam_psn = m_up_orientation * Eigen::Matrix<GLdouble,3,1>{ sin(m_theta_cam) * sin(m_phi_cam), cos(m_theta_cam), sin(m_theta_cam) * cos(m_phi_cam) };
  m_cam_z = -1.0 * m_cam_psn;
  m_cam_psn *= m_rho_cam;
  m_cam_y = m_up_orientation * Eigen::Matrix<GLdouble,3,1>{ cos(m_phi_cam), 0.0, -sin(m_phi_cam) };
  m_cam_x = m_cam_y.cross( m_cam_z );

  assert( fabs( m_cam_x.norm() - 1.0 ) < 1.0e-6 );
  assert( fabs( m_cam_y.norm() - 1.0 ) < 1.0e-6 );
  assert( fabs( m_cam_z.norm() - 1.0 ) < 1.0e-6 );
}

void PerspectiveCameraController::reset()
{
  *this = PerspectiveCameraController();
}


text:
// Created by mooming.go@gmail.com 2022

#include "OSThread.h"

#include "Engine.h"
#include <thread>

void OS::Yield()
{
    std::this_thread::yield();
}

void OS::Sleep(uint32_t milliseconds)
{
    std::this_thread::sleep_for(std::chrono::microseconds(milliseconds));
}

#ifdef __linux__
#include <sched.h>

int OS::GetCPUIndex()
{
    return sched_getcpu();
}

void OS::SetThreadAffinity(std::thread& thread, uint64_t mask)
{
    static_assert(false, "Not implemented yet.");
}

void SetThreadPriority(std::thread& thread, int priority)
{
    static_assert(false, "Not implemented yet.");
}

#elif defined __APPLE__
#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include "Log/Logger.h"
#include "String/StringUtil.h"
#include <pthread.h>

int OS::GetCPUIndex()
{
    size_t cpuNumber = 0;
    auto result = pthread_cpu_number_np(&cpuNumber);
    if (unlikely(result != 0))
    {
        using namespace HE;
        using namespace StringUtil;
        auto funcName = PrettyFunctionToFunctionName(__PRETTY_FUNCTION__);
        auto log = Logger::Get(funcName);

        log.OutError([](auto& ls)
        {
            ls << "failed to get cpu number";
        });

        return -1;
    }

    return static_cast<int>(cpuNumber);
}

int OS::GetThreadPriority(std::thread& thread)
{
    auto nativeHandle = thread.native_handle();

    int policy = 0;
    struct sched_param sp;

    auto result = pthread_getschedparam(nativeHandle, &policy, &sp);
    if (unlikely(result != 0))
    {
        using namespace HE;
        using namespace StringUtil;
        auto funcName = PrettyFunctionToFunctionName(__PRETTY_FUNCTION__);
        auto log = Logger::Get(funcName);

        switch (result)
        {
            case ESRCH:
                log.OutError([](auto& ls)
                {
                    ls << "Non-existent thread.";
                });
                break;

            default:
                log.OutError([result](auto& ls)
                {
                    ls << "Unexpected error code = " << result;
                });
                break;
        }

        return -1;
    }

    return sp.sched_priority;
}

void OS::SetThreadAffinity(std::thread& thread, uint64_t mask)
{
    // Not supproted on Apple Silicon
}

void OS::SetThreadPriority(std::thread& thread, int priority)
{
    auto nativeHandle = thread.native_handle();

    struct sched_param sp;
    memset(&sp, 0, sizeof(decltype(sp)));
    sp.sched_priority = priority;

    constexpr int policy = SCHED_FIFO;
    auto result = pthread_setschedparam(nativeHandle, policy, &sp);
    if (unlikely(result != 0))
    {
        using namespace HE;
        auto log = Logger::Get("OS::Thread");

        switch (result)
        {
            case EINVAL:
                log.OutError([policy](auto& ls)
                {
                    ls << "Invalid value for policy. Input policy = " << policy;
                });
                break;

            case ENOTSUP:
                log.OutError([](auto& ls)
                {
                    ls << "Invalid value for scheduling parameters.";
                });
                break;

            case ESRCH:
                log.OutError([](auto& ls)
                {
                    ls << "Non-existent thread.";
                });
                break;

            default:
                log.OutError([result](auto& ls)
                {
                    ls << "Unexpected error code = " << result;
                });
                break;
        }
    }
}
#elif defined _WIN32
#include <Windows.h>

int OS::GetCPUIndex()
{
    auto index = GetCurrentProcessorNumber();
    return static_cast<int>(index);
}

void OS::SetThreadAffinity(std::thread& thread, uint64_t mask)
{
    ::SetThreadAffinityMask(thread.native_handle(), mask);
}

void OS::SetThreadPriority(std::thread& thread, int priority)
{
    auto result = ::SetThreadPriority(thread.native_handle(), priority);
    if (result == false)
    {
        auto& engine = HE::Engine::Get();
        engine.LogError([](auto& ls)
        {
            ls << "SetThreadPriority failed.";
        });
    }
}
#else
static_assert(false, "System is not specified.");
#endif

#ifdef __UNIT_TEST__

void HE::OSThreadTest::Prepare()
{
    // TODO
}

#endif //__UNIT_TEST__


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE email_texts SYSTEM "../../../../../lib/pkp/dtd/emailTemplateData.dtd">

<email_texts locale="id_ID">
	<email_text key="PAYPAL_INVESTIGATE_PAYMENT">
	<subject> Kegiatan pembayaran paypal yang tidak biasa </subject>
		<body> IOJS telah menemukan kegiatan yang tidak biasa yang berhubungan dengan bantuan pembayaran paypal untuk jurnal {$contextName}. Kegiatan ini mungkin dibutuhkan investigasi yang lebih lanjut atau intervensi manual. Emai ini diciptakan oleh OJS PayPal plugin.
Informasi posting penuh untuk permohonan:
{$postInfo}
Informasi tambahan (jika tersedia):
{$additionalInfo}
Variasi Server :
{$serverVars}
</body>
		<description> Email ini digunakan untuk memberitahukan jurnal kontak utama yang mempunyai kegiatan yang mencurigakan atau kegiatan yang membutuhkan intervensi manual yang ditemukan oleh plugin paypal.</description>
	</email_text>
</email_texts>


text:
package discordgo

import (
	"net/http"
	"strconv"
	"testing"
	"time"
)

// This test takes ~2 seconds to run
func TestRatelimitReset(t *testing.T) {
	rl := NewRatelimiter()

	sendReq := func(endpoint string) {
		bucket, id := rl.LockBucket(endpoint)

		headers := http.Header(make(map[string][]string))

		headers.Set("X-RateLimit-Remaining", "0")
		// Reset for approx 2 seconds from now
		headers.Set("X-RateLimit-Reset-After", "2")
		headers.Set("Date", time.Now().Format(time.RFC850))

		err := bucket.Release(headers, id)
		if err != nil {
			t.Errorf("Release returned error: %v", err)
		}
	}

	sent := time.Now()
	sendReq("/guilds/99/channels")
	sendReq("/guilds/55/channels")
	sendReq("/guilds/66/channels")

	sendReq("/guilds/99/channels")
	sendReq("/guilds/55/channels")
	sendReq("/guilds/66/channels")

	// We hit the same endpoint 2 times, so we should only be ratelimited 2 second
	// And always less than 4 seconds (unless you're on a stoneage computer or using swap or something...)
	if time.Since(sent) >= time.Second && time.Since(sent) < time.Second*4 {
		t.Log("OK", time.Since(sent))
	} else {
		t.Error("Did not ratelimit correctly, got:", time.Since(sent))
	}
}

// This test takes ~1 seconds to run
func TestRatelimitGlobal(t *testing.T) {
	rl := NewRatelimiter()

	sendReq := func(endpoint string) {
		bucket, id := rl.LockBucket(endpoint)

		headers := http.Header(make(map[string][]string))

		headers.Set("X-RateLimit-Global", "1")
		// Reset for approx 1 seconds from now
		headers.Set("Retry-After", "1000")

		err := bucket.Release(headers, id)
		if err != nil {
			t.Errorf("Release returned error: %v", err)
		}
	}

	sent := time.Now()

	// This should trigger a global ratelimit
	sendReq("/guilds/99/channels")
	time.Sleep(time.Millisecond * 100)

	// This shouldn't go through in less than 1 second
	sendReq("/guilds/55/channels")

	if time.Since(sent) >= time.Second && time.Since(sent) < time.Second*2 {
		t.Log("OK", time.Since(sent))
	} else {
		t.Error("Did not ratelimit correctly, got:", time.Since(sent))
	}
}

func BenchmarkRatelimitSingleEndpoint(b *testing.B) {
	rl := NewRatelimiter()
	rl.MaxConcurrentRequests = 10
	for i := 0; i < b.N; i++ {
		sendBenchReq("/guilds/99/channels", rl)
	}
}

func BenchmarkRatelimitParallelMultiEndpoints(b *testing.B) {
	rl := NewRatelimiter()
	rl.MaxConcurrentRequests = 10
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			sendBenchReq("/guilds/"+strconv.Itoa(i)+"/channels", rl)
			// i++
		}
	})
}

// Does not actually send requests, but locks the bucket and releases it with made-up headers
func sendBenchReq(endpoint string, rl *RateLimiter) {
	bucket, id := rl.LockBucket(endpoint)

	headers := http.Header(make(map[string][]string))

	headers.Set("X-RateLimit-Remaining", "10")
	headers.Set("X-RateLimit-Reset", strconv.FormatInt(time.Now().Unix(), 10))
	headers.Set("Date", time.Now().Format(time.RFC850))

	time.Sleep(time.Millisecond * 100)

	bucket.Release(headers, id)
}


text:
function [Y, lbls, Ytest] = readMovieLensMarlinStrong(partNo)

% READMOVIELENSMARLINSTRONG Read in Marlin's strong partitions for movielens 1M.
% FORMAT
% DESC reads the Movielens 1M Marlin strong partitions.
% ARG partNo : the part of the Movielens data to read in.
% RETURN Y : the data.
% RETURN lbls : the labels associated with the movies.
% RETURN Ytest : the test data.
%
% SEEALSO : collabLoadData, readMovieLensMarlinWeak
%
% COPYRIGHT : Raquel Urtasun, 2009

% COLLAB

lbls = [];

baseDir = datasetsDirectory;
dirSep = filesep;

% load the ratings

fileName = [baseDir dirSep 'collab' dirSep 'project' dirSep '1mml-mmmf' dirSep 'data' dirSep 'marlin.mat'];

disp(['Reading ... ',fileName]);

load(fileName);

Y = weaktrain{partNo}';
lbls = strongtrain{partNo}';
Ytest = strongtest{partNo}';


text:
<?php
/**
 * Created by PhpStorm.
 * User: trasweb
 * Date: 24/01/18
 * Time: 19:11
 */

namespace Team\Data;

class Formatter
{
    protected $data;

    public function __construct(array $data = []) {
        $this->data = $data;
    }

    public static function change(array $data, string $toFormat = 'string', array $arguments = []) {
        $formatter = new Formatter($data);
        return $formatter->$toFormat($arguments);
    }

    public function url($options = []) {
        return http_build_query($this->data);
    }

    public function terminal($options = []) {
        if(!empty($this->data) ) {
            foreach($this->data as $_key => $_value) {
                if(!is_array($_value) && !is_object($_value) )
                    echo "{$_key} => {$_value}\n";
            }
        }
        return "";
    }

    public function string($options = []) {
        return  print_r($this->data,true);
    }

    public function params($options = []) {
        $separator_fields = $options['fields']?? '="';
        $separator_params = $options['params']?? ' ';
        $end = $options['end']?? '"';
        $prefix = $options['prefix']?? 'param_';

        $result = '';
        foreach($this->data as $field => $value) {
            if(is_numeric($field) ) {
                $name = $prefix.$field;
            }else {
                $name = $field;
            }

            $result .= "{$separator_params}{$name}{$separator_fields}{$end}";
        }
        return ltrim($result, $separator_params);
    }

    public function object($options = []) {
        return (object) $this->data;
    }

    public function xml($options = []) {
        return  $this->array_to_xml($this->data, new \SimpleXMLElement('<root/>'))->asXML();
    }

    protected function array_to_xml(array $arr,  $xml)
    {
        foreach ($arr as $k => $v) {
            is_array($v)
                ? $this->array_to_xml($v, $xml->addChild($k))
                : $xml->addChild($k, $v);
        }
        return $xml;
    }

    public function json($options = []) {
        $data = $this->convert_entities($this->data);

        return json_encode($data);
    }

    private function  convert_entities($data) {
        if (is_array($data)) {
            return array_map([$this, 'convert_entities'],$data);
        }

        if (is_numeric($data)) {
            return (strpos('.', $data)===false)? (float)$data : (int)$data;
        }

        if('UTF-8' != \Team\Config::get('CHARSET') ) {
            $data = \Team\Data\Sanitize::toJs((string)$data);
            return utf8_encode($data);
        }else {
            return (string)$data;
        }
    }

    public function html($options = []) {
        $type_engine = $this->data["HTML_ENGINE"]?? \Team\Config::get("HTML_ENGINE");

        $engine = $this->getHtmlEngine($type_engine);

        return $engine->transform($this->data);
    }

    private function getHtmlEngine($type_engine) {

        $type_engine = $this->filterEngine($type_engine, "TemplateEngine");
        if(!isset($type_engine) ) return null;

        $class = \Team\Data\Filter::apply('\team\htmlengine\\'.$type_engine, '\Team\Data\Htmlengine\\'.$type_engine);

        return  \Team\Loader\Classes::factory($class, true);
    }

    private function filterEngine($type, $default) {
        return  ucfirst(\team\data\Check::key($type, $default));
    }
}


text:
<?php

namespace MySQLConcentrator;

class Buffer
{
  public $buffer;
  public $max_size;

  public function __construct($initial_data = '', $max_size = 4096)
  {
    $this->buffer = $initial_data;
    $this->max_size = $max_size;
  }

  public function append($data)
  {
    if (strlen($data) > $this->space_remaining())
    {
      throw new MySQLConcentratorBufferException("Can't append '" . hex_dump(substr($data, 0, 10)) . "...' to buffer because data is " . strlen($data) . " bytes long and there is only space remaining for " . $this->space_remaining() . ".");
    }
    $this->buffer .= $data;
  }

  public function is_empty()
  {
    return ($this->buffer == '');
  }

  public function length()
  {
    return strlen($this->buffer);
  }

  public function pop($length = NULL)
  {
    if ($length === NULL)
    {
      $length = $this->length();
    }
    $result = substr($this->buffer, 0, $length);
    $this->buffer = substr($this->buffer, $length);
    return $result;
  }

  public function space_remaining()
  {
    return $this->max_size - count($this->buffer);
  }
}