text:
/*!
 * \file   event_log_backend.cpp
 * \author Andrey Semashev
 * \date   07.11.2008
 *
 * \brief  A logging sink backend that uses Windows NT event log API
 *         for signalling application events.
 */

#ifndef BOOST_LOG_WITHOUT_EVENT_LOG

#include <boost/log/detail/config.hpp>
#include <string>
#include <vector>
#include <ostream>
#include <stdexcept>
#include <boost/scoped_array.hpp>
#include <boost/system/windows_error.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/sinks/event_log_backend.hpp>
#include <boost/log/sinks/event_log_constants.hpp>
#include <boost/log/utility/once_block.hpp>
#include <boost/log/detail/cleanup_scope_guard.hpp>
#include <boost/log/detail/attachable_sstream_buf.hpp>
#include <boost/log/detail/code_conversion.hpp>
#include <boost/log/utility/formatting_ostream.hpp>
#include <windows.h>
#include <psapi.h>
#include "unique_ptr.hpp"
#include "windows/event_log_registry.hpp"
#include "windows/simple_event_log.h"
#include <boost/log/detail/header.hpp>

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace sinks {

namespace event_log {

    //! The function constructs log record level from an integer
    BOOST_LOG_API event_type make_event_type(unsigned short lev)
    {
        switch (lev)
        {
        case success: return success;
        case warning: return warning;
        case error: return error;
        default:
            BOOST_THROW_EXCEPTION(std::out_of_range("Windows NT event type is out of range"));
            BOOST_LOG_UNREACHABLE_RETURN(info);
        case info: return info;
        }
    }

} // namespace event_log

BOOST_LOG_ANONYMOUS_NAMESPACE {

#ifdef BOOST_LOG_USE_CHAR
    //! A simple forwarder to the ReportEvent API
    inline BOOL report_event(
        HANDLE hEventLog,
        WORD wType,
        WORD wCategory,
        DWORD dwEventID,
        PSID lpUserSid,
        WORD wNumStrings,
        DWORD dwDataSize,
        const char** lpStrings,
        LPVOID lpRawData)
    {
        return ReportEventA(hEventLog, wType, wCategory, dwEventID, lpUserSid, wNumStrings, dwDataSize, lpStrings, lpRawData);
    }
    //! A simple forwarder to the GetModuleFileName API
    inline DWORD get_module_file_name(HMODULE hModule, char* lpFilename, DWORD nSize)
    {
        return GetModuleFileNameA(hModule, lpFilename, nSize);
    }
    //! A simple forwarder to the RegisterEventSource API
    inline HANDLE register_event_source(const char* lpUNCServerName, const char* lpSourceName)
    {
        return RegisterEventSourceA(lpUNCServerName, lpSourceName);
    }
    //! The function completes default source name for the sink backend
    inline void complete_default_simple_event_log_source_name(std::string& name)
    {
        name += " simple event source";
    }
    //! The function completes default source name for the sink backend
    inline void complete_default_event_log_source_name(std::string& name)
    {
        name += " event source";
    }
#endif // BOOST_LOG_USE_CHAR

#ifdef BOOST_LOG_USE_WCHAR_T
    //! A simple forwarder to the ReportEvent API
    inline BOOL report_event(
        HANDLE hEventLog,
        WORD wType,
        WORD wCategory,
        DWORD dwEventID,
        PSID lpUserSid,
        WORD wNumStrings,
        DWORD dwDataSize,
        const wchar_t** lpStrings,
        LPVOID lpRawData)
    {
        return ReportEventW(hEventLog, wType, wCategory, dwEventID, lpUserSid, wNumStrings, dwDataSize, lpStrings, lpRawData);
    }
    //! A simple forwarder to the GetModuleFileName API
    inline DWORD get_module_file_name(HMODULE hModule, wchar_t* lpFilename, DWORD nSize)
    {
        return GetModuleFileNameW(hModule, lpFilename, nSize);
    }
    //! A simple forwarder to the RegisterEventSource API
    inline HANDLE register_event_source(const wchar_t* lpUNCServerName, const wchar_t* lpSourceName)
    {
        return RegisterEventSourceW(lpUNCServerName, lpSourceName);
    }
    //! The function completes default source name for the sink backend
    inline void complete_default_simple_event_log_source_name(std::wstring& name)
    {
        name += L" simple event source";
    }
    //! The function completes default source name for the sink backend
    inline void complete_default_event_log_source_name(std::wstring& name)
    {
        name += L" event source";
    }
#endif // BOOST_LOG_USE_WCHAR_T

    //! The function finds the handle for the current module
    void init_self_module_handle(HMODULE& handle)
    {
        // Acquire all modules of the current process
        HANDLE hProcess = GetCurrentProcess();
        std::vector< HMODULE > modules;
        DWORD module_count = 1024;
        do
        {
            modules.resize(module_count, HMODULE(0));
            BOOL res = EnumProcessModules(
                hProcess,
                &modules[0],
                static_cast< DWORD >(modules.size() * sizeof(HMODULE)),
                &module_count);
            module_count /= sizeof(HMODULE);

            if (!res)
            {
                DWORD err = GetLastError();
                BOOST_LOG_THROW_DESCR_PARAMS(system_error, "Could not enumerate process modules", (err));
            }
        }
        while (module_count > modules.size());
        modules.resize(module_count, HMODULE(0));

        // Now find the current module among them
        void* p = (void*)&init_self_module_handle;
        for (std::size_t i = 0, n = modules.size(); i < n; ++i)
        {
            MODULEINFO info;
            if (!GetModuleInformation(hProcess, modules[i], &info, sizeof(info)))
            {
                DWORD err = GetLastError();
                BOOST_LOG_THROW_DESCR_PARAMS(system_error, "Could not acquire module information", (err));
            }

            if (info.lpBaseOfDll <= p && (static_cast< unsigned char* >(info.lpBaseOfDll) + info.SizeOfImage) > p)
            {
                // Found it
                handle = modules[i];
                break;
            }
        }

        if (!handle)
            BOOST_LOG_THROW_DESCR_PARAMS(system_error, "Could not find self module information", (boost::system::windows_error::invalid_handle));
    }

    //! Retrieves the full name of the current module (be that dll or exe)
    template< typename CharT >
    std::basic_string< CharT > get_current_module_name()
    {
        static HMODULE hSelfModule = 0;

        BOOST_LOG_ONCE_BLOCK()
        {
            init_self_module_handle(hSelfModule);
        }

        // Get the module file name
        CharT buf[MAX_PATH];
        DWORD size = get_module_file_name(hSelfModule, buf, sizeof(buf) / sizeof(*buf));
        if (size == 0)
        {
            DWORD err = GetLastError();
            BOOST_LOG_THROW_DESCR_PARAMS(system_error, "Could not get module file name", (err));
        }

        return std::basic_string< CharT >(buf, buf + size);
    }

} // namespace

//////////////////////////////////////////////////////////////////////////
//  Simple event log backend implementation
//////////////////////////////////////////////////////////////////////////
//! Sink backend implementation
template< typename CharT >
struct basic_simple_event_log_backend< CharT >::implementation
{
    //! A handle for the registered event provider
    HANDLE m_SourceHandle;
    //! A level mapping functor
    event_type_mapper_type m_LevelMapper;

    implementation() : m_SourceHandle(0)
    {
    }
};

//! Default constructor. Registers event source Boost.Log <Boost version> in the Application log.
template< typename CharT >
BOOST_LOG_API basic_simple_event_log_backend< CharT >::basic_simple_event_log_backend()
{
    construct(log::aux::empty_arg_list());
}

//! Destructor
template< typename CharT >
BOOST_LOG_API basic_simple_event_log_backend< CharT >::~basic_simple_event_log_backend()
{
    DeregisterEventSource(m_pImpl->m_SourceHandle);
    delete m_pImpl;
}

//! Constructs backend implementation
template< typename CharT >
BOOST_LOG_API void basic_simple_event_log_backend< CharT >::construct(
    string_type const& target, string_type const& log_name, string_type const& source_name, event_log::registration_mode reg_mode)
{
    if (reg_mode != event_log::never)
    {
        aux::registry_params< char_type > reg_params;
        reg_params.event_message_file = get_current_module_name< char_type >();
        reg_params.types_supported = DWORD(
            EVENTLOG_SUCCESS |
            EVENTLOG_INFORMATION_TYPE |
            EVENTLOG_WARNING_TYPE |
            EVENTLOG_ERROR_TYPE);
        aux::init_event_log_registry(log_name, source_name, reg_mode == event_log::forced, reg_params);
    }

    log::aux::unique_ptr< implementation > p(new implementation());

    const char_type* target_unc = NULL;
    if (!target.empty())
        target_unc = target.c_str();

    HANDLE hSource = register_event_source(target_unc, source_name.c_str());
    if (!hSource)
    {
        const DWORD err = GetLastError();
        BOOST_LOG_THROW_DESCR_PARAMS(system_error, "Could not register event source", (err));
    }

    p->m_SourceHandle = hSource;

    m_pImpl = p.release();
}

//! Returns default log name
template< typename CharT >
BOOST_LOG_API typename basic_simple_event_log_backend< CharT >::string_type
basic_simple_event_log_backend< CharT >::get_default_log_name()
{
    return aux::registry_traits< char_type >::make_default_log_name();
}

//! Returns default source name
template< typename CharT >
BOOST_LOG_API typename basic_simple_event_log_backend< CharT >::string_type
basic_simple_event_log_backend< CharT >::get_default_source_name()
{
    string_type source_name = aux::registry_traits< char_type >::make_default_source_name();
    complete_default_simple_event_log_source_name(source_name);
    return source_name;
}

//! The method installs the function object that maps application severity levels to WinAPI event types
template< typename CharT >
BOOST_LOG_API void basic_simple_event_log_backend< CharT >::set_event_type_mapper(event_type_mapper_type const& mapper)
{
    m_pImpl->m_LevelMapper = mapper;
}

//! The method puts the formatted message to the event log
template< typename CharT >
BOOST_LOG_API void basic_simple_event_log_backend< CharT >::consume(record_view const& rec, string_type const& formatted_message)
{
    const char_type* message = formatted_message.c_str();
    event_log::event_type evt_type = event_log::info;
    if (!m_pImpl->m_LevelMapper.empty())
        evt_type = m_pImpl->m_LevelMapper(rec);

    DWORD event_id;
    switch (evt_type)
    {
    case event_log::success:
        event_id = BOOST_LOG_MSG_DEBUG; break;
    case event_log::warning:
        event_id = BOOST_LOG_MSG_WARNING; break;
    case event_log::error:
        event_id = BOOST_LOG_MSG_ERROR; break;
    default:
        event_id = BOOST_LOG_MSG_INFO; break;
    }

    report_event(
        m_pImpl->m_SourceHandle,        // Event log handle.
        static_cast< WORD >(evt_type),  // Event type.
        0,                              // Event category.
        event_id,                       // Event identifier.
        NULL,                           // No user security identifier.
        1,                              // Number of substitution strings.
        0,                              // No data.
        &message,                       // Pointer to strings.
        NULL);                          // No data.
}

//////////////////////////////////////////////////////////////////////////
//  Customizable event log backend implementation
//////////////////////////////////////////////////////////////////////////
namespace event_log {

    template< typename CharT >
    class basic_event_composer< CharT >::insertion_composer
    {
    public:
        //! Function object result type
        typedef void result_type;

    private:
        //! The list of insertion composers (in backward order)
        typedef std::vector< formatter_type > formatters;

    private:
        //! The insertion string composers
        formatters m_Formatters;

    public:
        //! Default constructor
        insertion_composer() {}
        //! Composition operator
        void operator() (record_view const& rec, insertion_list& insertions) const
        {
            std::size_t size = m_Formatters.size();
            insertions.resize(size);
            for (std::size_t i = 0; i < size; ++i)
            {
                typename formatter_type::stream_type strm(insertions[i]);
                m_Formatters[i](rec, strm);
                strm.flush();
            }
        }
        //! Adds a new formatter to the list
        void add_formatter(formatter_type const& fmt)
        {
            m_Formatters.push_back(formatter_type(fmt));
        }
    };

    //! Default constructor
    template< typename CharT >
    basic_event_composer< CharT >::basic_event_composer(event_id_mapper_type const& id_mapper) :
        m_EventIDMapper(id_mapper)
    {
    }
    //! Copy constructor
    template< typename CharT >
    basic_event_composer< CharT >::basic_event_composer(basic_event_composer const& that) :
        m_EventIDMapper(that.m_EventIDMapper),
        m_EventMap(that.m_EventMap)
    {
    }
    //! Destructor
    template< typename CharT >
    basic_event_composer< CharT >::~basic_event_composer()
    {
    }

    //! Assignment
    template< typename CharT >
    basic_event_composer< CharT >& basic_event_composer< CharT >::operator= (basic_event_composer that)
    {
        swap(that);
        return *this;
    }
    //! Swapping
    template< typename CharT >
    void basic_event_composer< CharT >::swap(basic_event_composer& that)
    {
        m_EventIDMapper.swap(that.m_EventIDMapper);
        m_EventMap.swap(that.m_EventMap);
    }
    //! Creates a new entry for a message
    template< typename CharT >
    typename basic_event_composer< CharT >::event_map_reference
    basic_event_composer< CharT >::operator[] (event_id id)
    {
        return event_map_reference(id, *this);
    }
    //! Creates a new entry for a message
    template< typename CharT >
    typename basic_event_composer< CharT >::event_map_reference
    basic_event_composer< CharT >::operator[] (int id)
    {
        return event_map_reference(make_event_id(id), *this);
    }

    //! Event composition operator
    template< typename CharT >
    event_id basic_event_composer< CharT >::operator() (record_view const& rec, insertion_list& insertions) const
    {
        event_id id = m_EventIDMapper(rec);
        typename event_map::const_iterator it = m_EventMap.find(id);
        if (it != m_EventMap.end())
            it->second(rec, insertions);
        return id;
    }

    //! Adds a formatter to the insertion composers list
    template< typename CharT >
    typename basic_event_composer< CharT >::insertion_composer*
    basic_event_composer< CharT >::add_formatter(event_id id, insertion_composer* composer, formatter_type const& fmt)
    {
        if (!composer)
            composer = &m_EventMap[id];
        composer->add_formatter(fmt);
        return composer;
    }

#ifdef BOOST_LOG_USE_CHAR
    template class BOOST_LOG_API basic_event_composer< char >;
#endif
#ifdef BOOST_LOG_USE_WCHAR_T
    template class BOOST_LOG_API basic_event_composer< wchar_t >;
#endif

} // namespace event_log

//! Backend implementation
template< typename CharT >
struct basic_event_log_backend< CharT >::implementation
{
    //  NOTE: This order of data members is critical for MSVC 9.0 in debug mode,
    //        as it ICEs if boost::functions are not the first members. Doh!

    //! An event category mapper
    event_category_mapper_type m_CategoryMapper;
    //! A level mapping functor
    event_type_mapper_type m_LevelMapper;

    //! A handle for the registered event provider
    HANDLE m_SourceHandle;
    //! A functor that composes an event
    event_composer_type m_EventComposer;
    //! An array of formatted insertions
    insertion_list m_Insertions;

    implementation() : m_SourceHandle(0)
    {
    }
};

//! Destructor
template< typename CharT >
BOOST_LOG_API basic_event_log_backend< CharT >::~basic_event_log_backend()
{
    DeregisterEventSource(m_pImpl->m_SourceHandle);
    delete m_pImpl;
}

//! Constructs backend implementation
template< typename CharT >
BOOST_LOG_API void basic_event_log_backend< CharT >::construct(
    filesystem::path const& message_file_name,
    string_type const& target,
    string_type const& log_name,
    string_type const& source_name,
    event_log::registration_mode reg_mode)
{
    if (reg_mode != event_log::never)
    {
        if (message_file_name.empty())
            BOOST_THROW_EXCEPTION(std::invalid_argument("Message file name not specified."));
        aux::registry_params< char_type > reg_params;
        string_type file_name;
        log::aux::code_convert(message_file_name.string(), file_name);
        reg_params.event_message_file = file_name;
        reg_params.types_supported = DWORD(
            EVENTLOG_SUCCESS |
            EVENTLOG_INFORMATION_TYPE |
            EVENTLOG_WARNING_TYPE |
            EVENTLOG_ERROR_TYPE);
        aux::init_event_log_registry(log_name, source_name, reg_mode == event_log::forced, reg_params);
    }

    log::aux::unique_ptr< implementation > p(new implementation());

    const char_type* target_unc = NULL;
    if (!target.empty())
        target_unc = target.c_str();

    HANDLE hSource = register_event_source(target_unc, source_name.c_str());
    if (!hSource)
    {
        const DWORD err = GetLastError();
        BOOST_LOG_THROW_DESCR_PARAMS(system_error, "Could not register event source", (err));
    }

    p->m_SourceHandle = hSource;

    m_pImpl = p.release();
}

//! The method puts the formatted message to the event log
template< typename CharT >
BOOST_LOG_API void basic_event_log_backend< CharT >::consume(record_view const& rec)
{
    if (!m_pImpl->m_EventComposer.empty())
    {
        log::aux::cleanup_guard< insertion_list > cleaner(m_pImpl->m_Insertions);

        // Get event ID and construct insertions
        DWORD id = m_pImpl->m_EventComposer(rec, m_pImpl->m_Insertions);
        WORD string_count = static_cast< WORD >(m_pImpl->m_Insertions.size());
        scoped_array< const char_type* > strings(new const char_type*[string_count]);
        for (WORD i = 0; i < string_count; ++i)
            strings[i] = m_pImpl->m_Insertions[i].c_str();

        // Get event type
        WORD event_type = EVENTLOG_INFORMATION_TYPE;
        if (!m_pImpl->m_LevelMapper.empty())
            event_type = static_cast< WORD >(m_pImpl->m_LevelMapper(rec));

        WORD event_category = 0;
        if (!m_pImpl->m_CategoryMapper.empty())
            event_category = static_cast< WORD >(m_pImpl->m_CategoryMapper(rec));

        report_event(
            m_pImpl->m_SourceHandle,       // Event log handle.
            event_type,                    // Event type.
            event_category,                // Event category.
            id,                            // Event identifier.
            NULL,                          // No user security identifier.
            string_count,                  // Number of substitution strings.
            0,                             // No data.
            strings.get(),                 // Pointer to strings.
            NULL);                         // No data.
    }
}

//! Returns default log name
template< typename CharT >
BOOST_LOG_API typename basic_event_log_backend< CharT >::string_type
basic_event_log_backend< CharT >::get_default_log_name()
{
    return aux::registry_traits< char_type >::make_default_log_name();
}

//! Returns default source name
template< typename CharT >
BOOST_LOG_API typename basic_event_log_backend< CharT >::string_type
basic_event_log_backend< CharT >::get_default_source_name()
{
    string_type source_name = aux::registry_traits< char_type >::make_default_source_name();
    complete_default_event_log_source_name(source_name);
    return source_name;
}

//! The method installs the function object that maps application severity levels to WinAPI event types
template< typename CharT >
BOOST_LOG_API void basic_event_log_backend< CharT >::set_event_type_mapper(event_type_mapper_type const& mapper)
{
    m_pImpl->m_LevelMapper = mapper;
}

//! The method installs the function object that extracts event category from attribute values
template< typename CharT >
BOOST_LOG_API void basic_event_log_backend< CharT >::set_event_category_mapper(event_category_mapper_type const& mapper)
{
    m_pImpl->m_CategoryMapper = mapper;
}

/*!
 * The method installs the function object that extracts event identifier from the attributes and creates
 * insertion strings that will replace placeholders in the event message.
 */
template< typename CharT >
BOOST_LOG_API void basic_event_log_backend< CharT >::set_event_composer(event_composer_type const& composer)
{
    m_pImpl->m_EventComposer = composer;
}

#ifdef BOOST_LOG_USE_CHAR
template class basic_simple_event_log_backend< char >;
template class basic_event_log_backend< char >;
#endif
#ifdef BOOST_LOG_USE_WCHAR_T
template class basic_simple_event_log_backend< wchar_t >;
template class basic_event_log_backend< wchar_t >;
#endif

} // namespace sinks

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // !defined(BOOST_LOG_WITHOUT_EVENT_LOG)


