text:
namespace YAF.Pages
{
    #region Using

    using System;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI.WebControls;

    using VZF.Data.Common;
    using VZF.Utils;
    using VZF.Utils.Helpers;

    using YAF.Classes;
    using YAF.Core;
    using YAF.Types;
    using YAF.Types.Constants;
    using YAF.Types.Flags;
    using YAF.Types.Interfaces;

    #endregion

    /// <summary>
    /// Interface for creating or editing user roles/groups.
    /// </summary>
    public partial class editgroup : ForumPage
    {
        #region Methods

        /// <summary>
        /// Gets or sets the access masks list.
        /// </summary>
        public DataTable AccessMasksList { get; set; }

        /// <summary>
        /// Gets or sets the personal groups number.
        /// </summary>
        public int PersonalGroupsNumber { get; set; }

        /// <summary>
        /// Gets or sets the personal forums number.
        /// </summary>
        public int PersonalForumsNumber { get; set; }

        /// <summary>
        /// Gets or sets the personal access masks number.
        /// </summary>
        public int PersonalAccessMasksNumber { get; set; }

        /// <summary>
        /// Handles data binding event of initial access masks dropdown control.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void BindData_AccessMaskID([NotNull] object sender, [NotNull] EventArgs e)
        {
            // We don't change access masks if it's a guest

            // get sender object as dropdown list
            var c = (DropDownList)sender;

            // list all access masks as data source
            c.DataSource = this.AccessMasksList;

            // set value and text field names
            c.DataValueField = "AccessMaskID";
            c.DataTextField = "Name";
        }

        /// <summary>
        /// Handles click on cancel button.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Cancel_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            // go back to roles administration
            YafBuildLink.Redirect(ForumPages.personalgroup, "u={0}".FormatWith(PageContext.PageUserID));
        }

        /// <summary>
        /// Creates page links for this page.
        /// </summary>
        protected override void CreatePageLinks()
        {
            // forum index
            this.PageLinks.AddLink(this.Get<YafBoardSettings>().Name, YafBuildLink.GetLink(ForumPages.forum));

            // profile
            this.PageLinks.AddLink(this.Get<YafBoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.PageUserName, YafBuildLink.GetLink(ForumPages.cp_profile, "u={0}".FormatWith(PageContext.PageUserID)));

            this.PageLinks.AddLink(this.GetText("PERSONALGROUP", "TITLE"), YafBuildLink.GetLink(ForumPages.personalgroup, "u={0}".FormatWith(PageContext.PageUserID)));

            // current page label (no link)
            this.PageLinks.AddLink(this.GetText("PERSONALGROUP_EDIT", "TITLE_EDIT"), string.Empty);

            this.Page.Header.Title = "{0} - {1}".FormatWith(
                this.Get<YafBoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.PageUserName,
                this.GetText("PERSONALGROUP_EDIT", "TITLE"));
        }

        /// <summary>
        /// Handles page load event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
        {
            // this needs to be done just once, not during postbacks
            if (this.IsPostBack)
            {
                return;
            }

            // A new group case
            if (PageContext.PersonalGroupsNumber >= PageContext.UsrPersonalGroups && this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("i") == null)
            {
                YafBuildLink.AccessDenied();
            }

            // the calling user is not the owner
            if (this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("u") == null || this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("u").ToType<int>() != PageContext.PageUserID)
            {
                YafBuildLink.AccessDenied();
            }

            if (this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("i") != null)
            {
                if (!ValidationHelper.IsValidInt(this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("i")))
                {
                    YafBuildLink.AccessDenied();
                }

                DataTable dt = CommonDb.group_byuserlist(
                    PageContext.PageModuleID,
                    PageContext.PageBoardID,
                    this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("i").ToType<int>(),
                    this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("u").ToType<int>(),
                    true);

                if (dt != null && dt.Rows.Count > 0)
                {
                }
                else
                {
                    YafBuildLink.AccessDenied();
                }
            }

            // create page links
            this.CreatePageLinks();

            // bind data
            this.BindData();

            // is this editing of existing role or creation of new one?
            if (this.Request.QueryString.GetFirstOrDefault("i") == null)
            {
                return;
            }

            // we are not creating new role
            this.NewGroupRow.Visible = false;

            // get data about edited role
            using (
                DataTable dt = CommonDb.group_byuserlist(PageContext.PageModuleID, this.PageContext.PageBoardID, this.Request.QueryString.GetFirstOrDefault("i"), PageContext.PageUserID, true))
            {
                // get it as row
                DataRow row = dt.Rows[0];

                // get role flags
                var flags = new GroupFlags(row["Flags"]);
                this.IsHiddenX.Checked = flags.IsHidden;

                // this.IsHiddenX.Enabled = !flags.IsGuest;
                // set controls to role values
                this.Name.Text = (string)row["Name"];
                this.StyleTextBox.Text = row["Style"].ToString();
                this.Priority.Text = row["SortOrder"].ToString();
                this.Description.Text = row["Description"].ToString();
                this.PersonalGroupsNumber = row["UsrPersonalGroups"].ToType<int>();
                this.PersonalForumsNumber = row["UsrPersonalForums"].ToType<int>();
                this.PersonalAccessMasksNumber = row["UsrPersonalMasks"].ToType<int>();
            }
        }

        /// <summary>
        /// Handles click on save button.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (!ValidationHelper.IsValidInt(this.Priority.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_INTEGER"));
                return;
            }

            // Role
            long roleId = 0;

            // get role ID from page's parameter
            if (this.Request.QueryString.GetFirstOrDefault("i") != null)
            {
                roleId = long.Parse(this.Request.QueryString.GetFirstOrDefault("i"));
            }

            // get new and old name
            string roleName = this.Name.Text.Trim();
            string oldRoleName = string.Empty;

            // if we are editing exising role, get it's original name
            if (roleId != 0)
            {
                // get the current role name in the DB
                using (DataTable dt = CommonDb.group_byuserlist(PageContext.PageModuleID, this.PageContext.PageBoardID, this.Request.QueryString.GetFirstOrDefault("i"), PageContext.PageUserID, true))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        oldRoleName = row["Name"].ToString();
                    }
                }
            }

            // save role and get its ID if it's new (if it's old role, we get it anyway)
            roleId = CommonDb.group_save(
                PageContext.PageModuleID,
                roleId,
                this.PageContext.PageBoardID,
                roleName,
              false,
              false,
              false,
              false,
              this.IsHiddenX.Checked,
              this.AccessMaskID.SelectedValue,
              0,
              this.StyleTextBox.Text.Trim(),
              this.Priority.Text.Trim(),
              this.Description.Text,
              0,
              null,
              null,
              0,
              0,
              PageContext.PageUserID,
              true,
              this.PersonalForumsNumber > 0 ? this.PersonalForumsNumber : 0,
              this.PersonalAccessMasksNumber > 0 ? this.PersonalAccessMasksNumber : 0,
              this.PersonalGroupsNumber > 0 ? this.PersonalGroupsNumber  : 0);

            // empty out access table
            CommonDb.activeaccess_reset(PageContext.PageModuleID);

            // see if need to rename an existing role...
            if (oldRoleName.IsSet() && roleName != oldRoleName && RoleMembershipHelper.RoleExists(oldRoleName) && !RoleMembershipHelper.RoleExists(roleName))
            {
                // transfer users in addition to changing the name of the role...
                var users = this.Get<RoleProvider>().GetUsersInRole(oldRoleName);

                // delete the old role...
                RoleMembershipHelper.DeleteRole(oldRoleName, false);

                // create new role...
                RoleMembershipHelper.CreateRole(roleName);

                if (users.Any())
                {
                    // put users into new role...
                    this.Get<RoleProvider>().AddUsersToRoles(users, new[] { roleName });
                }
            }
            else if (!RoleMembershipHelper.RoleExists(roleName))
            {
                // if role doesn't exist in provider's data source, create it
                RoleMembershipHelper.CreateRole(roleName);
            }

            // number of current groups changed
            this.Get<IDataCache>().Remove(Constants.Cache.ActiveUserLazyData);

            // Access masks for a newly created or an existing role
            if (this.Request.QueryString.GetFirstOrDefault("i") != null)
            {
                    // go trhough all forums
                    for (int i = 0; i < this.AccessList.Items.Count; i++)
                    {
                        // get current repeater item
                        RepeaterItem item = this.AccessList.Items[i];

                        // get forum ID
                        int forumId = int.Parse(((Label)item.FindControl("ForumID")).Text);

                        // save forum access maks for this role
                        CommonDb.forumaccess_save(
                            PageContext.PageModuleID,
                            forumId,
                            roleId,
                            ((DropDownList)item.FindControl("AccessmaskID")).SelectedValue);
                    }

                    YafBuildLink.Redirect(ForumPages.personalgroup, "u={0}".FormatWith(PageContext.PageUserID));
            }

            // remove caching in case something got updated...
            this.Get<IDataCache>().Remove(Constants.Cache.ForumModerators);

            // Clearing cache with old permissions data...
            this.Get<IDataCache>().Remove(k => k.StartsWith(Constants.Cache.ActiveUserLazyData.FormatWith(string.Empty)));

            // Done, redirect to role editing page
            YafBuildLink.Redirect(ForumPages.editgroup, "i={0}&u={1}", roleId, this.PageContext.PageUserID);
        }

        /// <summary>
        /// Handles pre-render event of each forum's access mask dropdown.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void SetDropDownIndex([NotNull] object sender, [NotNull] EventArgs e)
        {
            // get dropdown which raised this event
            var list = (DropDownList)sender;

            // select value from the list
            ListItem item = list.Items.FindByValue(list.Attributes["value"]);

            // verify something was found...
            if (item != null)
            {
                item.Selected = true;
            }
        }

        /// <summary>
        /// Bind data for this control.
        /// </summary>
        private void BindData()
        {
            // set datasource of access list (list of forums and role's access masks) if we are editing existing mask
            if (this.Request.QueryString.GetFirstOrDefault("i") != null)
            {
                this.AccessList.DataSource = CommonDb.forumaccess_group(PageContext.PageModuleID, this.Request.QueryString.GetFirstOrDefault("i"), PageContext.PageUserID, true);
            }

            this.AccessMasksList = CommonDb.accessmask_pforumlist(
              mid: PageContext.PageModuleID,
              boardId: this.PageContext.PageBoardID,
              accessMaskId: null,
              excludeFlags: 0,
              pageUserId: this.PageContext.PageUserID,
              isUserMask: true,
              isCommonMask: !this.Get<YafBoardSettings>().AllowPersonalMasksOnlyForPersonalForums);

            // bind data to controls
            this.DataBind();
        }

        #endregion
    }
}


text:
#include <qlabel.h>
#include <qlistview.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <kcombobox.h>
#include <klocale.h>
#include "symboldlg.h"
#include "cscopefrontend.h"
#include "kscopeconfig.h"