text:
#ifndef SIDECAR_GUI_STRINGSETTING_H // -*- C++ -*-
#define SIDECAR_GUI_STRINGSETTING_H

#include "GUI/Setting.h"

namespace SideCar {
namespace GUI {

/** Derivation of the Setting class that manages boolean values.
 */
class StringSetting : public Setting {
    Q_OBJECT
    using Super = Setting;

public:
    /** Constructor.

        \param mgr

        \param name

        \param global
    */
    StringSetting(PresetManager* mgr, const QString& name, bool global = false);

    /** Constructor.

        \param mgr

        \param name

        \param value

        \param global
    */
    StringSetting(PresetManager* mgr, const QString& name, const QString& value, bool global = false);

    /** Obtain the current setting value.

        \return setting value
    */
    const QString& getValue() const { return value_; }

public slots:

    /** Change the setting value. Emits the valueChanged() signal if the given value is diferent than the held
        one.

        \param value new value to use
    */
    void setValue(const QString& value);

signals:

    /** Notification sent out when the held value changes.

        \param value new held value
    */
    void valueChanged(const QString& value);

protected:
    /** Override of Setting::valueUpdated() method. Records the new value and emits the valueChanged() signal.
     */
    void valueUpdated();

private:
    QString value_;
};

} // end namespace GUI
} // end namespace SideCar