QStringList SymbolDlg::s_slHistory;

/**
 * Class constructor.
 * @param	pParent	Parent widget
 * @param	szName	This widget's name
 */
SymbolDlg::SymbolDlg(QWidget* pParent, const char* szName) :
	SymbolLayout(pParent, szName, true, 0),
	m_progress(m_pHintList)
{
	// Create a persistent Cscope process
	m_pCscope = new CscopeFrontend();

	// Initialise the hint list (hidden by default)
	m_pHintList->addColumn(i18n("Suggested Symbols"));
	m_pHintList->hide();
	((QWidget*)m_pHintGroup)->hide();
	m_pBeginWithRadio->toggle();
	adjustSize();

	// Close the dialogue when either the "OK" or "Cancel" button are clicked
	connect(m_pOKButton, SIGNAL(clicked()), this, SLOT(accept()));
	connect(m_pCancelButton, SIGNAL(clicked()), this, SLOT(reject()));

	// Run a symbol completion query when the "Hint" button is clicked
	connect(m_pHintButton, SIGNAL(clicked()), this, SLOT(slotHintClicked()));

	// Add results to the hint list
	connect(m_pCscope, SIGNAL(dataReady(FrontendToken*)), this,
		SLOT(slotHintDataReady(FrontendToken*)));

	// Set hint button availability based on the type of query
	connect(m_pTypeCombo, SIGNAL(activated(int)), this,
		SLOT(slotTypeChanged(int)));

	// Selecting an item in the hint list sets it as the current text
	connect(m_pHintList, SIGNAL(selectionChanged(QListViewItem*)), this,
		SLOT(slotHintItemSelected(QListViewItem*)));

	// Double-clicking an item in the hint list accepts that item as the
	// result of the query (i.e., the item is selcted and the dialogue is
	// closed)
	connect(m_pHintList, SIGNAL(doubleClicked(QListViewItem*)), this,
		SLOT(accept()));

	// Refresh the hint list when the hint options change
	connect(m_pBeginWithRadio, SIGNAL(toggled(bool)), this,
		SLOT(slotHintOptionChanged(bool)));
	connect(m_pContainRadio, SIGNAL(toggled(bool)), this,
		SLOT(slotHintOptionChanged(bool)));

	// Show hint query progress information
	connect(m_pCscope, SIGNAL(progress(int, int)), this,
		SLOT(slotHintProgress(int, int)));
	connect(m_pCscope, SIGNAL(finished(uint)), this,
		SLOT(slotHintFinished(uint)));
}

/**
 * Class destructor.
 */
SymbolDlg::~SymbolDlg()
{
	delete m_pCscope;
}

/**
 * Displays the requested type of query in the type combo-box.
 * @param	nType	The requested type
 */
void SymbolDlg::setType(uint nType)
{
	m_pTypeCombo->setCurrentItem(nType);
	slotTypeChanged(nType);
}

/**
 * @param	sSymbol	The initial text of the combo-box
 */
void SymbolDlg::setSymbol(const QString& sSymbol)
{
	m_pSymbolHC->setCurrentText(sSymbol);
}

/**
 * @param	slSymHistory	A list of previously queried symbols
 */
void SymbolDlg::setHistory(QStringList& slSymHistory)
{
	m_pSymbolHC->setHistoryItems(slSymHistory);
}

/**
 * @return	The current text of the symbol combo-box
 */
QString SymbolDlg::getSymbol() const
{
	QString sResult;

	sResult = m_pSymbolHC->currentText().stripWhiteSpace();
	if (m_pSubStringCheck->isChecked())
		sResult = ".*" + sResult + ".*";

	return sResult;
}

/**
 * @return	The type of query requested by the user
 * @note	The returned value does not conform to the type used for running
 * 			Cscope queries. Use getQueryType() to translate between these
 *			values.
 */
uint SymbolDlg::getType() const
{
	return m_pTypeCombo->currentItem();
}

bool SymbolDlg::getCase() const
{
	return !m_pCaseCheck->isChecked();
}

/**
 * A convinience static function for creating and showing SymbolDlg dialogue.
 * @param	pParent		The parent widget
 * @param	nType		The type of query requested by the user (may be
 *						changed in the dialogue)
 * @param	sSymbol		The initial text of the combo-box
 * @return	The text entered by the user in the symbol combo-box, or an empty
 *			string if the dialogue was cancelled
 */
QString SymbolDlg::promptSymbol(QWidget* pParent, uint& nType,
	const QString& sSymbol, bool& bCase)
{
	SymbolDlg dlg(pParent);

	// Initialise the dialogue
	dlg.setType(nType);
	dlg.setHistory(s_slHistory);
	dlg.setSymbol(sSymbol);

	// Display the dialogue
	if (dlg.exec() != QDialog::Accepted)
		return "";

	// Return the text entered by the user
	nType = dlg.getType();
	bCase = dlg.getCase();
	dlg.m_pSymbolHC->addToHistory(dlg.getSymbol());
	s_slHistory = dlg.m_pSymbolHC->historyItems();
	return dlg.getSymbol();
}

/**
 * Translates a symbol dialogue type into a Cscope query type.
 * @param	nType	The type to translate
 * @return	A query type matching the symbol dialogue type
 */
uint SymbolDlg::getQueryType(uint nType)
{
	if (nType == CallTree)
		return CscopeFrontend::None;

	if (nType <= Text)
		return nType;

	return nType + 1;
}

/**
 * Runs a symbol definition query, looking for symbols starting with the
 * currently entered text.
 * If the hint list is not visible, it is shown first.
 * This slot is connected to the clicked() signal of the "Hint" button.
 */
void SymbolDlg::slotHintClicked()
{
	QString sText, sRegExp;

	// Show the hint list if necessary
	if (!m_pHintList->isVisible()) {
		m_pHintList->show();
		((QWidget*)m_pHintGroup)->show();
		adjustSize();
	}

	// Clear the previous contents
	m_pHintList->clear();

	// Get the currently entered text (must have at least one character)
	sText = m_pSymbolHC->currentText().stripWhiteSpace();
	if (sText.isEmpty())
		return;

	// Create the regular expression
	if (m_pBeginWithRadio->isOn())
		sRegExp = sText + "[a-zA-Z0-9_]*";
	else
		sRegExp = "[a-zA-Z0-9_]*" + sText + "[a-zA-Z0-9_]*";

	m_reHint.setPattern(sRegExp);

	// Run a Cscope symbol definition query using a regular expression
	m_pCscope->query(CscopeFrontend::Definition, sRegExp);
}

/**
 * Called when a new record is ready to be added to the hint list.
 * NOTE: Cscope 15.5 has a bug where the "function" field of the record
 * displays the regular expression instead of the matched symbol name. For
 * this reason, we need to extract the symbol from the "Text" field.
 * @param	pToken	The head of the record's token list
 */
void SymbolDlg::slotHintDataReady(FrontendToken* pToken)
{
	QString sText;

	// Get the line text
	pToken = pToken->getNext()->getNext()->getNext();
	sText = pToken->getData();

	// Find the symbol within the line
	if (m_reHint.search(sText) == -1)
		return;

	// Find the symbol within the list, if found - do not add
	if (m_pHintList->findItem(m_reHint.capturedTexts().first(), 0))
		return;

	// Add a list item
	(void)new QListViewItem(m_pHintList, m_reHint.capturedTexts().first());

}

/**
 * Sets the text of a selected hint list item as the current text of the
 * symbol combo-box.
 * This slot is connected to the doubleClicked() signal of the hint list-view.
 * @param	pItem	The clicked list item
 */
void SymbolDlg::slotHintItemSelected(QListViewItem* pItem)
{
	m_pSymbolHC->setCurrentText(pItem->text(0));
}

/**
 * Refreshes the hint list based on the newly selected option.
 * This slot is connected to the toggled() signal of the hint options radio
 * buttons.
 * NOTE: The list is only refreshed if the system profile is set to Fast.
 * @param	bOn	true if the button was toggled on
 */
void SymbolDlg::slotHintOptionChanged(bool bOn)
{
	if (bOn && Config().getSysProfile() == KScopeConfig::Fast)
		slotHintClicked();
}

/**
 * Display a progress bar while the hint query is working.
 * This slot is connected to the progress() signal emitted by the Cscope
 * frontend object.
 * @param	nProgress	Progress value
 * @param	nTotal		The final expected value
 */
void SymbolDlg::slotHintProgress(int nProgress, int nTotal)
{
	m_progress.setProgress(nProgress, nTotal);
}

/**
 * Destroys all progress information widget when the query process terminates.
 * This slot is connected to the finished() signal emitted by the Cscope
 * process.
 */
void SymbolDlg::slotHintFinished(uint /* ignored */)
{
	m_progress.finished();
}

/**
 * Enables/disables the hint button, based on the newly selected type.
 * This slot is connected to the activated() signal of the type combo-box.
 * @param	nType	The newly selected type
 */
void SymbolDlg::slotTypeChanged(int nType)
{
	if (nType == FileName || nType == Including)
		m_pHintButton->setEnabled(false);
	else
		m_pHintButton->setEnabled(true);
}

#include "symboldlg.moc"

redpajama_set_name: RedPajamaGithub


text:
package io.netty.handler.codec.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Sends a 100 CONTINUE
 * {@link HttpResponse} to {@link HttpRequest}s which contain a 'expect: 100-continue' header. It
 * should only be used for applications which do not install the {@link HttpObjectAggregator}.
 *

 * By default it accepts all expectations.
 *

 * Since {@link HttpServerExpectContinueHandler} expects {@link HttpRequest}s it should be added after {@link
 * HttpServerCodec} but before any other handlers that might send a {@link HttpResponse}.

 *

 *  {@link io.netty.channel.ChannelPipeline} p = ...;
 *  ...
 *  p.addLast("serverCodec", new {@link HttpServerCodec}());
 *  p.addLast("respondExpectContinue", new {@link HttpServerExpectContinueHandler}());
 *  ...
 *  p.addLast("handler", new HttpRequestHandler());
 *

 *

 */
public class HttpServerExpectContinueHandler extends ChannelInboundHandlerAdapter {

    private static final FullHttpResponse EXPECTATION_FAILED = new DefaultFullHttpResponse(
            HTTP_1_1, HttpResponseStatus.EXPECTATION_FAILED, Unpooled.EMPTY_BUFFER);

    private static final FullHttpResponse ACCEPT = new DefaultFullHttpResponse(
            HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER);

    static {
        EXPECTATION_FAILED.headers().set(CONTENT_LENGTH, 0);
        ACCEPT.headers().set(CONTENT_LENGTH, 0);
    }

    /**
     * Produces a {@link HttpResponse} for {@link HttpRequest}s which define an expectation. Returns {@code null} if the
     * request should be rejected. See {@link #rejectResponse(HttpRequest)}.
     */
    protected HttpResponse acceptMessage(@SuppressWarnings("unused") HttpRequest request) {
        return ACCEPT.retainedDuplicate();
    }

    /**
     * Returns the appropriate 4XX {@link HttpResponse} for the given {@link HttpRequest}.
     */
    protected HttpResponse rejectResponse(@SuppressWarnings("unused") HttpRequest request) {
        return EXPECTATION_FAILED.retainedDuplicate();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;

            if (HttpUtil.is100ContinueExpected(req)) {
                HttpResponse accept = acceptMessage(req);

                if (accept == null) {
                    // the expectation failed so we refuse the request.
                    HttpResponse rejection = rejectResponse(req);
                    ReferenceCountUtil.release(msg);
                    ctx.writeAndFlush(rejection).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
                    return;
                }

                ctx.writeAndFlush(accept).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
                req.headers().remove(HttpHeaderNames.EXPECT);
            }
        }
        super.channelRead(ctx, msg);
    }
}


text:
// @tag core
/**
 * Represents single event type that an Observable object listens to.
 * All actual listeners are tracked inside here.  When the event fires,
 * it calls all the registered listener functions.
 *
 * @private
 */
Ext.define('Ext.util.Event', function() {
  var arraySlice = Array.prototype.slice,
      arrayInsert = Ext.Array.insert,
      toArray = Ext.Array.toArray,
      fireArgs = {};

  return {
    requires: 'Ext.util.DelayedTask',

    /**
     * @property {Boolean} isEvent
     * `true` in this class to identify an object as an instantiated Event, or subclass thereof.
     */
    isEvent: true,

    // Private. Event suspend count
    suspended: 0,

    noOptions: {},

    constructor: function(observable, name) {
        this.name = name;
        this.observable = observable;
        this.listeners = [];
    },

    addListener: function(fn, scope, options, caller, manager) {
        var me = this,
            added = false,
            observable = me.observable,
            eventName = me.name,
            listeners, listener, priority, isNegativePriority, highestNegativePriorityIndex,
            hasNegativePriorityIndex, length, index, i, listenerPriority;

        //<debug>
        if (scope && !Ext._namedScopes[scope] && (typeof fn === 'string') && (typeof scope[fn] !== 'function')) {
            Ext.raise("No method named '" + fn + "' found on scope object");
        }
        //</debug>

        if (me.findListener(fn, scope) === -1) {
            listener = me.createListener(fn, scope, options, caller, manager);
            if (me.firing) {
                // if we are currently firing this event, don't disturb the listener loop
                me.listeners = me.listeners.slice(0);
            }
            listeners = me.listeners;
            index = length = listeners.length;
            priority = options && options.priority;
            highestNegativePriorityIndex = me._highestNegativePriorityIndex;
            hasNegativePriorityIndex = highestNegativePriorityIndex !== undefined;
            if (priority) {
                // Find the index at which to insert the listener into the listeners array,
                // sorted by priority highest to lowest.
                isNegativePriority = (priority < 0);
                if (!isNegativePriority || hasNegativePriorityIndex) {
                    // If the priority is a positive number, or if it is a negative number
                    // and there are other existing negative priority listenrs, then we
                    // need to calcuate the listeners priority-order index.
                    // If the priority is a negative number, begin the search for priority
                    // order index at the index of the highest existing negative priority
                    // listener, otherwise begin at 0
                    for(i = (isNegativePriority ? highestNegativePriorityIndex : 0); i < length; i++) {
                        // Listeners created without options will have no "o" property
                        listenerPriority = listeners[i].o ? listeners[i].o.priority||0 : 0;
                        if (listenerPriority < priority) {
                            index = i;
                            break;
                        }
                    }
                } else {
                    // if the priority is a negative number, and there are no other negative
                    // priority listeners, then no calculation is needed - the negative
                    // priority listener gets appended to the end of the listeners array.
                    me._highestNegativePriorityIndex = index;
                }
            } else if (hasNegativePriorityIndex) {
                // listeners with a priority of 0 or undefined are appended to the end of
                // the listeners array unless there are negative priority listeners in the
                // listeners array, then they are inserted before the highest negative
                // priority listener.
                index = highestNegativePriorityIndex;
            }

            if (!isNegativePriority && index <= highestNegativePriorityIndex) {
                me._highestNegativePriorityIndex ++;
            }
            if (index === length) {
                listeners[length] = listener;
            } else {
                arrayInsert(listeners, index, [listener]);
            }

            if (observable.isElement) {
                // It is the role of Ext.util.Event (vs Ext.Element) to handle subscribe/
                // unsubscribe because it is the lowest level place to intercept the
                // listener before it is added/removed.  For addListener this could easily
                // be done in Ext.Element's doAddListener override, but since there are
                // multiple paths for listener removal (un, clearListeners), it is best
                // to keep all subscribe/unsubscribe logic here.
                observable._getPublisher(eventName).subscribe(
                    observable,
                    eventName,
                    options.delegated !== false,
                    options.capture
                );
            }

            added = true;
        }

        return added;
    },

    createListener: function(fn, scope, o, caller, manager) {
        var me = this,
            namedScope = Ext._namedScopes[scope],
            listener = {
                fn: fn,
                scope: scope,
                ev: me,
                caller: caller,
                manager: manager,
                namedScope: namedScope,
                defaultScope: namedScope ? (scope || me.observable) : undefined,
                lateBound: typeof fn === 'string'
            },
            handler = fn,
            wrapped = false,
            type;

        // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper
        // because the event removal that the single listener does destroys the listener's DelayedTask(s)
        if (o) {
            listener.o = o;
            if (o.single) {
                handler = me.createSingle(handler, listener, o, scope);
                wrapped = true;
            }
            if (o.target) {
                handler = me.createTargeted(handler, listener, o, scope, wrapped);
                wrapped = true;
            }
            if (o.delay) {
                handler = me.createDelayed(handler, listener, o, scope, wrapped);
                wrapped = true;
            }
            if (o.buffer) {
                handler = me.createBuffered(handler, listener, o, scope, wrapped);
                wrapped = true;
            }

            if (me.observable.isElement) {
                // If the event type was translated, e.g. mousedown -> touchstart, we need to save
                // the original type in the listener object so that the Ext.event.Event object can
                // reflect the correct type at firing time
                type = o.type;
                if (type) {
                    listener.type = type;
                }
            }
        }

        listener.fireFn = handler;
        listener.wrapped = wrapped;
        return listener;
    },

    findListener: function(fn, scope) {
        var listeners = this.listeners,
            i = listeners.length,
            listener;

        while (i--) {
            listener = listeners[i];
            if (listener) {
                // use ==, not === for scope comparison, so that undefined and null are equal
                if (listener.fn === fn && listener.scope == scope) {
                    return i;
                }
            }
        }

        return - 1;
    },

    removeListener: function(fn, scope, index) {
        var me = this,
            removed = false,
            observable = me.observable,
            eventName = me.name,
            listener, highestNegativePriorityIndex, options,
            k, manager, managedListeners, managedListener, i;

        index = index || me.findListener(fn, scope);

        if (index !== -1) {
            listener = me.listeners[index];
            options = listener.o;
            highestNegativePriorityIndex = me._highestNegativePriorityIndex;

            if (me.firing) {
                me.listeners = me.listeners.slice(0);
            }

            // cancel and remove a buffered handler that hasn't fired yet.
            // When the buffered listener is invoked, it must check whether
            // it still has a task.
            if (listener.task) {
                listener.task.cancel();
                delete listener.task;
            }

            // cancel and remove all delayed handlers that haven't fired yet
            k = listener.tasks && listener.tasks.length;
            if (k) {
                while (k--) {
                    listener.tasks[k].cancel();
                }
                delete listener.tasks;
            }

            // Remove this listener from the listeners array
            // We can use splice directly. The IE8 bug which Ext.Array works around only affects *insertion*
            // http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
            me.listeners.splice(index, 1);

            manager = listener.manager;
            if (manager) {
                // If this is a managed listener we need to remove it from the manager's
                // managedListeners array.  This ensures that if we listen using mon
                // and then remove without using mun, the managedListeners array is updated
                // accordingly, for example
                //
                //     manager.on(target, 'foo', fn);
                //
                //     target.un('foo', fn);
                managedListeners = manager.managedListeners;
                if (managedListeners) {
                    for (i = managedListeners.length; i--;) {
                        managedListener = managedListeners[i];
                        if (managedListener.item === me.observable && managedListener.ename === eventName &&
                                managedListener.fn === fn && managedListener.scope === scope) {
                            managedListeners.splice(i, 1);
                        }
                    }
                }
            }

            // if the listeners array contains negative priority listeners, adjust the
            // internal index if needed.
            if (highestNegativePriorityIndex) {
                if (index < highestNegativePriorityIndex) {
                    me._highestNegativePriorityIndex --;
                } else if (index === highestNegativePriorityIndex && index === me.listeners.length) {
                    delete me._highestNegativePriorityIndex;
                }
            }

            if (observable.isElement) {
                observable._getPublisher(eventName).unsubscribe(
                    observable,
                    eventName,
                    options.delegated !== false,
                    options.capture
                );
            }

            removed = true;
        }

        return removed;
    },

    // Iterate to stop any buffered/delayed events
    clearListeners: function() {
        var listeners = this.listeners,
            i = listeners.length,
            listener;

        while (i--) {
            listener = listeners[i];
            this.removeListener(listener.fn, listener.scope);
        }
    },

    suspend: function() {
        ++this.suspended;
    },

    resume: function() {
        if (this.suspended) {
            --this.suspended;
        }
    },

    isSuspended: function() {
        return this.suspended > 0;
    },

    fireDelegated: function(firingObservable, args) {
        this.firingObservable = firingObservable;
        return this.fire.apply(this, args);
    },

    fire: function() {
        var me = this,
            CQ = Ext.ComponentQuery,
            listeners = me.listeners,
            count = listeners.length,
            observable = me.observable,
            isElement = observable.isElement,
            isComponent = observable.isComponent,
            firingObservable = me.firingObservable,
            options, delegate, fireInfo, i, args, listener, len, delegateEl, currentTarget,
            type, chained, firingArgs, e, fireFn, fireScope;

        if (!me.suspended && count > 0) {
            me.firing = true;
            args = arguments.length ? arraySlice.call(arguments, 0) : [];
            len = args.length;
            if (isElement) {
                e = args[0];
            }
            for (i = 0; i < count; i++) {
                listener = listeners[i];
                options = listener.o;

                if (isElement) {
                    if (currentTarget) {
                        // restore the previous currentTarget if we changed it last time
                        // around the loop while processing the delegate option.
                        e.setCurrentTarget(currentTarget);
                    }

                    // For events that have been translated to provide device compatibility,
                    // e.g. mousedown -> touchstart, we want the event object to reflect the
                    // type that was originally listened for, not the type of the actual event
                    // that fired. The listener's "type" property reflects the original type.
                    type = listener.type;

                    if (type) {
                        // chain a new object to the event object before changing the type.
                        // This is more efficient than creating a new event object, and we
                        // don't want to change the type of the original event because it may
                        // be used asynchronously by other handlers
                        chained = e;
                        e = args[0] = chained.chain({ type: type });
                    }

                    // In Ext4 Ext.EventObject was a singleton event object that was reused as events
                    // were fired.  Set Ext.EventObject to the last fired event for compatibility.
                    Ext.EventObject = e;
                }

                firingArgs = args;

                if (options) {
                    delegate = options.delegate;
                    if (delegate) {
                        if (isElement) {
                            // prepending the currentTarget.id to the delegate selector
                            // allows us to match selectors such as "> div"
                            delegateEl = e.getTarget('#' + e.currentTarget.id + ' ' + delegate);
                            if (delegateEl) {
                                args[1] = delegateEl;
                                // save the current target before changing it to the delegateEl
                                // so that we can restore it next time around
                                currentTarget = e.currentTarget;
                                e.setCurrentTarget(delegateEl);
                            } else {
                                continue;
                            }
                        } else if (isComponent && !CQ.is(firingObservable, delegate, observable)) {
                            continue;
                        }
                    }

                    if (isElement) {
                        if (options.preventDefault) {
                            e.preventDefault();
                        }

                        if (options.stopPropagation) {
                            e.stopPropagation();
                        }

                        if (options.stopEvent) {
                            e.stopEvent();
                        }
                    }

                    args[len] = options;

                    if (options.args) {
                        firingArgs = options.args.concat(args);
                    }
                }

                fireInfo = me.getFireInfo(listener);
                fireFn = fireInfo.fn;
                fireScope = fireInfo.scope;

                // We don't want to keep closure and scope on the Event prototype!
                fireInfo.fn = fireInfo.scope = null;

                if (fireFn.apply(fireScope, firingArgs) === false) {
                    Ext.EventObject = null;

                    return (me.firing = false);
                }

                if (chained) {
                    // if we chained the event object for type translation we need to
                    // un-chain it before proceeding to process the next listener, which
                    // may not be a translated event.
                    e = args[0] = chained;
                    chained = null;
                }

                // We don't guarantee Ext.EventObject existence outside of the immediate
                // event propagation scope
                Ext.EventObject = null;
            }
        }

        me.firing = false;

        return true;
    },

    getFireInfo: function(listener, fromWrapped) {
        var observable = this.observable,
            fireFn = listener.fireFn,
            scope = listener.scope,
            namedScope = listener.namedScope,
            fn;

        // If we are called with a wrapped listener, only attempt to do scope
        // resolution if we are explicitly called by the last wrapped function
        if (!fromWrapped && listener.wrapped) {
            fireArgs.fn = fireFn;
            return fireArgs;
        }

        fn = fromWrapped ? listener.fn : fireFn;
        //<debug>
        var name = fn;

        //</debug>
        if (listener.lateBound) {
            // handler is a function name - need to resolve it to a function reference
            if (!scope || namedScope) {
                // Only invoke resolveListenerScope if the user did not specify a scope,
                // or if the user specified a named scope.  Named function handlers that
                // use an arbitrary object as the scope just skip this part, and just
                // use the given scope object to resolve the method.
                scope = (listener.caller || observable).resolveListenerScope(listener.defaultScope);
            }
            //<debug>
            if (!scope) {
                Ext.raise('Unable to dynamically resolve scope for "' + listener.ev.name + '" listener on ' + this.observable.id);
            }

            if (!Ext.isFunction(scope[fn])) {
                Ext.raise('No method named "' + fn + '" on ' +
                    (scope.$className || 'scope object.'));
            }
            //</debug>

            fn = scope[fn];
        } else if (namedScope && namedScope.isController) {
            // If handler is a function reference and scope:'controller' was requested
            // we'll do our best to look up a controller.
            scope = (listener.caller || observable).resolveListenerScope(listener.defaultScope);
            //<debug>
            if (!scope) {
                Ext.raise('Unable to dynamically resolve scope for "' + listener.ev.name + '" listener on ' + this.observable.id);
            }
            //</debug>
        } else if (!scope || namedScope) {
            // If handler is a function reference we use the observable instance as
            // the default scope
            scope = observable;
        }

        // We can only ever be firing one event at a time, so just keep
        // overwriting tghe object we've got in our closure, otherwise we'll be
        // creating a whole bunch of garbage objects
        fireArgs.fn = fn;
        fireArgs.scope = scope;
        //<debug>
        if (!fn) {
            Ext.raise('Unable to dynamically resolve method "' + name + '" on ' + this.observable.$className);
        }
        //</debug>
        return fireArgs;
    },

    createTargeted: function (handler, listener, o, scope, wrapped) {
        return function(){
            if (o.target === arguments[0]) {
                var fireInfo;

                if (!wrapped) {
                    fireInfo = listener.ev.getFireInfo(listener, true);
                    handler = fireInfo.fn;
                    scope = fireInfo.scope;

                    // We don't want to keep closure and scope references on the Event prototype!
                    fireInfo.fn = fireInfo.scope = null;
                }

                return handler.apply(scope, arguments);
            }
        };
    },

    createBuffered: function (handler, listener, o, scope, wrapped) {
        listener.task = new Ext.util.DelayedTask();
        return function() {
            // If the listener is removed during the event call, the listener stays in the
            // list of listenes to be invoked in the fire method, but the task is deleted
            // So if we get here with no task, it's because the listener has been removed.
            if (listener.task) {
                var fireInfo;

                if (!wrapped) {
                    fireInfo = listener.ev.getFireInfo(listener, true);
                    handler = fireInfo.fn;
                    scope = fireInfo.scope;

                    // We don't want to keep closure and scope references on the Event prototype!
                    fireInfo.fn = fireInfo.scope = null;
                }

                listener.task.delay(o.buffer, handler, scope, toArray(arguments));
            }
        };
    },

    createDelayed: function (handler, listener, o, scope, wrapped) {
        return function() {
            var task = new Ext.util.DelayedTask(),
                fireInfo;

            if (!wrapped) {
                fireInfo = listener.ev.getFireInfo(listener, true);
                handler = fireInfo.fn;
                scope = fireInfo.scope;

                // We don't want to keep closure and scope references on the Event prototype!
                fireInfo.fn = fireInfo.scope = null;
            }

            if (!listener.tasks) {
                listener.tasks = [];
            }
            listener.tasks.push(task);
            task.delay(o.delay || 10, handler, scope, toArray(arguments));
        };
    },

    createSingle: function (handler, listener, o, scope, wrapped) {
        return function() {
            var event = listener.ev,
                observable = event.observable,
                fn = listener.fn,
                fireInfo;

            // If we have an observable, use that to clean up because there
            // can be special cases that need handling. For example element
            // listeners may bind multiple events (mousemove+touchmove) and they
            // need to act in tandem.
            if (observable) {
                observable.removeListener(event.name, fn, scope);
            } else {
                event.removeListener(fn, scope);
            }

            if (!wrapped) {
                fireInfo = event.getFireInfo(listener, true);
                handler = fireInfo.fn;
                scope = fireInfo.scope;

                // We don't want to keep closure and scope references on the Event prototype!
                fireInfo.fn = fireInfo.scope = null;
            }

            return handler.apply(scope, arguments);
        };
    }
  };
});