#endif

redpajama_set_name: RedPajamaGithub


text:
	<?php
		include_once("procesar-mostrar-followers-ipe2.php");
		$query="SELECT DISTINCT * FROM rrss WHERE persona_id=".$_SESSION['id'];
		$result=mysqli_query($mysqli,$query)or die (mysqli_error());
		$row= mysqli_fetch_array($result, MYSQLI_BOTH);
		$num_row=mysqli_num_rows($result);
		$redes_sociales= muestra_followers($_SESSION['id']);
		$html_redes_sociales=explode(';', $redes_sociales);

		$facebook=explode("!",$html_redes_sociales[0]);
		$html_facebook= $facebook[0];
		$reach_facebook = $facebook[1];

		$instagram=explode("!",$html_redes_sociales[1]);
		$html_instagram= $instagram[0];
		$reach_instagram = $instagram[1];

		$twitter=explode("!",$html_redes_sociales[2]);
		$html_twitter= $twitter[0];
		$reach_twitter = $twitter[1];

		$youtube=explode("!",$html_redes_sociales[3]);
		$html_youtube= $youtube[0];
		$reach_youtube = $youtube[1];

		$suma=(int)($reach_facebook+$reach_instagram+$reach_twitter);

		$query_facebook="SELECT DISTINCT * FROM rrss WHERE persona_id='".$_SESSION['id']."' AND descripcion_rrss='facebook' AND cuenta='1'";
		$result_facebook=mysqli_query($mysqli,$query_facebook)or die (mysqli_error());
		$num_row_facebook= mysqli_num_rows($result_facebook);

		$query_instagram="SELECT DISTINCT * FROM rrss WHERE persona_id='".$_SESSION['id']."' AND descripcion_rrss='instagram' AND cuenta='1'";
		$result_instagram=mysqli_query($mysqli,$query_instagram)or die (mysqli_error());
		$num_row_instagram= mysqli_num_rows($result_instagram);

		$query_twitter="SELECT DISTINCT * FROM rrss WHERE persona_id='".$_SESSION['id']."' AND descripcion_rrss='twitter' AND cuenta='1'";
		$result_twitter=mysqli_query($mysqli,$query_twitter)or die (mysqli_error());
		$num_row_twitter= mysqli_num_rows($result_twitter);

		$query_youtube="SELECT DISTINCT * FROM rrss WHERE persona_id='".$_SESSION['id']."' AND descripcion_rrss='youtube' AND cuenta='1'";
		$result_youtube=mysqli_query($mysqli,$query_youtube)or die (mysqli_error());
		$num_row_youtube= mysqli_num_rows($result_youtube);

		if($num_row < 1){
			echo '

					<svg style="display:none;">
						<symbol id="poly-gon" viewBox="0 0 140.341 133.52">
							<polygon points="134,98.26 70.5,129.76 7,98.26 7,35.26 70.5,3.76 134,35.26"/>
						</symbol>
					</svg>

						<svg class="poly-gon" viewBox="0 0 140.341 133.52">
							<use xlink:href="#poly-gon"/>
						</svg>

';
		}else{
			echo '

Alcance social
Alcance total de tus redes sociales
'.formato_numeros_reachs($suma).'

';
		}
	?>

 Facebook

		<?php
			if($num_row_facebook>0){
				$query_likes_facebook="SELECT DISTINCT core.followers FROM rrss as red, core_redes_sociales as core WHERE red.persona_id='".$_SESSION['id']."' AND red.rrss_id = core.rrss_id and descripcion_rrss='facebook' and id_estado='1'";
				$result_likes_facebook=mysqli_query($mysqli,$query_likes_facebook)or die (mysqli_error());
				$likes_facebook=0;
				do{
					$row_likes_facebook= mysqli_fetch_array($result_likes_facebook, MYSQLI_BOTH);
					$likes_facebook += $row_likes_facebook[0];

				}while($row_likes_instagram = mysqli_fetch_array($result_likes_facebook));

				echo '
alcance social '.formato_numeros_reachs($likes_facebook).'
';
				echo $html_facebook;
			}
		?>

Conectar Facebook

 Instagram

		<?php
			if($num_row_instagram>0){
				echo '
alcance social '.formato_numeros_reachs($reach_instagram).'
';
				echo $html_instagram;

	  		}
		?>

Conectar Instagram

 Twitter

		<?php
			if($num_row_twitter>0){
				echo '
alcance social '.formato_numeros_reachs($reach_twitter).'
';
				echo $html_twitter;
			}
		?>
		<a id="twitter-inscription" href="./rrss/twitter/process.php" value="<?php //echo $num_row3;?>" class="btns">Conectar Twitter

 Youtube

		<?php
			if($num_row_youtube>0){

				echo '
reproducciones'.$reach_youtube.'
';
				echo $html_youtube;
			}
		?>

Conectar Youtube

<?php
	unset($mysqli);
?>


text:
/**
 * Colors
 */
/**
 * Breakpoints & Media Queries
 */
/**
 * SCSS Variables.
 *
 * Please use variables from this sheet to ensure consistency across the UI.
 * Don't add to this sheet unless you're pretty sure the value will be reused in many places.
 * For example, don't add rules to this sheet that affect block visuals. It's purely for UI.
 */
/**
 * Colors
 */
/**
 * Fonts & basic variables.
 */
/**
 * Grid System.
 * https://make.wordpress.org/design/2019/10/31/proposal-a-consistent-spacing-system-for-wordpress/
 */
/**
 * Dimensions.
 */
/**
 * Shadows.
 */
/**
 * Editor widths.
 */
/**
 * Block & Editor UI.
 */
/**
 * Block paddings.
 */
/**
 * React Native specific.
 * These variables do not appear to be used anywhere else.
 */
/**
*  Converts a hex value into the rgb equivalent.
*
* @param {string} hex - the hexadecimal value to convert
* @return {string} comma separated rgb values
*/
/**
 * Breakpoint mixins
 */
/**
 * Long content fade mixin
 *
 * Creates a fading overlay to signify that the content is longer
 * than the space allows.
 */
/**
 * Focus styles.
 */
/**
 * Applies editor left position to the selector passed as argument
 */
/**
 * Styles that are reused verbatim in a few places
 */
/**
 * Allows users to opt-out of animations via OS-level preferences.
 */
/**
 * Reset default styles for JavaScript UI based pages.
 * This is a WP-admin agnostic reset
 */
/**
 * Reset the WP Admin page styles for Gutenberg-like pages.
 */
.wp-block-pullquote {
  margin: 0 0 1em 0;
  padding: 3em 0;
  text-align: center;
  overflow-wrap: break-word;
  box-sizing: border-box;
}
.wp-block-pullquote p,
.wp-block-pullquote blockquote,
.wp-block-pullquote cite {
  color: inherit;
}
.wp-block-pullquote.has-text-align-left, .wp-block-pullquote.has-text-align-right, .wp-block-pullquote.alignleft, .wp-block-pullquote.alignright {
  max-width: 420px;
}
.wp-block-pullquote.has-text-align-left p, .wp-block-pullquote.has-text-align-right p, .wp-block-pullquote.alignleft p, .wp-block-pullquote.alignright p {
  font-size: 1.25em;
}
.wp-block-pullquote p {
  font-size: 1.75em;
  line-height: 1.6;
}
.wp-block-pullquote cite,
.wp-block-pullquote footer {
  position: relative;
}
.wp-block-pullquote .has-text-color a {
  color: inherit;
}

.wp-block-pullquote.has-text-align-left blockquote {
  text-align: left;
}

.wp-block-pullquote.has-text-align-right blockquote {
  text-align: right;
}

.wp-block-pullquote.is-style-solid-color {
  border: none;
}
.wp-block-pullquote.is-style-solid-color blockquote {
  margin-left: auto;
  margin-right: auto;
  max-width: 60%;
}
.wp-block-pullquote.is-style-solid-color blockquote p {
  margin-top: 0;
  margin-bottom: 0;
  font-size: 2em;
}
.wp-block-pullquote.is-style-solid-color blockquote cite {
  text-transform: none;
  font-style: normal;
}

.wp-block-pullquote cite {
  color: inherit;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

using Messages;
using Messages.custom_msgs;
using Messages.roscpp_tutorials;
using Ros_CSharp;
using XmlRpc_Wrapper;
using Int32 = Messages.std_msgs.Int32;
using String = Messages.std_msgs.String;
using m = Messages.std_msgs;
using gm = Messages.geometry_msgs;
using nm = Messages.nav_msgs;
using sm = Messages.sensor_msgs;
//using d = System.Drawing;
using cm = Messages.custom_msgs;
using tf = Messages.tf;

namespace ServiceTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private NodeHandle nodeHandle;
        private string NODE_NAME = "ServiceTest";
        //private ServiceServer<Messages.roscpp_tutorials.TwoInts, Messages.roscpp_tutorials.TwoInts.Request, Messages.roscpp_tutorials.TwoInts.Response> server;
        private ServiceClient<Messages.roscpp_tutorials.TwoInts.Request, Messages.roscpp_tutorials.TwoInts.Response> client;

        private bool addition(Messages.roscpp_tutorials.TwoInts.Request req, ref Messages.roscpp_tutorials.TwoInts.Response resp)
        {
            resp.sum = req.a + req.b;
            return true;
        }

        public MainWindow()
        {
            InitializeComponent();
        }
         private void Window_Loaded(object sender, RoutedEventArgs e)
         {
            ROS.ROS_MASTER_URI = "http://10.0.2.88:11311";
            ROS.ROS_HOSTNAME = "10.0.2.152";
            ROS.Init(new string[0], NODE_NAME);

            nodeHandle = new NodeHandle();

            //server = nodeHandle.advertiseService<Messages.roscpp_tutorials.TwoInts, Messages.roscpp_tutorials.TwoInts.Request, Messages.roscpp_tutorials.TwoInts.Response>("/add_two_ints", addition);
            client = nodeHandle.serviceClient<Messages.roscpp_tutorials.TwoInts.Request, Messages.roscpp_tutorials.TwoInts.Response>("/add_two_ints");

            new Thread(new ThreadStart(() =>
                {
                    Random r = new Random();
                    while (!ROS.shutting_down)
                    {
                        TwoInts.Request req = new TwoInts.Request() { a = r.Next(100), b = r.Next(100) };
                        TwoInts.Response resp = new TwoInts.Response();
                        if (client.call(req, ref resp))
                            Dispatcher.Invoke(new Action(() =>
                                {
                                    math.Content = "" + req.a + " + " + req.b + " = " + resp.sum;
                                }));
                        Thread.Sleep(500);
                    }
                })).Start();
        }

        protected override void OnClosed(EventArgs e)
        {
            ROS.shutdown();
            base.OnClosed(e);
        }
    }
}


text:
<?php
	return array(
		'connectionString' => 'mysql:host=localhost;dbname=sm',
		'emulatePrepare' => true,
		'username' => 'root',
		'password' => '',
		'charset' => 'utf8',
		'tablePrefix' => 'sd_',
		'enableProfiling'=>true,
		'enableParamLogging'=>true,
	)
?>


text:
using std::string;

typedef bool (*BrainfuckWriter)(void* writer_arg, char c);
typedef char (*BrainfuckReader)(void* reader_arg);

class BrainfuckRunner {
 public:
  // Initialize the runner using the Brainfuck opcodes between the given
  // iterators. Returns false if the Brainfuck code is invalid (i.e. there
  // is a "[" with a matching "]") or there is another initialization error.
  virtual bool init(string::const_iterator start,
                    string::const_iterator end) = 0;

  // Runs the Brainfuck code given in "init" using the provided memory.
  // When "," is evaluated, call reader(reader_arg).
  // When "." is evaluated, call writer(writer_arg, <char to write>)
  // The return value is the location of the data pointer
  // (see http://en.wikipedia.org/wiki/Brainfuck#Commands) when the code is
  // finished being executed.
  virtual void* run(BrainfuckReader reader,
                    void* reader_arg,
                    BrainfuckWriter writer,
                    void* writer_arg,
                    void* memory) = 0;
};

#endif  // BF_RUNNER_H_


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.osconfig.v1beta.model;

/**
 * Represents a single apt package repository. These will be added to a repo file that will be
 * managed at /etc/apt/sources.list.d/google_osconfig.list.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud OS Config API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class RepositoryResourceAptRepository extends com.google.api.client.json.GenericJson {

  /**
   * Type of archive files in this repository. The default behavior is DEB.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String archiveType;

  /**
   * List of components for this repository. Must contain at least one item.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> components;

  /**
   * Distribution of this repository.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String distribution;

  /**
   * URI of the key file for this repository. The agent will maintain a keyring at
   * /etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String gpgKey;

  /**
   * URI for this repository.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String uri;

  /**
   * Type of archive files in this repository. The default behavior is DEB.
   * @return value or {@code null} for none
   */
  public java.lang.String getArchiveType() {
    return archiveType;
  }

  /**
   * Type of archive files in this repository. The default behavior is DEB.
   * @param archiveType archiveType or {@code null} for none
   */
  public RepositoryResourceAptRepository setArchiveType(java.lang.String archiveType) {
    this.archiveType = archiveType;
    return this;
  }

  /**
   * List of components for this repository. Must contain at least one item.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getComponents() {
    return components;
  }

  /**
   * List of components for this repository. Must contain at least one item.
   * @param components components or {@code null} for none
   */
  public RepositoryResourceAptRepository setComponents(java.util.List<java.lang.String> components) {
    this.components = components;
    return this;
  }

  /**
   * Distribution of this repository.
   * @return value or {@code null} for none
   */
  public java.lang.String getDistribution() {
    return distribution;
  }

  /**
   * Distribution of this repository.
   * @param distribution distribution or {@code null} for none
   */
  public RepositoryResourceAptRepository setDistribution(java.lang.String distribution) {
    this.distribution = distribution;
    return this;
  }

  /**
   * URI of the key file for this repository. The agent will maintain a keyring at
   * /etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg.
   * @return value or {@code null} for none
   */
  public java.lang.String getGpgKey() {
    return gpgKey;
  }

  /**
   * URI of the key file for this repository. The agent will maintain a keyring at
   * /etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg.
   * @param gpgKey gpgKey or {@code null} for none
   */
  public RepositoryResourceAptRepository setGpgKey(java.lang.String gpgKey) {
    this.gpgKey = gpgKey;
    return this;
  }

  /**
   * URI for this repository.
   * @return value or {@code null} for none
   */
  public java.lang.String getUri() {
    return uri;
  }

  /**
   * URI for this repository.
   * @param uri uri or {@code null} for none
   */
  public RepositoryResourceAptRepository setUri(java.lang.String uri) {
    this.uri = uri;
    return this;
  }

  @Override
  public RepositoryResourceAptRepository set(String fieldName, Object value) {
    return (RepositoryResourceAptRepository) super.set(fieldName, value);
  }

  @Override
  public RepositoryResourceAptRepository clone() {
    return (RepositoryResourceAptRepository) super.clone();
  }

}


text:
package ru.job4j.chess;

import java.util.Arrays;

public class Board {
    /*
        private Figure[] figures = new Figure[]{new Rook(new Cell(0, 0), true), new Knight(new Cell(1, 0), true), new Bishop(new Cell(2, 0), true), new Queen(new Cell(3, 0), true),
                new King(new Cell(4, 0), true), new Bishop(new Cell(5, 0), true), new Knight(new Cell(6, 0), true), new Rook(new Cell(7, 0), true),
                new Pawn(new Cell(0, 1), true), new Pawn(new Cell(1, 1), true), new Pawn(new Cell(2, 1), true), new Pawn(new Cell(3, 1), true),
                new Pawn(new Cell(4, 1), true), new Pawn(new Cell(5, 1), true), new Pawn(new Cell(6, 1), true), new Pawn(new Cell(7, 1), true),
                new Pawn(new Cell(0, 6), false), new Pawn(new Cell(1, 6), false), new Pawn(new Cell(2, 6), false), new Pawn(new Cell(3, 6), false),
                new Pawn(new Cell(4, 6), false), new Pawn(new Cell(5, 6), false), new Pawn(new Cell(6, 6), false), new Pawn(new Cell(7, 6), false),
                new Rook(new Cell(0, 7), false), new Knight(new Cell(1, 7), false), new Bishop(new Cell(2, 7), false), new Queen(new Cell(3, 7), false),
                new King(new Cell(4, 7), false), new Bishop(new Cell(5, 7), false), new Knight(new Cell(6, 7), false), new Rook(new Cell(7, 7), false)};
    */
    private Figure[] figures;

    public Board(Figure[] figures) {
        this.figures = figures;
    }