text:
from email.header import Header, decode_header, make_header
from email.message import Message
from typing import Any, Dict, List, Union

METADATA_FIELDS = [
    # Name, Multiple-Use
    ("Metadata-Version", False),
    ("Name", False),
    ("Version", False),
    ("Dynamic", True),
    ("Platform", True),
    ("Supported-Platform", True),
    ("Summary", False),
    ("Description", False),
    ("Description-Content-Type", False),
    ("Keywords", False),
    ("Home-page", False),
    ("Download-URL", False),
    ("Author", False),
    ("Author-email", False),
    ("Maintainer", False),
    ("Maintainer-email", False),
    ("License", False),
    ("Classifier", True),
    ("Requires-Dist", True),
    ("Requires-Python", False),
    ("Requires-External", True),
    ("Project-URL", True),
    ("Provides-Extra", True),
    ("Provides-Dist", True),
    ("Obsoletes-Dist", True),
]

def json_name(field: str) -> str:
    return field.lower().replace("-", "_")

def msg_to_json(msg: Message) -> Dict[str, Any]:
    """Convert a Message object into a JSON-compatible dictionary."""

    def sanitise_header(h: Union[Header, str]) -> str:
        if isinstance(h, Header):
            chunks = []
            for bytes, encoding in decode_header(h):
                if encoding == "unknown-8bit":
                    try:
                        # See if UTF-8 works
                        bytes.decode("utf-8")
                        encoding = "utf-8"
                    except UnicodeDecodeError:
                        # If not, latin1 at least won't fail
                        encoding = "latin1"
                chunks.append((bytes, encoding))
            return str(make_header(chunks))
        return str(h)

    result = {}
    for field, multi in METADATA_FIELDS:
        if field not in msg:
            continue
        key = json_name(field)
        if multi:
            value: Union[str, List[str]] = [
                sanitise_header(v) for v in msg.get_all(field)
            ]
        else:
            value = sanitise_header(msg.get(field))
            if key == "keywords":
                # Accept both comma-separated and space-separated
                # forms, for better compatibility with old data.
                if "," in value:
                    value = [v.strip() for v in value.split(",")]
                else:
                    value = value.split()
        result[key] = value

    payload = msg.get_payload()
    if payload:
        result["description"] = payload

    return result


text:
<?php
/**
 * Garp_Model_Info
 * Generic info model. Allows admins to configure various parameters about their system.
 *
 * @author       Harmen Janssen | grrr.nl
 * @version      1.0
 * @package      G_Model
 */
class G_Model_Info extends Model_Base_Info {
	/**#@+
	 * Constants that are used for types of info
	 * @var string
	 */
	const INFO = 'info';
	const SETTING = 'setting';
	const MESSAGE = 'message';
    /**#@-*/

	/**
 	 * Fetch results and converts to Zend_Config object
 	 * @param Zend_Db_Select $select A select object to filter results
 	 * @param String $env Which application env to use
 	 * @return Zend_Config
 	 */
	public function fetchAsConfig(Zend_Db_Select $select = null, $env = APPLICATION_ENV) {
		if (is_null($select)) {
			$select = $this->select();
		}
		$results = $this->fetchAll($select);

		$ini = $this->_createIniFromResults($results, $env);
		return $ini;
	}