    public boolean move(Cell source, Cell dist) throws ImposibleMoveException, OccupiedWayException, FigureNotFoundException {
        boolean step = false;
        for (Figure figure : figures) {
            if (figure.rightCell(source)) {
                try {
                    Cell[] cells = figure.way(dist);
                    for(int i =0; i<cells.length; i++) {
                        for (Figure figureint : figures) {
                            if (figureint.rightCell(cells[i])) {
                                throw new OccupiedWayException();
                            }
                        }
                    }
                    figure.clone(dist);
                    step = true;
                } catch (ImposibleMoveException ime) {
                    throw ime;
                }
                break;
            } else {
                throw new FigureNotFoundException();
            }
        }
        return step;
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <title>utils</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />

<big></big>

utils

Index

Contents

Functions

Modules

stringutil

random

noisemanager

nodeutil

posutil

objectrefutil

nodeboxutil

mapmanipulator

fisheryates

textureutil

blockutil

tango

arraymanipulator

inventoryutil

entityutil

scheduler

blockedcache

mathutil

log

arrayutil

directmapmanipulator

rotationutil

settings

pathutil

wallmountedutil

interpolate

transform

numberutil

test

facedirutil

constants

minetestex

list

stopwatch

itemutil

color

tableutil

Module fisheryates

An implementation of the Fisher-Yates algorithm, which allows to access
 an array in a random or pseudo-random order.

Functions

	run (data, min, max, random, action)
	Runs the Fisher-Yates algorithm on the given data.

Functions

    run (data, min, max, random, action)

    Runs the Fisher-Yates algorithm on the given data.

 The given action method is invoked on each item, which means that the action
 method gets items in random order.

Parameters:

data
         The array on which to operate.

min
         The minimum index of the array (inclusive).

max
         The maximum index of the array (inclusive).

random
         The method that returns random numbers, assumed to accept two
               parameters, a minimum and maximum value. Can also be a table
               with an instance method like the one descriped above.

action
         The action to perform on each item. Assumed to accept two
               parameters, the item and the current index.

generated by LDoc 1.4.2


text:
package coder36.sbent.sql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;

/**
 * Map result set onto an array of Longs.  Assumes all columns are of type
 * java.lang.long
 * @author Mark Middleton
 */
public class LongRowMapper implements RowMapper<Long[]> {

	public Long[] mapRow( ResultSet rs, int rowNum ) {
		try {
			List<Long> l = new ArrayList<Long>();
			for ( int i = 1; i <= rs.getMetaData().getColumnCount(); i++  ) {
				l.add( rs.getLong(i) );
			}
			return l.toArray( new Long[0] );
		}
		catch( SQLException s ) {
			throw new RuntimeException(s);
		}
	}
}


text:
#region LGPL License

#endregion LGPL License

#region Using Directives

using System;

using System.Collections;

using System.Diagnostics;

using Axiom.Core;

using Axiom.MathLib;

using Axiom.Collections;

using Axiom.Media;

using Axiom.Graphics;

using Axiom.SceneManagers.PagingLandscape.Collections;

#endregion Using Directives

namespace Axiom.SceneManagers.PagingLandscape.Renderable

{

	enum Stitch_Shift : int

	{

		North = 0,

		South = 8,

		West = 16,

		East = 24

	}

	enum Stitch_Direction : long

	{

		North	=  128L << Stitch_Shift.North,
		South	=  128L << Stitch_Shift.South,
		West	=  128L << Stitch_Shift.West,
        East	=  128L << Stitch_Shift.East
	}

	/// <summary>

	/// Summary description for IndexBuffer.

	/// </summary>

	public class IndexBuffer: IDisposable

	{

		#region Fields
		protected long tileSize;

		protected ArrayList cache;
		/// Shared array of IndexData (reuse indexes across tiles)
		protected ArrayList levelIndex;
		// Store the indexes for every combination
		protected long numIndexes;
		#endregion Fields

		#region Singleton Implementation

		/// <summary>

		/// Constructor

		/// </summary>

		public IndexBuffer()

		{

			if (instance != null)

			{

				throw new ApplicationException("IndexBuffer.Constructor() called twice!");

			}

			instance = this;

			tileSize = Options.Instance.TileSize + 1;
			numIndexes = Options.Instance.MaxRenderLevel + 1;
			//mLevelIndex.reserve (mNumIndexes);
			cache = new ArrayList();
			levelIndex = new ArrayList((int)numIndexes);
			for ( long i = 0; i < numIndexes; i++ )
			{
				levelIndex.Add( new Map() );
			}
		}

		private static IndexBuffer instance = null;

		public static IndexBuffer Instance

		{

			get

			{

				return instance;

			}

		}

		#endregion Singleton Implementation

		#region IDisposable Implementation

		public void Dispose()

		{

			if (instance == this)

			{

				levelIndex.Clear();

				cache.Clear();

				instance = null;

			}

		}

		#endregion IDisposable Implementation

		//public IndexData GetIndex( int LOD)
		//{
		//}

		/** Utility method to generate stitching indexes on the edge of a tile
		@param neighbor The neighbor direction to stitch
		@param hiLOD The LOD of this tile
		@param loLOD The LOD of the neighbor
		@param omitFirstTri Whether the first tri of the stitch (always clockwise
		relative to the centre of this tile) is to be omitted because an
		adjoining edge is also being stitched
		@param omitLastTri Whether the last tri of the stitch (always clockwise
		relative to the centre of this tile) is to be omitted because an
		adjoining edge is also being stitched
		@param pIdx Pointer to a pointer to the index buffer to push the results
		into (this pointer will be updated)
		@returns The number of indexes added
		*/
		public long StitchEdge(Neighbor neighbor, long hiLOD, long loLOD, bool omitFirstTri, bool omitLastTri, IntPtr Idx, ref long pos)
		{
			Debug.Assert( loLOD > hiLOD );
			/*
			Now do the stitching; we can stitch from any level to any level.
			The stitch pattern is like this for each pair of vertices in the lower LOD
			(excuse the poor ascii art):

			lower LOD
			*-----------*
			|\  \ 3 /  /|
			|1\2 \ / 4/5|
			*--*--*--*--*
			higher LOD

			The algorithm is, for each pair of lower LOD vertices:
			1. Iterate over the higher LOD vertices, generating tris connected to the
			first lower LOD vertex, up to and including 1/2 the span of the lower LOD
			over the higher LOD (tris 1-2). Skip the first tri if it is on the edge
			of the tile and that edge is to be stitched itself.
			2. Generate a single tri for the middle using the 2 lower LOD vertices and
			the middle vertex of the higher LOD (tri 3).
			3. Iterate over the higher LOD vertices from 1/2 the span of the lower LOD
			to the end, generating tris connected to the second lower LOD vertex
			(tris 4-5). Skip the last tri if it is on the edge of a tile and that
			edge is to be stitched itself.

			The same algorithm works for all edges of the patch; stitching is done
			clockwise so that the origin and steps used change, but the general
			approach does not.
			*/

			// Work out the steps ie how to increment indexes
			// Step from one vertex to another in the high detail version
			int step = 1 << (int)hiLOD;
			// Step from one vertex to another in the low detail version
			int superstep = 1 << (int)loLOD;
			// Step half way between low detail steps
			int halfsuperstep = superstep >> 1;

			// Work out the starting points and sign of increments
			// We always work the strip clockwise
			int startx = 0, starty = 0, endx = 0, rowstep = 0;
			bool horizontal = false;
			switch(neighbor)
			{
				case Neighbor.North:
					startx = starty = 0;
					endx =  (int)this.tileSize - 1;
					rowstep = step;
					horizontal = true;
					break;
				case Neighbor.South:
					// invert x AND y direction, helps to keep same winding
					startx = starty = (int)this.tileSize - 1;
					endx = 0;
					rowstep = -step;
					step = -step;
					superstep = -superstep;
					halfsuperstep = -halfsuperstep;
					horizontal = true;
					break;
				case Neighbor.East:
					startx = 0;
					endx = (int)this.tileSize - 1;
					starty = (int)this.tileSize - 1;
					rowstep = -step;
					horizontal = false;
					break;
				case Neighbor.West:
					startx = (int)this.tileSize  - 1;
					endx = 0;
					starty = 0;
					rowstep = step;
					step = -step;
					superstep = -superstep;
					halfsuperstep = -halfsuperstep;
					horizontal = false;
					break;
				default:
					break;
			};

			long numStitches = 0;

			unsafe
			{
				ushort* pIdx = (ushort *)Idx.ToPointer();
				for ( int j = startx; j != endx; j += superstep )
				{
					int k;
					for (k = 0; k != halfsuperstep; k += step)
					{
						int jk = j + k;
						//skip the first bit of the corner?
						if ( j != startx || k != 0 || !omitFirstTri )
						{
							if (horizontal)
							{
								pIdx[pos++] = index( j , starty );						numStitches++;
								pIdx[pos++] = index( jk, starty + rowstep );			numStitches++;
								pIdx[pos++] = index( jk + step, starty + rowstep );		numStitches++;
							}
							else
							{
								pIdx[pos++] = index( starty, j );						numStitches++;
								pIdx[pos++] = index( starty + rowstep, jk );			numStitches++;
								pIdx[pos++] = index( starty + rowstep, jk + step);		numStitches++;
							}
						}
					}

					// Middle tri
					if (horizontal)
					{
						pIdx[pos++] = index( j, starty );								numStitches++;
						pIdx[pos++] = index( j + halfsuperstep, starty + rowstep);		numStitches++;
						pIdx[pos++] = index( j + superstep, starty );					numStitches++;
					}
					else
					{
						pIdx[pos++] = index( starty, j );								numStitches++;
						pIdx[pos++] = index( starty + rowstep, j + halfsuperstep );		numStitches++;
						pIdx[pos++] = index( starty, j + superstep );					numStitches++;
					}

					for (k = halfsuperstep; k != superstep; k += step)
					{
						int jk = j + k;
						if ( j != endx - superstep || k != superstep - step || !omitLastTri )
						{
							if (horizontal)
							{
								pIdx[pos++] = index( j + superstep, starty );			numStitches++;
								pIdx[pos++] = index( jk, starty + rowstep );			numStitches++;
								pIdx[pos++] = index( jk + step, starty + rowstep );		numStitches++;
							}
							else
							{
								pIdx[pos++] = index( starty, j + superstep );			numStitches++;
								pIdx[pos++] = index( starty + rowstep, jk );			numStitches++;
								pIdx[pos++] = index( starty + rowstep, jk + step );		numStitches++;
							}
						}
					}
				}
			}

			return numStitches;
		}

		/// Gets the index data for this tile based on current settings
		public IndexData GetIndexData( long stitchFlags, long RenderLevel, Renderable[] neighbors)
		{
			Debug.Assert (levelIndex[ (int)RenderLevel ] != null);
			IEnumerator ii = ((Axiom.Collections.Map)(levelIndex[ (int)RenderLevel ])).Find( (long)stitchFlags );
			if ( ii == null)
			{
				// Create
				IndexData indexData = GenerateTriListIndexes((long)stitchFlags, RenderLevel, neighbors);
				((Axiom.Collections.Map)(levelIndex[ (int)RenderLevel ])).Insert((long) stitchFlags, indexData );
				return indexData;
			}
			else
			{
				ii.MoveNext();
				return (IndexData)ii.Current;
			}
		}

		/// Internal method for generating triangle list terrain indexes
		public IndexData GenerateTriListIndexes( long stitchFlags, long RenderLevel, Renderable[] neighbors)
		{
			long step = (1L << (int)RenderLevel);
			long north = ((stitchFlags & (long)Stitch_Direction.North) != 0 ? step : 0);
			long south = ((stitchFlags & (long)Stitch_Direction.South) != 0 ? step : 0);
			long east =  ((stitchFlags & (long)Stitch_Direction.East)  != 0 ? step : 0);
			long west =  ((stitchFlags & (long)Stitch_Direction.West)  != 0 ? step : 0);

			long new_length = ( tileSize * tileSize * 6 ) / step;

			IndexData indexData = new IndexData();
			indexData.indexBuffer =
			HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, (int)new_length, BufferUsage.StaticWriteOnly);

			cache.Add( indexData );

			/** Returns the index into the height array for the given coordinates. */
			IntPtr ipIdx = indexData.indexBuffer.Lock(0,indexData.indexBuffer.Size,BufferLocking.Discard);
			numIndexes = 0;

			long pos = 0;
			long step_offset = step * tileSize;
			long height_count = north * tileSize;
			unsafe
			{
				ushort* pIdx = (ushort *)ipIdx.ToPointer();
				for (long j = north; j < tileSize - 1 - south; j += step )
				{
					for (long i = west; i <  tileSize - 1 - east; i += step )
					{
						//triangles

						pIdx[pos++] = (ushort) (i        + height_count);                 numIndexes++;
						pIdx[pos++] = (ushort) (i        + height_count + step_offset);   numIndexes++;
						pIdx[pos++] = (ushort) (i + step + height_count);                 numIndexes++;

						pIdx[pos++] = (ushort) (i        + height_count + step_offset);   numIndexes++;
						pIdx[pos++] = (ushort) (i + step + height_count + step_offset);   numIndexes++;
						pIdx[pos++] = (ushort) (i + step + height_count);                 numIndexes++;

					}
					height_count += step_offset;
				}

			}

			// North stitching
			if ( north != 0 )
			{
				numIndexes += StitchEdge(Neighbor.North, RenderLevel, neighbors[(int)Neighbor.North].RenderLevel,
					west > 0 , east > 0 , ipIdx,ref pos);
			}
			// East stitching
			if ( east != 0 )
			{
				numIndexes += StitchEdge(Neighbor.East, RenderLevel, neighbors[(int)Neighbor.East].RenderLevel,
					north > 0, south > 0, ipIdx,ref pos);
			}
			// South stitching
			if ( south != 0 )
			{
				numIndexes += StitchEdge(Neighbor.South, RenderLevel, neighbors[(int)Neighbor.South].RenderLevel,
					east > 0 , west > 0, ipIdx,ref pos);
			}
			// West stitching
			if ( west != 0 )
			{
				numIndexes += StitchEdge(Neighbor.West, RenderLevel, neighbors[(int)Neighbor.West].RenderLevel,
					south > 0 , north > 0, ipIdx,ref pos);
			}

			indexData.indexBuffer.Unlock();
			indexData.indexCount = (int)numIndexes;
			indexData.indexStart = 0;

			return indexData;
		}

		/** Returns the index into the height array for the given coordinates. */
		protected ushort index( int x, int z )
		{
			return (ushort)(x + z * tileSize);
		}

	}

}


text:
    <div class="footer">
        <!-- echo out the content of the SESSION via KINT, a Composer-loaded much better version of var_dump -->
        <!-- KINT can be used with the simple function d() -->
        <?php d($_SESSION); ?>
    </div>
</body>
</html>


text:
module SpreeNoShipping
  VERSION = "0.0.04"
end


text:
[key='value'],
body .dummy-css-class {
  display: block;
  width: 3px;
}

[key='value']::before,
body .dummy-css-class::before {
  content: '';
}

[key='value']::after,
body .dummy-css-class::after {
  content: '';
}


text:
layout: post
microblog: true
category: photo
date: '2017-07-01T09:49:01'
title: ""
slug: '17070112094901'
location: 'Hola Arepa'
mf-photo:
  - https://cdn.ericalba.com/blog-images/_ig-photos/photos/201707/71ba45b6ba00823b4754623c60f2e136.jpg
---
Arepa Benedict: Spanish Sausage, Poached Eggs, Spicy Hollandaise, Guava Sauce, Chicharron, Arugula & Tomato Salad.

Sofrito Potatoes: Yukon Gold, Puerto Rican Sofrito (Bell Pepper-Olive Sauce), Citrus Crema, Kalamata Olives.

At @HolaArepa 😋

<img src="https://cdn.ericalba.com/blog-images/_ig-photos/photos/201707/71ba45b6ba00823b4754623c60f2e136.jpg" />


text:
package com.bridgewalkerapp.androidclient.apidata;

import org.codehaus.jackson.annotate.JsonProperty;

public class Login extends WebsocketRequest {
	private final String accountName;
	private final String accountPassword;

	public Login(String accountName, String accountPassword) {
		this.accountName = accountName;
		this.accountPassword = accountPassword;
	}

	public String getOp() {
		return "login";
	}

	@JsonProperty("account_name")
	public String getAccountName() {
		return accountName;
	}

	@JsonProperty("account_password")
	public String getAccountPassword() {
		return accountPassword;
	}

	@Override
	public int getRequestType() {
		return TYPE_LOGIN;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <title>C com Cerveja</title>

    <link rel="stylesheet" href="App/public/css/poole.css">
    <link rel="stylesheet" href="App/public/css/syntax.css">
    <link rel="stylesheet" href="App/public/css/hyde.css">
    <link rel="stylesheet" href="App/public/css/mods.css">

    <link rel="shortcut icon" href="App/public/img/favicon.png">

C com Cerveja

Comunidade de Programadores e Estudantes da Linguagem C

          Home

Download

GitHub project

Currently v

© 2017. All rights reserved.

Bem Vindo(a) a Comunidade !

        "Porque o homem não vive so de código !"

Novos Posts


text:
from contextlib import (contextmanager)
import argparse
import sys

import pylibmc

def parse_args(args=None):
    p = argparse.ArgumentParser()
    p.add_argument('--protocol', '-p', default='text',
                   help="choose protocol type. One of text or bin")
    p.add_argument('--remote', '-r', default='127.0.0.1:11211',
                   help="remote server address")
    return p.parse_args(sys.argv[1:] if args is None else args)

def connect_tcp(opts=None):
    opts = opts or parse_args()
    opts.transport = 'tcp'
    return connect(opts)

def connect_udp(opts=None):
    opts = opts or parse_args()
    opts.transport = 'udp'
    return connect(opts)

def connect(opts):
    if opts.transport == 'udp':
        addr = 'udp:' + opts.remote
    else:
        addr = opts.remote
    return pylibmc.Client([addr],
                          binary=opts.protocol == 'bin')

def make_connect_cmd(con):
    def go(opts=None):
        mc = con(opts)
        try:
            yield mc
        finally:
            mc.disconnect_all()
    return contextmanager(go)

def make_run(con):
    def go(fn, opts=None):
        with con() as mc:
            fn(mc)
    return go

connection = make_connect_cmd(connect)
tcp_connection = make_connect_cmd(connect_tcp)
udp_connection = make_connect_cmd(connect_udp)

run_tcp = make_run(tcp_connection)
run_udp = make_run(udp_connection)


text:
<?php
namespace SGH\Comparable\Comparator;

use SGH\Comparable\Comparator;
use SGH\Comparable\ComparatorException;

class NumericComparator implements Comparator
{
    /**
     * (non-PHPdoc)
     *
     * @see \SGH\Comparable\Comparator::compare()
     */
    public function compare($object1, $object2)
    {
        if (! is_scalar($object1) && ! is_null($object1)) {
            throw new ComparatorException('$object1 (type: ' . gettype($object1) . ') is not a primitive numeric type.');
        }
        if (! is_scalar($object2) && ! is_null($object2)) {
            throw new ComparatorException('$object2 (type: ' . gettype($object2) . ') is not a primitive numeric type.');
        }
        if (1 * $object1 < 1 * $object2) {
            return - 1;
        } elseif (1 * $object1 > 1 * $object2) {
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * Returns a callback object that can be used for core functions that take a callback parameter
     *
     * @return \SGH\Comparable\Comparator\InvokableComparator
     */
    public static function callback()
    {
        return new InvokableComparator(new static);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/</Set>
  <Call name="addAliasCheck">
    <Arg>
      <New class="org.eclipse.jetty.server.handler.AllowSymLinkAliasChecker"/>
    </Arg>
  </Call>
</Configure>


text:
#ifndef QWEBVIEW_WINRT_P_H
#define QWEBVIEW_WINRT_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "qwebview_p.h"

namespace ABI {
    namespace Windows {
        namespace UI {
            namespace Xaml {
                namespace Controls {
                    struct IWebView;
                    struct IWebViewNavigationStartingEventArgs;
                    struct IWebViewNavigationCompletedEventArgs;
                }
            }
        }
    }
}

QT_BEGIN_NAMESPACE

struct WinRTWebView;
class QWinRTWebViewPrivate : public QWebViewPrivate
{
    Q_OBJECT
public:
    explicit QWinRTWebViewPrivate(QObject *parent = Q_NULLPTR);
    ~QWinRTWebViewPrivate() Q_DECL_OVERRIDE;

    QUrl url() const Q_DECL_OVERRIDE;
    void setUrl(const QUrl &url) Q_DECL_OVERRIDE;
    bool canGoBack() const Q_DECL_OVERRIDE;
    bool canGoForward() const Q_DECL_OVERRIDE;
    QString title() const Q_DECL_OVERRIDE;
    int loadProgress() const Q_DECL_OVERRIDE;
    bool isLoading() const Q_DECL_OVERRIDE;

    void setParentView(QObject *view) Q_DECL_OVERRIDE;
    QObject *parentView() const Q_DECL_OVERRIDE;
    void setGeometry(const QRect &geometry) Q_DECL_OVERRIDE;
    void setVisibility(QWindow::Visibility visibility) Q_DECL_OVERRIDE;
    void setVisible(bool visible) Q_DECL_OVERRIDE;

public Q_SLOTS:
    void goBack() Q_DECL_OVERRIDE;
    void goForward() Q_DECL_OVERRIDE;
    void reload() Q_DECL_OVERRIDE;
    void stop() Q_DECL_OVERRIDE;
    void loadHtml(const QString &html, const QUrl &baseUrl = QUrl()) Q_DECL_OVERRIDE;

protected:
    void runJavaScriptPrivate(const QString &script, int callbackId) Q_DECL_OVERRIDE;

private:
    HRESULT onNavigationStarted(ABI::Windows::UI::Xaml::Controls::IWebView *, ABI::Windows::UI::Xaml::Controls::IWebViewNavigationStartingEventArgs *);
    HRESULT onNavigationCompleted(ABI::Windows::UI::Xaml::Controls::IWebView *, ABI::Windows::UI::Xaml::Controls::IWebViewNavigationCompletedEventArgs *);
    QScopedPointer<WinRTWebView> d;
};

QT_END_NAMESPACE

#endif // QWEBVIEW_WINRT_P_H


text:
package org.apache.camel.component.mllp;

import java.util.concurrent.TimeUnit;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.LoggingLevel;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.apache.camel.test.mllp.Hl7TestMessageGenerator;
import org.apache.camel.test.mllp.PassthroughProcessor;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

public class MllpProducerConsumerLoopbackTest extends CamelTestSupport {

    Logger log = LoggerFactory.getLogger(MllpProducerConsumerLoopbackTest.class);
    int mllpPort = AvailablePortFinder.getNextAvailable();
    String mllpHost = "localhost";

    @EndpointInject("direct://source")
    ProducerTemplate source;

    @EndpointInject("mock://acknowledged")
    MockEndpoint acknowledged;

    @BeforeAll
    public static void setUpClass() {
        assumeTrue(System.getenv("BUILD_ID") == null,
                "Skipping test running in CI server - Fails sometimes on CI server with address already in use");
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        DefaultCamelContext context = (DefaultCamelContext) super.createCamelContext();

        context.setUseMDCLogging(true);
        context.setName(this.getClass().getSimpleName());

        return context;
    }

    @Override
    protected RouteBuilder[] createRouteBuilders() {
        RouteBuilder[] builders = new RouteBuilder[2];

        builders[0] = new RouteBuilder() {
            String routeId = "mllp-receiver";

            public void configure() {
                fromF("mllp://%s:%d?autoAck=true&readTimeout=5000", mllpHost, mllpPort).id(routeId)
                        .convertBodyTo(String.class)
                        .to(acknowledged)
                        .process(new PassthroughProcessor("after send to result"))
                        .log(LoggingLevel.DEBUG, routeId, "Receiving: ${body}");
            }
        };

        builders[1] = new RouteBuilder() {
            String routeId = "mllp-sender";

            public void configure() {
                from(source.getDefaultEndpoint()).routeId(routeId)
                        .log(LoggingLevel.DEBUG, routeId, "Sending: ${body}")
                        .toF("mllp://%s:%d?readTimeout=5000", mllpHost, mllpPort)
                        .setBody(header(MllpConstants.MLLP_ACKNOWLEDGEMENT));
            }
        };

        return builders;
    }

    @Test
    public void testLoopbackWithOneMessage() throws Exception {
        String testMessage = Hl7TestMessageGenerator.generateMessage();
        acknowledged.expectedBodiesReceived(testMessage);

        String acknowledgement = source.requestBody((Object) testMessage, String.class);
        assertThat("Should be acknowledgment for message 1", acknowledgement,
                CoreMatchers.containsString(String.format("MSA|AA|00001")));

        MockEndpoint.assertIsSatisfied(context, 60, TimeUnit.SECONDS);
    }

    @Test
    public void testLoopbackWithMultipleMessages() throws Exception {
        int messageCount = 1000;
        acknowledged.expectedMessageCount(messageCount);

        for (int i = 1; i <= messageCount; ++i) {
            log.debug("Processing message {}", i);
            String testMessage = Hl7TestMessageGenerator.generateMessage(i);
            acknowledged.message(i - 1).body().isEqualTo(testMessage);
            String acknowledgement = source.requestBody((Object) testMessage, String.class);
            assertThat("Should be acknowledgment for message " + i, acknowledgement,
                    CoreMatchers.containsString(String.format("MSA|AA|%05d", i)));
        }

        MockEndpoint.assertIsSatisfied(context, 60, TimeUnit.SECONDS);
    }
}


text:
package api;

import exception.user.UserNotFoundException;
import manager.ClientConnectionManager;
import manager.EncryptionManager;
import model.ConnectionInfo;
import model.DHParams;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.crypto.spec.DHParameterSpec;
import java.math.BigInteger;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

public class EntryPointTest {

  private EntryPoint testModel;

  @Mock
  private ClientConnectionManager mockClientConnectionManager;
  @Mock
  private EncryptionManager mockEncryptionManager;

  @BeforeMethod
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    testModel = new EntryPoint(mockClientConnectionManager, mockEncryptionManager);
  }

  @Test
  public void shouldCreateConnection() {
    testModel.setUpConnection("user1", new ConnectionInfo("host", 0));
    verify(mockClientConnectionManager).setUpConnection(eq("user1"), any());
  }

  @Test
  public void shouldCreatePublicParameters() {
    testModel.sendParameters("user1");
    verify(mockEncryptionManager).getPublicParameters(eq("user1"));
  }

  @Test
  public void shouldSetUpSharedKey() throws UserNotFoundException {
    testModel.setUpSharedKey("user1", new DHParams(new DHParameterSpec(BigInteger.valueOf(5),
            BigInteger.valueOf(5)), new byte[16]));
    verify(mockEncryptionManager).generateSharedKey(eq("user1"), any());
  }
}


text:
#ifndef __LINENOISE_H
#define __LINENOISE_H

// Error codes
#define LINENOISE_HISTORY_NOT_ENABLED ( -2 )
#define LINENOISE_HISTORY_EMPTY       ( -3 )

// Components that use linenoise in eLua
#define LINENOISE_ID_LUA            0
#define LINENOISE_ID_SHELL          1
#define LINENOISE_TOTAL_COMPONENTS  2

int linenoise_getline( int id, char* buffer, int maxinput, const char* prompt );
int linenoise_addhistory( int id, const char *line );
void linenoise_cleanup( int id );
int linenoise_savehistory( int id, const char* filename );

#endif /* __LINENOISE_H */


text:
class InvalidTokenError(TypeError):
    """Error raised when the token in malformed"""
    pass

class NoServiceError(ValueError):
    """Error raised when no services are added"""
    pass

class ServiceNotFoundError(KeyError):
    """Error raised when service is not found for a given token"""
    pass

class UnexpectedAttributeError(ValueError):
    """
    Error raised when an unexpected attribute
    is looked up in the Service Descriptor
    """
    pass

class ServiceAlreadyExistsError(Exception):
    """Error raised when trying to add already existing service"""
    pass

# Exceptions for installutils
class InstallError(Exception):
    """Error raised when install fails"""
    pass

class SiteNotFoundError(IOError):
    """Error raised site does not exist"""
    pass

class SiteNotRegisteredError(ValueError):
    """Error raised when site is not registered for package lookups"""
    pass

class InvalidPackageError(IOError):
    """Error raised when trying to install an invalid package"""
    pass

class UninstallError(IOError):
    """Error raised when unable to uninstall package"""
    pass

# Exceptions for nodeutils
class NodeCreationError(ValueError):
    """Error raised when unable to create node"""
    pass

class TreeCreationError(ValueError):
    """Error raised when unable to create tree"""
    pass

class TreeRenderError(ValueError):
    """Error raised when unable to render tree"""
    pass


text:
VirtualBox enviropment kit
==========================

Requirements
------------

- VirtualBox with VirtualBox Extension Pack
- procps
- expect
- Cygwin for Windows host PC

Run
---

In order to successfully run Mirantis OpenStack under VirtualBox, you need to:
- download the official release (.iso) and place it under 'iso/' directory
- run "./launch.sh" (or "./launch\_4GB.sh", "./launch\_8GB.sh" or "./launch\_16GB.sh" according to your system resources). It will automatically pick up the iso and spin up master node and slave nodes

If there are any errors, the script will report them and abort.

If you want to change settings (number of OpenStack nodes, CPU, RAM, HDD), please refer to "config.sh".


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

    Copyright (C) [2013] [The FURTHeR Project]

    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.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
	xmlns:ctx="http://www.springframework.org/schema/context" xmlns:osgi="http://www.springframework.org/schema/osgi"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/osgi-compendium
	http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd
	http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd">

	<!--
		definitions using elements of the osgi namespace can be included in
		this file. There is no requirement to keep these definitions in a
		separate file if you do not want to. The rationale for keeping these
		definitions separate is to facilitate integration testing of the
		bundle outside of an OSGi container
	-->

	<!-- =========================================== -->
	<!-- Managed properties                          -->
	<!-- =========================================== -->

	<!-- placeholder configurer -->
	<ctx:property-placeholder properties-ref="coreXmlProps" />

	<!-- Configuration Admin entry -->
	<osgix:cm-properties id="coreXmlProps"
		persistent-id="further.core.xml">
		<!-- Add default property values here -->
	</osgix:cm-properties>

</beans>


text:
"use strict";

require("./gulp");


text:
;(function() {
"use strict";

var FormComponent = React.createClass({
    propTypes: {
        value: React.PropTypes.object.isRequired,
        onChange: React.PropTypes.func.isRequired
    },
    render: function() {
        return (
            React.DOM.form({className: 'form-inline'},
                React.DOM.div({className: 'row'},
                    React.DOM.div({className: 'small-5 medium-3 large-2 column'},
                        React.DOM.label(null, 'Start Date',
                            React.createElement(DatePicker, {
                                selected: this.props.value.startDate,
                                onChange: this.handleDateOnChange,
                                dateFormat: 'YYYY-MM-DD',
                                popoverAttachment: 'bottom left',
                                popoverTargetAttachment: 'top left',
                                popoverTargetOffset: '10px 0px'
                            })
                        )
                    ),
                    React.DOM.div({className: 'small-3 medium-2 large-1 column'},
                        React.DOM.label(null, 'Cycles',
                            React.DOM.input({
                                className: 'form-control',
                                type: 'number',
                                name: 'cycles',
                                value: this.props.value.cycles,
                                onChange: this.handleInputFieldOnChange
                            })
                        )
                    ),
                    React.DOM.div({className: 'small-4 medium-3 large-2 column end'},
                        React.DOM.label(null, 'Days per cycle',
                            React.DOM.input({
                                className: 'form-control',
                                type: 'number',
                                name: 'days',
                                value: this.props.value.days,
                                onChange: this.handleInputFieldOnChange
                            })
                        )
                    )
                )
            )
        );
    },
    handleDateOnChange: function(date) {
        this.props.value.startDate = date;
        this.props.onChange(this.props.value);
    },
    handleInputFieldOnChange: function(e) {
        if (this.props.value.hasOwnProperty(e.target.name)) {
            this.props.value[e.target.name] = e.target.value;
            this.props.onChange(this.props.value);
        }
    },
    // @todo: remove both functions below.
    handleCyclesOnChange: function(e) {
        this.props.value.cycles = e.target.value;
        this.props.onChange(this.props.value);
    },
    handleDaysOnChange: function(e) {
        this.props.value.days = e.target.value;
        this.props.onChange(this.props.value);
    }
});

var TableRowComponent = React.createClass({
    propTypes: {
        label: React.PropTypes.string,
        date: React.PropTypes.string,
        datePretty: React.PropTypes.string
    },
    render: function() {
        return (
            React.DOM.tr(null,
                React.DOM.td(null, this.props.label),
                React.DOM.td(null, this.props.date),
                React.DOM.td(null, this.props.datePretty)
            )
        );
    }
});
var TableComponent = React.createClass({
    propTypes: {
        value: React.PropTypes.object.isRequired
    },
    render: function() {
        return (
            React.DOM.table(null,
                React.DOM.thead(null,
                    React.DOM.tr(null,
                        React.DOM.th({width: 90}, 'Cycle'),
                        React.DOM.th({width: 110}, 'Date'),
                        React.DOM.th()
                    )
                ),
                React.DOM.tbody(null,
                    this.getTableRowComponents(
                        this.parseValue(this.props.value)
                    )
                )
            )
        );
    },
    /**
     *
     * @param array
     */
    getTableRowComponents: function(rows) {
        return rows.map(function(data, index) {
            return React.createElement(TableRowComponent, {
                key: index,
                label: data.label,
                date: data.date,
                datePretty: data.datePretty
            });
        });
    },
    /**
     *
     * @param int
     */
    daysToMilliseconds: function(numOfDays) {
        // hours per day, minutes per hour, seconds per minute, millisecconds.
        return (24 * 60 * 60 * 1000) * numOfDays;
    },
    /**
     *
     * @param object
     */
    parseValue: function(value) {
        var report = [];
        var days = parseInt(value.days);
        var cycles = parseInt(value.cycles);
        var stageDate;

        if (isNaN(days) || isNaN(cycles) || days < 1 || cycles < 1) return report;

        for (var i = 0; i < cycles; i++) {
            if (i === 0) {
                // do nothing.
                stageDate = new Date(value.startDate);
            } else {
                stageDate = new Date(stageDate.getTime() + this.daysToMilliseconds(days));
            }
            report.push({
                id: Date.now() + i,
                label: (i + 1).toString(),
                //date: stageDate.toDateString()
                date: moment(stageDate.getTime()).format("YYYY-MM-DD"),
                datePretty: moment(stageDate.getTime()).format("dddd, MMMM D, YYYY")
            });
        }
        // calculate last day.
        stageDate = new Date(stageDate.getTime() + this.daysToMilliseconds(days - 1));
        report.push({
            id: Date.now() + cycles,
            label: 'Last day',
            //date: stageDate.toDateString()
            date: moment(stageDate.getTime()).format("YYYY-MM-DD"),
            datePretty: moment(stageDate.getTime()).format("dddd, MMMM D, YYYY")
        });
        return report;
    }
});

var Application = React.createClass({
    propTypes: function() {
        // js dependencies.
        urijs: React.PropTypes.object.isRequired
    },
    getInitialState: function() {
        // try to incorporate url data to app.
        var params = this.props.urijs.search(true);
        return {
            startDate: moment(params['start-date']),
            cycles: parseInt(params.cycles) || 1,
            days: parseInt(params.days) || 32
        };
    },
    render: function() {
        return (
            React.DOM.div({className: 'row'},
                React.DOM.h1(null, 'Date Cycle Calculator'),
                React.createElement(FormComponent, {
                    value: this.state,
                    onChange: this.handleFormOnChange
                }),
                React.createElement(TableComponent, {
                    value: this.state
                })
            )
        );
    },
    handleFormOnChange: function(value) {
        // update view.
        this.setState(value);

        // save current state to url.
        var params = {};
        params['start-date'] = value.startDate.format('YYYY-MM-DD');
        params.cycles = value.cycles;
        params.days = value.days;
        window.history.replaceState({}, '', this.props.urijs.search(params).toString());
    }
});
ReactDOM.render(
    React.createElement(Application, {urijs: new URI()}),
    document.getElementById('application')
);
}());


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

namespace Cik.Magazine.Shared.Messages
{
    public class CommandResponse
    {
        private readonly bool _success;
        private readonly Exception[] _exceptions;

        public CommandResponse(bool success, IEnumerable<Exception> exceptions = null)
        {
            _success = success;
            _exceptions = exceptions?.ToArray() ?? new Exception[0];
        }

        public bool Success => _success && _exceptions.Length == 0;

        public AggregateException Exception => Success ? null : new AggregateException(_exceptions);
    }
}


text:
/**
 *
 */
package com.g4g.arrays;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author kushal
 *
 *         https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/
 *
 */
public class SlidingWindowProblem {

  public static void printMaxInWindow(int[] arr, int k) {
    if (arr == null || k < 0)
      return;

    Deque<Integer> dq = new LinkedList<>();
    int i = 0;

    // Process the 1st k elements into the q
    for (i = 0; i < k; i++) {
      // Pop while dq is not empty and the tail element in dq is <= current arr element
      while (!dq.isEmpty() && arr[dq.peekLast()] <= arr[i])
        dq.pollLast();

      dq.addFirst(i);
    }

    // Process rest of the elements
    for (; i < arr.length; i++) {
      System.out.println(arr[dq.peekFirst()]);

      // remove out of window elements
      while (!dq.isEmpty() && dq.peekFirst() < i - k + 1)
        dq.pollFirst();

      // remove all elements that are no longer useful, smaller elements than the current
      while (!dq.isEmpty() && arr[dq.peekLast()] <= arr[i])
        dq.pollLast();

      dq.addLast(i);
    }

    System.out.println(arr[dq.peekFirst()]);

  }

  /**
   * @param args
   */
  public static void main(String[] args) {
    int arr[] = {12, 1, 78, 90, 57, 89, 56};
    int k = 3;
    printMaxInWindow(arr, k);
  }

}


text:
define([
    "qasht/package/Unit",
    "RdfJs/parser/integer",
    "blocks/parser/Data"
], function (TestPackage, integer, Data) {
    return new TestPackage({
        module: "RdfJs/parser/integer",
        tests: [
            {
                name: "return null not an integer",
                input: "Not an integer",
                exec: function (test) {
                    test.assertNull(integer(test.data));

                    test.complete();
                }
            },
            {
                name: "return integer value",
                input: "1029384756 3",
                exec: function (test) {
                    test.assertEqual("1029384756", integer(test.data));

                    test.assertEqual(' ', test.data.input[test.data.pos]);

                    test.complete();
                }
            }
        ],
        setUp: function (test) {
            test.data = new Data({
                input: test.input
            })
        }
    });
});


text:
from onecodex import Api

def test_api_fixture(ocx):
    assert isinstance(ocx, Api)


text:
package com.salesforceiq.example.pageobjects;

import com.salesforceiq.augmenteddriver.web.pageobjects.WebPageObject;
import org.openqa.selenium.By;

import java.util.Optional;

public class WikiPage extends WebPageObject {
    @Override
    public Optional<By> visibleBy() {
        return Optional.of(Bys.HEADING);
    }

    public String getTitle() {
        return augmented().findElementVisible(Bys.HEADING).getText();
    }

    public InfoBox infoBox() {
        return get(InfoBox.class);
    }

    public static class Bys {
        public static final By HEADING = By.id("firstHeading");
    }
}