	/**
 	 * Create a Zend_Config instance from database results
 	 * @param Zend_Db_Table_Rowset $results
 	 * @param Array $config The array that's recursively filled with the right keys
 	 * @return Zend_Config
 	 */
	protected function _createIniFromResults($results, $env) {
		// Create a parse_ini_string() compatible string.
		$ini = "[$env]\n";
		foreach ($results as $result) {
			$keyValue = "{$result->key} = \"{$result->value}\"\n";
			$ini .= $keyValue;
		}

		$iniObj = Garp_Config_Ini::fromString($ini);
		return $iniObj;
	}
}


text:
package lfsom.visualization.clustering;

import java.util.ArrayList;

import weka.clusterers.EM;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;

public class LFSWEKACluster {

	int numberOfInstances;
	int[] instancesInClusters;

	public LFSWEKACluster(int k, double[][] data, int nparalels,
			double minLogLike) {
		// Calcula el cluster empleando la clase de WEKA

		numberOfInstances = data.length;
		this.instancesInClusters = new int[numberOfInstances];

		EM clusterer = new EM();

		ArrayList<Attribute> listaAt = new ArrayList<Attribute>();

		for (int r = 0; r < data[0].length; r++)
			listaAt.add(r, new Attribute("At" + r));

		Instances data1 = new Instances("Cluster", listaAt, 0);

		for (int r = 0; r < numberOfInstances; r++)
			data1.add(new DenseInstance(1.0, data[r]));

		clusterer.setNumExecutionSlots(nparalels);
		// double aver = clusterer.getMinLogLikelihoodImprovementCV();
		clusterer.setMinLogLikelihoodImprovementCV(minLogLike);
		try {
			if (k > 0) {
				clusterer.setNumClusters(k);
				clusterer.setMaximumNumberOfClusters(k);
			}

			clusterer.buildClusterer(data1);

			for (int r = 0; r < numberOfInstances; r++) {
				this.instancesInClusters[r] = clusterer
						.clusterInstance(new DenseInstance(1.0, data[r]));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public int[] getResultados() {
		int resultados[] = new int[this.numberOfInstances];

		for (int k = 0; k < this.numberOfInstances; k++) {
			resultados[k] = this.instancesInClusters[k];
		}

		return resultados;
	}
}


text:
BTFXWSS
=======

Client for Bitfinex Websocket API written in Python

Currently supports all public endpoints; authenticated channels are a
work in progress.

Offers graceful exception handling of common server errors.

Data is stored within `BtfxWss` as `Queue`s. There are convenience
methods available to retrieve a queue for a given type. Consult
the code for more documentation.

Please note that you must take care of handling data in the queues yourself!
Not doing so will eventually result in `MemoryError`s, since the queues
do not have a maximum length defined.

Installation
------------

Via pip:

.. code-block:: bash

    pip install btfxwss

Usage
-----

Starting a session and subscribing to channels.

.. code-block:: python

    from btfxwss import BtfxWss

    logging.basicConfig(level=logging.DEBUG, filename='test.log')
    log = logging.getLogger(__name__)

    fh = logging.FileHandler('test.log')
    fh.setLevel(logging.DEBUG)
    sh = logging.StreamHandler(sys.stdout)
    sh.setLevel(logging.DEBUG)

    log.addHandler(sh)
    log.addHandler(fh)

    wss = BtfxWss()
    wss.start()
    while not wss.connection.is_connected.is_set():
        time.sleep(1)

    # Subscribe to some channels
    wss.subscribe_to_ticker('BTCUSD')
    wss.subscribe_to_order_book('BTCUSD')

    # Send a ping - if this returns silently, everything's fine.
    wss.ping()

    # Do something else
    t = time.time()
    while time.time() - t < 10:
        pass

Accessing data stored in BtfxWss:

.. code-block:: python

    ticker_q = wss.tickers('BTCUSD')  # returns a Queue object for the pair.
    while not ticker_q.empty():
        print(ticker_q.get())

Unsubscribing from channels:

.. code-block:: python

    wss.ticker('BTCUSD', unsubscribe=True)
    wss.ticker('BTCEUR', unsubscribe=True)

Shutting down the client:

.. code-block:: python

    wss.stop()

Your help is required
'''''''''''''''''''''

If you find any bugs, error or have feature requests, please don't hesitate to open an issue.
Be as descriptive as possible, and I'll look into the matter as soon as I can.

Thanks
''''''

A big thanks to the devs providing the websocket-client_ library,
as well ekulyk for providing the `PythonPusherClient`, which I used as a reference
for the connection class. And finally, a big thanks to all the people submitting
issues, discussing solutions and simply starring the project - you all help me
stay excited and motivated for this project! Cheers to you.

.. _websocket-client: https://github.com/websocket-client/websocket-client


text:
#pragma once

#include <curl/curl.h>

#include "status_bar.h"
#include "base_monitor.h"

struct nginx_monitor {
  struct base_monitor* base;

  GString* icon;
  GString* request_str;

  char* err;
  GString* res;
  struct http_data* http_data;
};

void* nginx_init(GArray*);
gboolean nginx_update_text(void*);
int nginx_sleep_time(void*);
void nginx_free(void*);

int format_nginx_status(GString*, GString*);


text:
package com.handywedge.converter.topdf.exceptions;

import com.handywedge.common.FWException;

public class FWConvertProcessException extends FWException {

  private static final long serialVersionUID = 1L;

  public FWConvertProcessException(String code, Object... args) {
    super(code, args);
  }

  public FWConvertProcessException(String code, Throwable cause, Object... args) {
    super(code, cause, args);
  }
}


text:
<!DOCTYPE html>

    <title>ComponentAlternativeType Enumeration Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

DITranquillity 4.1.1 Docs (90% documented)

View on GitHub

Install in Dash

          <form role="search" action="../search.json">
            <input type="text" placeholder="Search documentation" data-typeahead>
          </form>

        DITranquillity Reference

        ComponentAlternativeType Enumeration Reference

            Classes

                DIArg

                DIArgumentVertex

                DIByTag

                DICacheStorage

                DIComponentBuilder

                DIComponentVertex

                DICompositeStorage

                DIContainer

                DIEdge

                DIExtensions

                DIMany

                DIManyInFramework

                DIScope

                DIStoryboard

                DIUnknownVertex

                InternalArg

                InternalByMany

                InternalByManyInFramework

                InternalByTag

            Enumerations

                ComponentAlternativeType

                DIComponentPriority

                DILifeTime

                – ReferenceCounting

                DILogLevel

                DIVertex

            Extensions

                Lazy

                Provider

                Provider1

                Provider2

                Provider3

                Provider4

                Provider5

            Functions

                *(_:)

                arg(_:)

                by(tag:on:)

                by(tags:_:_:on:)

                by(tags:_:on:)

                many(_:)

                manyInFramework(_:)

            Protocols

                DIFramework

                DIPart

                DIStorage

            Structures

                DIComponentInfo

                DICycle

                DIGraph

                DISetting

                – Defaults

                – Log

            Type Aliases

                DIAType

                DILogFunc

                DITag

ComponentAlternativeType

public enum ComponentAlternativeType

Alternative type. It’ types setup in component used function as(...

                Show on GitHub

                    type(_:<wbr>)

Undocumented

Declaration

Swift

case type(DIAType)

                        Show on GitHub

                    tag(_:<wbr>type:<wbr>)

Undocumented

Declaration

Swift

case tag(DITag, type: DIAType)

                        Show on GitHub

                    name(_:<wbr>type:<wbr>)

Undocumented

Declaration

Swift

case name(String, type: DIAType)

                        Show on GitHub

© 2020 Ivlev. All rights reserved. (Last updated: 2020-09-05)

Generated by jazzy ♪♫ v0.13.5, a Realm project.


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<feature id="org.wso2.carbon.claim.mgt.ui" label="Claim Management UI Feature" provider-name="%providerName" version="4.2.0">
  <description>This feature contains the bundles required for Front-end Claim Management functionality</description>
  <copyright>%copyright</copyright>
  <license url="%licenseURL">%license</license>
  <plugin id="org.wso2.carbon.claim.mgt.ui" unpack="false" version="4.2.0"/>
  <plugin id="org.wso2.carbon.claim.mgt.stub" unpack="false" version="4.2.0"/>
  <require>
    <import feature="org.wso2.carbon.core.ui" match="equivalent" version="4.2.0"/>
  </require>
</feature>


text:
The Middlestack is a simple and convenient way to build and run of your own middleware stack for ruby

[![Build Status](https://travis-ci.org/undr/middlestack.svg)](https://travis-ci.org/undr/middlestack)
[![Code Climate](https://codeclimate.com/github/undr/middlestack/badges/gpa.svg)](https://codeclimate.com/github/undr/middlestack)
[![Test Coverage](https://codeclimate.com/github/undr/middlestack/badges/coverage.svg)](https://codeclimate.com/github/undr/middlestack)
[![Gem Version](https://badge.fury.io/rb/middlestack.svg)](http://badge.fury.io/rb/middlestack)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'middlestack'
```

And then execute:

```
$ bundle
```

Or install it yourself as:

```
$ gem install middlestack
```

## Usage

It's pretty simple.

```ruby
class TraceValue < Struct.new(:env, :value)
  def before
    env << ('->' + value)
  end

  def after
    env << ('<-' + value)
  end
end

class Executor
  include Middlestack::Helper

  middlewares do
    use TraceValue, 'A'
    use TraceValue, 'B'
    use TraceValue, 'C'
  end

  def execute
    run_middlewares([]){|env| env << 'run' }
  end
end

Executor.new.execute
# => ['->A', '->B', '->C', 'run', '<-C', '<-B', '<-A']
```

That's all. Have a nice code!

## Contributing

1. Fork it ( https://github.com/undr/middlestack/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
{% extends "layout/layout.html" %}
{% from "_helper.html" import href_image_button %}

{% block content %}
<legend> Inventory Table </legend>

  {{ href_image_button ("center","fa-info-circle","/inventory/") }}
List of all clusters

{% for cluster in clusters | sort %}

    {{ href_image_button ("center","fa-info-circle","/inventory/cluster/"+ cluster + "/") }}
    {{ href_image_button ("center","fa-table","/inventory/cluster/table/"+ cluster + "/") }}
    Cloudmesh - Inventory for {{ cluster }}

      Updated :  {{ updated }}

      {% for server in inventory[cluster] | sort  %}

		  		{{ server}}

        {% if (loop.index) %(parameters.columns) == 0  %}

	{% endif %}
        {% endfor %}

{% endfor %}

{% endblock %}


text:
'use strict';

var videoSourceList = [
    'TV1',
    'AV1', 'AV2', 'AV3', 'AV4',
    'SVIDEO1', 'SVIDEO2', 'SVIDEO3', 'SVIDEO4',
    'COMP1', 'COMP2', 'COMP3', 'COMP4',
    'PC1', 'PC2', 'PC3', 'PC4',
    'HDMI1', 'HDMI2', 'HDMI3', 'HDMI4',
    'SCART1', 'SCART2', 'SCART3', 'SCART4',
    'DVI1', 'DVI2', 'DVI3', 'DVI4'
];

var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec');

var tvwindowExport = {
    setSource: function (videoSource, successCallback, errorCallback) {
        argscheck.checkArgs('ofF', 'tvwindow.setSource', arguments);
        if(!videoSource.type || typeof videoSource.type != 'string') {
            throw new TypeError('videoSource.type is not a string.');
        }
        if(!videoSource.number || typeof videoSource.number != 'number') {
            throw new TypeError('videoSource.number is not a number.');
        }
        var match = false;
        for (var i = 0; i < videoSourceList.length; i++) {
            if (videoSource.type + videoSource.number == videoSourceList[i]) {
                match = true;
                break;
            }
        }
        if (!match) {
            throw new TypeError('videoSource is wrong.');
        }

        errorCallback = errorCallback || function () {};

        var args = [videoSource];
        exec(successCallback, errorCallback, 'toast.tvwindow', 'setSource', args);
    },
    getSource: function (successCallback, errorCallback) {
        argscheck.checkArgs('fF', 'tvwindow.getSource', arguments);

        errorCallback = errorCallback || function () {};

        var args = [];
        exec(successCallback, errorCallback, 'toast.tvwindow', 'getSource', args);
    },
    show: function (rectangle, successCallback, errorCallback) {
        argscheck.checkArgs('afF', 'tvwindow.show', arguments);
        if(rectangle.length != 4) {
            throw new TypeError('rectangle.length is wrong.');
        }
        if(typeof rectangle[0] != 'number' || rectangle[0] < 0) {
            throw new TypeError('rectangle[0] is not a positive number.');
        }
        if(typeof rectangle[1] != 'number' || rectangle[1] < 0) {
            throw new TypeError('rectangle[1] is not a positive number.');
        }
        if(typeof rectangle[2] != 'number' || rectangle[2] < 0) {
            throw new TypeError('rectangle[2] is not a positive number.');
        }
        if(typeof rectangle[3] != 'number' || rectangle[3] < 0) {
            throw new TypeError('rectangle[3] is not a positive number.');
        }

        errorCallback = errorCallback || function () {};

        var args = [rectangle];
        exec(successCallback, errorCallback, 'toast.tvwindow', 'show', args);
    },
    hide: function (successCallback, errorCallback) {
        argscheck.checkArgs('fF', 'tvwindow.hide', arguments);

        errorCallback = errorCallback || function () {};

        var args = [];
        exec(successCallback, errorCallback, 'toast.tvwindow', 'hide', args);
    },
    getRect: function (successCallback, errorCallback) {
        argscheck.checkArgs('fF', 'tvwindow.getRect', arguments);

        errorCallback = errorCallback || function () {};

        var args = [];
        exec(successCallback, errorCallback, 'toast.tvwindow', 'getRect', args);
    }
};

module.exports = tvwindowExport;


text:
package proxyproto

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"log"
	"net"
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	// prefix is the string we look for at the start of a connection
	// to check if this connection is using the proxy protocol
	prefix    = []byte("PROXY ")
	prefixLen = len(prefix)
)

// Listener is used to wrap an underlying listener,
// whose connections may be using the HAProxy Proxy Protocol (version 1).
// If the connection is using the protocol, the RemoteAddr() will return
// the correct client address.
type Listener struct {
	Listener net.Listener
}

// Conn is used to wrap and underlying connection which
// may be speaking the Proxy Protocol. If it is, the RemoteAddr() will
// return the address of the client instead of the proxy address.
type Conn struct {
	bufReader *bufio.Reader
	conn      net.Conn
	dstAddr   *net.TCPAddr
	srcAddr   *net.TCPAddr
	once      sync.Once
}

// Accept waits for and returns the next connection to the listener.
func (p *Listener) Accept() (net.Conn, error) {
	// Get the underlying connection
	conn, err := p.Listener.Accept()
	if err != nil {
		return nil, err
	}
	return NewConn(conn), nil
}

// Close closes the underlying listener.
func (p *Listener) Close() error {
	return p.Listener.Close()
}

// Addr returns the underlying listener's network address.
func (p *Listener) Addr() net.Addr {
	return p.Listener.Addr()
}

// NewConn is used to wrap a net.Conn that may be speaking
// the proxy protocol into a proxyproto.Conn
func NewConn(conn net.Conn) *Conn {
	pConn := &Conn{
		bufReader: bufio.NewReader(conn),
		conn:      conn,
	}
	return pConn
}

// Read is check for the proxy protocol header when doing
// the initial scan. If there is an error parsing the header,
// it is returned and the socket is closed.
func (p *Conn) Read(b []byte) (int, error) {
	var err error
	p.once.Do(func() { err = p.checkPrefix() })
	if err != nil {
		return 0, err
	}
	return p.bufReader.Read(b)
}

func (p *Conn) Write(b []byte) (int, error) {
	return p.conn.Write(b)
}

func (p *Conn) Close() error {
	return p.conn.Close()
}

func (p *Conn) LocalAddr() net.Addr {
	return p.conn.LocalAddr()
}

// RemoteAddr returns the address of the client if the proxy
// protocol is being used, otherwise just returns the address of
// the socket peer. If there is an error parsing the header, the
// address of the client is not returned, and the socket is closed.
// Once implication of this is that the call could block if the
// client is slow. Using a Deadline is recommended if this is called
// before Read()
func (p *Conn) RemoteAddr() net.Addr {
	p.once.Do(func() {
		if err := p.checkPrefix(); err != nil && err != io.EOF {
			log.Printf("[ERR] Failed to read proxy prefix: %v", err)
		}
	})
	if p.srcAddr != nil {
		return p.srcAddr
	}
	return p.conn.RemoteAddr()
}

func (p *Conn) SetDeadline(t time.Time) error {
	return p.conn.SetDeadline(t)
}

func (p *Conn) SetReadDeadline(t time.Time) error {
	return p.conn.SetReadDeadline(t)
}

func (p *Conn) SetWriteDeadline(t time.Time) error {
	return p.conn.SetWriteDeadline(t)
}

func (p *Conn) checkPrefix() error {
	// Incrementally check each byte of the prefix
	for i := 1; i <= prefixLen; i++ {
		inp, err := p.bufReader.Peek(i)
		if err != nil {
			return err
		}

		// Check for a prefix mis-match, quit early
		if !bytes.Equal(inp, prefix[:i]) {
			return nil
		}
	}

	// Read the header line
	header, err := p.bufReader.ReadString('\n')
	if err != nil {
		p.conn.Close()
		return err
	}

	// Strip the carriage return and new line
	header = header[:len(header)-2]

	// Split on spaces, should be (PROXY <type> <src addr> <dst addr> <src port> <dst port>)
	parts := strings.Split(header, " ")
	if len(parts) != 6 {
		p.conn.Close()
		return fmt.Errorf("Invalid header line: %s", header)
	}

	// Verify the type is known
	switch parts[1] {
	case "TCP4":
	case "TCP6":
	default:
		p.conn.Close()
		return fmt.Errorf("Unhandled address type: %s", parts[1])
	}

	// Parse out the source address
	ip := net.ParseIP(parts[2])
	if ip == nil {
		p.conn.Close()
		return fmt.Errorf("Invalid source ip: %s", parts[2])
	}
	port, err := strconv.Atoi(parts[4])
	if err != nil {
		p.conn.Close()
		return fmt.Errorf("Invalid source port: %s", parts[4])
	}
	p.srcAddr = &net.TCPAddr{IP: ip, Port: port}

	// Parse out the destination address
	ip = net.ParseIP(parts[3])
	if ip == nil {
		p.conn.Close()
		return fmt.Errorf("Invalid destination ip: %s", parts[3])
	}
	port, err = strconv.Atoi(parts[5])
	if err != nil {
		p.conn.Close()
		return fmt.Errorf("Invalid destination port: %s", parts[5])
	}
	p.dstAddr = &net.TCPAddr{IP: ip, Port: port}

	return nil
}


text:
module.exports = {
    getLocal: function(){
        return localStorage.getItem('lang') || 'zh-cn';
    },
    setLocal: function(lang){
        localStorage.setItem('lang', lang);
    }
};


text:
/** \file winstl/system/windows_directory.hpp
 *
 * \brief [C++ only] Definition of the winstl::basic_windows_directory class
 *  template
 *   (\ref group__library__system "System" Library).
 */

#ifndef WINSTL_INCL_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY
#define WINSTL_INCL_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY

#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define WINSTL_VER_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY_MAJOR       4
# define WINSTL_VER_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY_MINOR       2
# define WINSTL_VER_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY_REVISION    1
# define WINSTL_VER_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY_EDIT        65
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#ifndef WINSTL_INCL_WINSTL_H_WINSTL
# include <winstl/winstl.h>
#endif /* !WINSTL_INCL_WINSTL_H_WINSTL */
#ifndef STLSOFT_INCL_STLSOFT_STRING_HPP_SPECIAL_STRING_INSTANCE
# include <stlsoft/string/special_string_instance.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_STRING_HPP_SPECIAL_STRING_INSTANCE */
#ifndef WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR
# include <winstl/memory/processheap_allocator.hpp>
#endif /* !WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR */
#ifndef WINSTL_INCL_WINSTL_SYNCH_HPP_SPIN_MUTEX
# include <winstl/synch/spin_mutex.hpp>
#endif /* !WINSTL_INCL_WINSTL_SYNCH_HPP_SPIN_MUTEX */
#ifndef WINSTL_INCL_WINSTL_SYSTEM_HPP_SYSTEM_TRAITS
# include <winstl/system/system_traits.hpp>
#endif /* !WINSTL_INCL_WINSTL_SYSTEM_HPP_SYSTEM_TRAITS */

/* /////////////////////////////////////////////////////////////////////////
 * Namespace
 */

#ifndef _WINSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
     defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::winstl */
namespace winstl
{
# else
/* Define stlsoft::winstl_project */

namespace stlsoft
{

namespace winstl_project
{

# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_WINSTL_NO_NAMESPACE */

/* /////////////////////////////////////////////////////////////////////////
 * Classes
 */

/** \brief \ref group__pattern__special_string_instance "Special String Instance"
 *   policy template for eliciting the Windows directory.
 *
 * \ingroup group__library__system
 */
template <ss_typename_param_k C>
struct windir_policy
{
/// \name Member Types
/// @{
public:
    typedef C                           char_type;
    typedef processheap_allocator<C>    allocator_type;
    typedef ws_size_t                   size_type;
    typedef size_type                   (*pfn_type)(char_type *, size_type);
    typedef winstl::spin_mutex          spin_mutex_type;
    typedef winstl::atomic_int_t        atomic_int_type;
/// @}

/// \name Member Constants
/// @{
public:
    enum { internalBufferSize       =   32  };

    enum { allowImplicitConversion  =   1   };

    enum { sharedState              =   1   };
/// @}

/// \name Operations
/// @{
public:
    static pfn_type     get_fn()
    {
        return winstl::system_traits<char_type>::get_windows_directory;
    }
/// @}
};

/* /////////////////////////////////////////////////////////////////////////
 * Typedefs for commonly encountered types
 */

/** \brief A \ref group__pattern__special_string_instance "Special String Instance"
 *   that represents the Windows directory; ANSI specialisation.
 *
 * \ingroup group__library__system
 */
typedef stlsoft_ns_qual(special_string_instance_0)< windir_policy<ws_char_a_t> >    windows_directory_a;
/** \brief A \ref group__pattern__special_string_instance "Special String Instance"
 *   that represents the Windows directory; 'Unicode' specialisation.
 *
 * \ingroup group__library__system
 */
typedef stlsoft_ns_qual(special_string_instance_0)< windir_policy<ws_char_w_t> >    windows_directory_w;
/** \brief A \ref group__pattern__special_string_instance "Special String Instance"
 *   that represents the Windows directory; TCHAR specialisation.
 *
 * \ingroup group__library__system
 */
typedef stlsoft_ns_qual(special_string_instance_0)< windir_policy<TCHAR> >          windows_directory;

/* ////////////////////////////////////////////////////////////////////// */

#ifndef _WINSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
     defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} // namespace winstl
# else
} // namespace winstl_project
} // namespace stlsoft
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_WINSTL_NO_NAMESPACE */

/* ////////////////////////////////////////////////////////////////////// */

#endif /* WINSTL_INCL_WINSTL_SYSTEM_HPP_WINDOWS_DIRECTORY */

/* ///////////////////////////// end of file //////////////////////////// */


text:
import './nav-menu-item.css';

const navMenuItemTemplate = `
  <md-list-item ng-click="$ctrl.onItemClick($ctrl.item)">
    <md-icon md-svg-icon="{{ $ctrl.item.icon }}" aria-label="{{ $ctrl.item.title }}"></md-icon>

{{ $ctrl.item.title }}

  </md-list-item>
`;

class NavMenuItemController { }

export default {
  require: '^navMenu',
  bindings: { item: '<', onItemClick: '&' },
  template: navMenuItemTemplate,
  controller: NavMenuItemController,
};


text:
'use strict';

angular.module('vuboruServerApp')
    .controller('VotesCtrl', function ($scope, $routeParams, $http, data) {
        data.promise.then(function (entities) {
            $scope.id = $routeParams.id;

            $scope.operation = $routeParams.operation;

            $scope.version = entities.version();

            if (!$scope.operation) {
                $scope.items = entities.tables['Vote'];
            } else if ($scope.operation == 'view') {
                $scope.item = entities.tables.Vote[$scope.id];
            } else if ($scope.operation === 'create') {
                $scope.item = $scope.version.track($scope.version.create('Vote'));
            } else if ($scope.operation === 'update') {
                $scope.item = $scope.version.track(entities.tables.Vote[$scope.id]);
            } else if ($scope.operation === 'delete') {
                $scope.item = $scope.version.track(entities.tables.Vote[$scope.id]);

                $scope.item.deleted = true;
            }

            $scope.store = function () {
                data.save($scope.version);
            };

            $scope.$on('$destroy', function () {
                $scope.version.dispose();
            });
        })
    });


text:
package com.tale.jfluxdemo.adapter.delegate;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hannesdorfmann.adapterdelegates.AbsAdapterDelegate;
import com.tale.jfluxdemo.R;
import com.tale.jfluxdemo.adapter.viewholder.TodoItemVH;
import com.tale.jfluxdemo.model.Todo;
import java.util.List;

public class TodoListDelegateAdapter extends AbsAdapterDelegate<List<Todo>> {

  public TodoListDelegateAdapter(int viewType) {
    super(viewType);
  }

  @Override public boolean isForViewType(List<Todo> items, int position) {
    return true;
  }

  @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
    final View view =
        LayoutInflater.from(parent.getContext()).inflate(R.layout.item_todo, parent, false);
    return new TodoItemVH(view);
  }

  @Override public void onBindViewHolder(@NonNull List<Todo> items, int position,
      @NonNull RecyclerView.ViewHolder holder) {
    ((TodoItemVH) holder).bind(items.get(position));
  }
}


text:
package test.eci.datahub

import java.util.Date
import org.schedoscope.dsl.Parameter
import org.schedoscope.dsl.Parameter.p
import org.schedoscope.dsl.Structure
import org.schedoscope.dsl.View
import org.schedoscope.dsl.transformations.OozieTransformation
import org.schedoscope.dsl.transformations.OozieTransformation.oozieWFPath
import org.schedoscope.dsl.transformations.HiveTransformation
import org.schedoscope.dsl.transformations.HiveTransformation.insertInto
import org.schedoscope.dsl.views.DailyParameterization
import org.schedoscope.dsl.views.Id
import org.schedoscope.dsl.views.JobMetadata
import org.schedoscope.dsl.views.PointOccurrence
import org.schedoscope.dsl.transformations.MorphlineTransformation
import org.schedoscope.Settings
import org.apache.hadoop.security.UserGroupInformation
import org.schedoscope.dsl.storageformats._
import scala.io.Source

case class Brand(
  ecNr: Parameter[String]) extends View
    with Id
    with JobMetadata {

  comment("In this example, brands are per shop but time invariant")

  val ecShopCode = fieldOf[String](99, "Shop code, but field pushed to the right by weight.")
  val name = fieldOf[String]("The brand's name, but field name overriden", "brand_name")

  asTableSuffix(ecNr)
}

case class Product(
  ecNr: Parameter[String],
  year: Parameter[String],
  month: Parameter[String],
  day: Parameter[String]) extends View
    with Id
    with PointOccurrence
    with JobMetadata
    with DailyParameterization {

  comment("In this example, shops have different products each day")

  val ecShopCode = fieldOf[String]
  val name = fieldOf[String]
  val brandId = fieldOf[String]

  asTableSuffix(ecNr)
}

case class ProductBrand(
  ecNr: Parameter[String],
  year: Parameter[String],
  month: Parameter[String],
  day: Parameter[String]) extends View
    with PointOccurrence
    with JobMetadata
    with DailyParameterization {

  comment("ProductBrand joins brands with products")

  val ecShopCode = fieldOf[String]
  val productId = fieldOf[String]
  val brandName = privacySensitive(fieldOf[String])

  val brand = dependsOn(() => Brand(ecNr))
  val product = dependsOn(() => Product(ecNr, year, month, day))

  asTableSuffix(privacySensitive(ecNr))
  storedAs(Parquet())

  transformVia(() =>
    HiveTransformation(insertInto(
      this,
      s"""
         SELECT 	${this.ecNr.v.get} AS ${this.ecShopCode.n},
      				p.${product().id.n} AS ${this.productId.n},
          			b.${brand().name.n} AS ${this.brandName.n},
          			p.${product().occurredAt.n} AS ${this.occurredAt.n}
          			${new Date} AS ${this.createdAt.n}
          			${"ProductBrand"} AS ${this.createdBy.n}
          FROM 		${product().n} p
          JOIN 		${brand().n} b
          ON		p.${product().brandId.n} = b.${brand().id.n}
          WHERE 	p.${product().year.n} = ${this.year.v.get}
          AND 		p.${product().month.n} = ${this.month.v.get}
          AND 		p.${product().day.n} = ${this.day.v.get}
          """)))
}

case class NestedStructure() extends Structure {
  val aField = fieldOf[Boolean]
}

case class ComplexStructure() extends Structure {
  val aField = fieldOf[Int]
  val aComplexField = fieldOf[List[NestedStructure]]
}

case class EdgeCasesView() extends View {
  val aMap = fieldOf[Map[String, Int]]
  val anArray = fieldOf[List[Int]]
  val aComplicatedBitch = fieldOf[Map[List[String], List[Map[String, Int]]]]
  val aStructure = fieldOf[ComplexStructure]
}

case class AvroView(
  ecNr: Parameter[String],
  year: Parameter[String],
  month: Parameter[String],
  day: Parameter[String]) extends View
    with DailyParameterization {

  val aField = fieldOf[String]
  val anotherField = fieldOf[String]

  asTableSuffix(ecNr)

  storedAs(Avro("test.avsc"))
}

case class ViewWithDefaultParams(
    ecNr: Parameter[String],
    year: Parameter[String],
    month: Parameter[String],
    day: Parameter[String],
    defaultParameter: Int = 2) extends View {
}

case class Click(
  ecShopCode: Parameter[String],
  year: Parameter[String],
  month: Parameter[String],
  day: Parameter[String]) extends View
    with Id
    with DailyParameterization {

  val url = fieldOf[String]
}

case class ClickOfEC0101(
  year: Parameter[String],
  month: Parameter[String],
  day: Parameter[String]) extends View
    with Id
    with DailyParameterization {

  val url = fieldOf[String]

  val click = dependsOn(() => Click(p("EC0101"), year, month, day))

  transformVia(
    () => HiveTransformation(
      insertInto(this, s"""
            SELECT ${click().id.n}, ${click().url.n}
            FROM ${click().tableName}
            WHERE ${click().ecShopCode.n} = '${click().ecShopCode.v.get}'""")))
}

case class ClickOfEC0101ViaOozie(
  year: Parameter[String],
  month: Parameter[String],
  day: Parameter[String]) extends View
    with Id
    with DailyParameterization {

  val url = fieldOf[String]

  val click = dependsOn(() => Click(p("EC0101"), year, month, day))

  transformVia(
    () => OozieTransformation(
      "bundle", "click",
      oozieWFPath("bundle", "click")))
}

case class SimpleDependendView() extends View with Id {
  val field1 = fieldOf[String]
  tablePathBuilder = s => "src/test/resources/input"

  storedAs(TextFile())

}

case class MorphlineView() extends View with Id {
  val field1 = fieldOf[String]
  dependsOn(() => SimpleDependendView())
  transformVia(() => MorphlineTransformation(s"""{ id :"bla"
      importCommands : ["org.kitesdk.**"]
		  commands : [ {
		  				if  {
                                          conditions: [{ not: {equals {ec_shop_code : ["${field1.n}"]}}}]
    								      then : [{ dropRecord{} }]
    										}}]}""").forView(this))
  tablePathBuilder = s => "src/test/resources/morphline.csv"
  storedAs(ExternalTextFile())
}

case class CompilingMorphlineView() extends View with Id {
  val visit_id = fieldOf[String]
  val site = fieldOf[String]
  dependsOn(() => SimpleDependendView())

  transformVia(() => MorphlineTransformation(s"""{ id :"bla"
      importCommands : ["org.kitesdk.**"]
		  commands : [ { extractAvroTree{} }
		  				]}""").forView(this))
  tablePathBuilder = s => "src/test/resources/compling_morphline.csv"
  storedAs(ExternalTextFile())
}

case class FailingMorphlineView() extends View with Id {
  dependsOn(() => SimpleDependendView())
  transformVia(() => MorphlineTransformation("invalid morphline code").forView(this))
  tablePathBuilder = s => "src/test/resources/failing_morphline.csv"
  storedAs(ExternalTextFile())

}

case class HDFSInputView() extends View with Id {
  val field1 = fieldOf[String]
  tablePathBuilder = s => "/tmp/test"
  storedAs(Parquet())

}


text:
import React, { Component } from 'react';
import Container from './container';

export default class Quotes extends Component {
  render() {
    return (
      <div>
        <Container />
      </div>
    );
  }
}


text:
package io.finch.oauth2

case class OAuthUser(scope: String, name: String)


text:
import { atom } from "@alxshelepenok/diesel";
import { useCoilPersistedState } from "@alxshelepenok/diesel-extensions";

import { getDefaultColorMode } from "@/utils";

interface Theme {
  mode: "dark" | "light";
}

export const themeAtomKey = "diesel:theme-atom";

const themeAtom = atom<Theme>({
  key: "themeAtom",
  default: {
    mode: getDefaultColorMode(),
  },
});

const useTheme = (): readonly [Theme, () => void] => {
  const [theme, set] = useCoilPersistedState(themeAtom);

  const toggle = () => set({ mode: theme.mode === "dark" ? "light" : "dark" });

  return [theme, toggle];
};

export default useTheme;


text:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE TypeFamilies          #-}
module Aws.Iam.Commands.DeleteUserPolicy
    ( DeleteUserPolicy(..)
    , DeleteUserPolicyResponse(..)
    ) where

import           Aws.Core
import           Aws.Iam.Core
import           Aws.Iam.Internal
import           Data.Text          (Text)
import           Data.Typeable

-- | Deletes the specified policy associated with the specified user.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUserPolicy.html>
data DeleteUserPolicy
    = DeleteUserPolicy {
        dupPolicyName :: Text
      -- ^ Name of the policy to be deleted.
      , dupUserName   :: Text
      -- ^ Name of the user with whom the policy is associated.
      }
    deriving (Eq, Ord, Show, Typeable)

instance SignQuery DeleteUserPolicy where
    type ServiceConfiguration DeleteUserPolicy = IamConfiguration
    signQuery DeleteUserPolicy{..}
        = iamAction "DeleteUserPolicy" [
              ("PolicyName", dupPolicyName)
            , ("UserName", dupUserName)
            ]

data DeleteUserPolicyResponse = DeleteUserPolicyResponse
    deriving (Eq, Ord, Show, Typeable)

instance ResponseConsumer DeleteUserPolicy DeleteUserPolicyResponse where
    type ResponseMetadata DeleteUserPolicyResponse = IamMetadata
    responseConsumer _ _ =
        iamResponseConsumer (const $ return DeleteUserPolicyResponse)

instance Transaction DeleteUserPolicy DeleteUserPolicyResponse

instance AsMemoryResponse DeleteUserPolicyResponse where
    type MemoryResponse DeleteUserPolicyResponse = DeleteUserPolicyResponse
    loadToMemory = return


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace ConstructionToolWithOptions
{
  /// <summary>
  /// Interaction logic for BufferedLineToolOptionsView.xaml
  /// </summary>
  public partial class BufferedLineToolOptionsView : UserControl
  {
    public BufferedLineToolOptionsView()
    {
      InitializeComponent();
    }
  }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/IntersectionOfThreeSortedArrays.dir/main.cpp.o"
  "IntersectionOfThreeSortedArrays.pdb"
  "IntersectionOfThreeSortedArrays"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/IntersectionOfThreeSortedArrays.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

     <ListView
         android:id="@id/android:list"
         android:layout_width="match_parent"
         android:layout_height="0dp"
         android:layout_weight="1"
         android:background="#FFFFFF"
         android:drawSelectorOnTop="false"
         android:divider="@color/milton_orange"
    	android:dividerHeight="1dp"/>

 </LinearLayout>


text:
<?php

namespace LinguaLeo\DI;

use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
use LinguaLeo\DI\Token\ClassToken;
use LinguaLeo\DI\Token\ScalarToken;
use LinguaLeo\DI\Token\GotoToken;
use LinguaLeo\DI\Token\ConstantToken;
use LinguaLeo\DI\Exception\ClosureSerializationException;

class Scope
{
    protected $values;

    public function __construct(array $values)
    {
        $this->values = $values;
    }

    /**
     * Returns a value as a property.
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->$key = $this->getValue($key);
    }

    /**
     * Returns a value.
     *
     * @param string $key
     * @return mixed
     */
    public function getValue($key)
    {
        try {
            $token = $this->tokenize($key);
        } catch (ClosureSerializationException $ex) {
            return $this->values[$key]($this, $key);
        }
        return $token->newInstance($this);
    }

    /**
     * Tokenizes a value by an identifier.
     *
     * @param mixed $key
     * @return \LinguaLeo\DI\TokenInterface
     * @throws \InvalidArgumentException
     */
    public function tokenize($key)
    {
        if (!isset($this->values[$key])) {
            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $key));
        }
        return $this->parseToken($this->values[$key], $key);
    }

    /**
     * Returns a token for a class.
     *
     * @param ReflectionClass $class
     * @param string $key
     * @return \LinguaLeo\DI\Token\ClassToken
     * @throws \UnexpectedValueException
     */
    private function getClassToken(ReflectionClass $class, $key)
    {
        if (!$class->inNamespace()) {
            throw new \ReflectionException(sprintf('No namespace found for the class "%s"', $class->name));
        }
        if (!$class->isInstantiable()) {
            if (empty($this->values[$class->name])) {
                throw new \UnexpectedValueException(
                    sprintf('No implementation found for "%s" in the path "%s".', $class->name, $key)
                );
            }
            return $this->parseToken($this->values[$class->name], $key);
        }
        $args = [];
        $constructor = $class->getConstructor();
        if ($constructor) {
            $args = $this->getArguments($constructor, $key);
        }
        return new ClassToken($key, $class, $args);
    }

    /**
     * Parses a token.
     *
     * @param mixed $value
     * @param string $key
     * @return \LinguaLeo\DI\TokenInterface
     * @throws \LinguaLeo\DI\Exception\ClosureSerializationException
     * @throws \InvalidArgumentException
     */
    protected function parseToken($value, $key)
    {
        if (is_object($value) && $value instanceof \Closure) {
            throw new ClosureSerializationException(sprintf('Serialization of Closure "%s" is not allowed', $key));
        }
        if (is_string($value) && !empty($value)) {
            switch ($value[0]) {
                case '@':
                    return $this->getSymlinkToken($value);
                case '$':
                    return $this->getVariableToken(substr($value, 1));
            }
            if (defined($value)) {
                return new ConstantToken($value);
            }
            try {
                return $this->getClassToken(new ReflectionClass($value), $key);
            } catch (\ReflectionException $ex) {
                error_log($ex->getMessage());
            }
        }
        return new ScalarToken($value);
    }

    /**
     * Returns arguments for a constructor.
     *
     * @param ReflectionMethod $constructor
     * @param string $key
     * @return array
     * @throws \InvalidArgumentException
     */
    private function getArguments(ReflectionMethod $constructor, $key)
    {
        $args = [];
        foreach ($constructor->getParameters() as $parameter) {
            $args[] = $this->getArgument($parameter, $key);
        }
        return $args;
    }

    /**
     * Finds a token for a parameter
     *
     * @param ReflectionParameter $parameter
     * @param string $key
     * @return \LinguaLeo\DI\TokenInterface
     * @throws \InvalidArgumentException
     */
    private function getArgument(ReflectionParameter $parameter, $key)
    {
        $key .= '.'.$parameter->name;
        try {
            return $this->tokenize($key);
        } catch (\InvalidArgumentException $ex) {
            $class = $parameter->getClass();
            if ($class) {
                return $this->getClassToken($class, $key);
            }
            if ($parameter->isDefaultValueAvailable()) {
                return new ScalarToken($parameter->getDefaultValue());
            }
            throw $ex;
        }
    }

    /**
     * Returns a token for a symlink.
     *
     * @param string $key
     * @return \LinguaLeo\DI\Token\GotoToken
     * @throws \UnexpectedValueException
     */
    private function getSymlinkToken($key)
    {
        if (empty($this->values[$key])) {
            throw new \UnexpectedValueException(sprintf('Unknown %s symlink', $key));
        }
        return new GotoToken($this->values[$key]);
    }

    /**
     * Returns a token for a variable.
     *
     * @param string $key
     * @return \LinguaLeo\DI\Token\GotoToken
     * @throws \UnexpectedValueException
     */
    private function getVariableToken($key)
    {
        if (empty($this->values[$key])) {
            throw new \UnexpectedValueException(sprintf('Unknown "%s" variable', $key));
        }
        return new GotoToken($key);
    }

    /**
     * Compiles values into php script.
     *
     * @param array $values
     * @return string
     */
    public static function compile(array $values)
    {
        $scope = new self($values);
        $script = '['.PHP_EOL;
        foreach ($scope->values as $id => $value) {
            if (interface_exists($id)) {
                continue;
            }
            $script .= "'$id' => ".$scope->parseToken($value, $id)->getBinding().','.PHP_EOL;
        }
        return $script.']';
    }
}


text:
package org.opensingular.flow.core.renderer;

import com.google.common.math.StatsAccumulator;

import javax.annotation.Nonnull;
import java.util.Optional;

/**
 * Represents the execution statistics of a particular task of the flow.
 *
 * @author Daniel C. Bordin
 * @since 2018-08-28
 */
public final class StatisticsTask {

    private final StatsAccumulator statsDuration = new StatsAccumulator();
    private final StatsAccumulator statsLast = new StatsAccumulator();
    private int countStarts = 0;
    private int countIns = 0;
    private int countOuts = 0;

    @Nonnull
    public StatsAccumulator getStatsDuration() {
        return statsDuration;
    }

    @Nonnull
    public StatsAccumulator getStatsLast() {
        return statsLast;
    }

    public int getCountStarts() {
        return countStarts;
    }

    public int getCountIns() {
        return countIns;
    }

    public int getCountOuts() {
        return countOuts;
    }

    public int countCurrents() {
        return countIns - countOuts;
    }

    public void registerStart() {
        countStarts++;
        countIns++;
    }

    public void registerOutTransition(long durationMilli) {
        statsDuration.add(durationMilli);
        countOuts++;
    }

    public void registerInTransition() {
        countIns++;
    }

    public void registerLast(long dtStartLastMilli) {
        statsLast.add(dtStartLastMilli);
    }

    @Nonnull
    public Optional<Double> getMeanDateStartAsLast() {
        return statsLast.count() > 0 ? Optional.of(statsLast.mean()) : Optional.empty();
    }
}