text:
/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#ifndef GUCEF_CORE_CCOREGLOBAL_H
#include "gucefCORE_CCoreGlobal.h"
#define GUCEF_CORE_CCOREGLOBAL_H
#endif /* GUCEF_CORE_CCOREGLOBAL_H ? */

#ifndef GUCEF_CORE_CGUCEFAPPLICATION_H
#include "CGUCEFApplication.h"
#define GUCEF_CORE_CGUCEFAPPLICATION_H
#endif /* GUCEF_CORE_CGUCEFAPPLICATION_H ? */

#ifndef GUCEF_CORE_LOGGING_H
#include "gucefCORE_Logging.h"
#define GUCEF_CORE_LOGGING_H
#endif /* GUCEF_CORE_LOGGING_H ? */

#ifndef GUCEF_CORE_DVCPPFILEUTILS_H
#include "dvcppfileutils.h"
#define GUCEF_CORE_DVCPPFILEUTILS_H
#endif /* GUCEF_CORE_DVCPPFILEUTILS_H ? */

#ifndef GUCEF_CORE_DVCPPOSWRAP_H
#include "DVCPPOSWRAP.h"
#define GUCEF_CORE_DVCPPOSWRAP_H
#endif /* GUCEF_CORE_DVCPPOSWRAP_H ? */

#ifndef GUCEF_CORE_CROLLINGFILEACCESS_H
#include "gucefCORE_CRollingFileAccess.h"
#define GUCEF_CORE_CROLLINGFILEACCESS_H
#endif /* GUCEF_CORE_CROLLINGFILEACCESS_H ? */

#ifndef GUCEF_CORE_CONFIGSTORE_H
#include "CConfigStore.h"
#define GUCEF_CORE_CONFIGSTORE_H
#endif /* GUCEF_CORE_CONFIGSTORE_H ? */

#ifndef GUCEF_CORE_CPLATFORMNATIVECONSOLEWINDOW_H
#include "gucefCORE_CPlatformNativeConsoleWindow.h"
#define GUCEF_CORE_CPLATFORMNATIVECONSOLEWINDOW_H
#endif /* GUCEF_CORE_CPLATFORMNATIVECONSOLEWINDOW_H ? */

#ifndef GUCEF_CORE_CGLOBALCONFIGVALUELIST_H
#include "gucefCORE_CGlobalConfigValueList.h"
#define GUCEF_CORE_CGLOBALCONFIGVALUELIST_H
#endif /* GUCEF_CORE_CGLOBALCONFIGVALUELIST_H ? */

#ifndef GUCEF_CORE_CTIMER_H
#include "CTimer.h"
#define GUCEF_CORE_CTIMER_H
#endif /* GUCEF_CORE_CTIMER_H ? */

#ifndef GUCEF_COMCORE_CUDPSOCKET_H
#include "CUDPSocket.h"
#define GUCEF_COMCORE_CUDPSOCKET_H
#endif /* GUCEF_COMCORE_CUDPSOCKET_H ? */

#ifndef GUCEF_COMCORE_CTCPSERVERSOCKET_H
#include "CTCPServerSocket.h"
#define GUCEF_COMCORE_CTCPSERVERSOCKET_H
#endif /* GUCEF_COMCORE_CTCPSERVERSOCKET_H ? */

#ifndef GUCEF_COMCORE_CCOMCOREGLOBAL_H
#include "gucefCOMCORE_CComCoreGlobal.h"
#define GUCEF_COMCORE_CCOMCOREGLOBAL_H
#endif /* GUCEF_COMCORE_CCOMCOREGLOBAL_H ? */

#ifndef GUCEF_COM_CCOMGLOBAL_H
#include "gucefCOM_CComGlobal.h"
#define GUCEF_COM_CCOMGLOBAL_H
#endif /* GUCEF_COM_CCOMGLOBAL_H ? */

#ifndef GUCEF_VFS_CVFSGLOBAL_H
#include "gucefVFS_CVfsGlobal.h"
#define GUCEF_VFS_CVFSGLOBAL_H
#endif /* GUCEF_VFS_CVFSGLOBAL_H ? */

#ifndef GUCEF_WEB_CWEBGLOBAL_H
#include "gucefWEB_CWebGlobal.h"
#define GUCEF_WEB_CWEBGLOBAL_H
#endif /* GUCEF_WEB_CWEBGLOBAL_H ? */

#include "MsmqMetrics.h"

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

using namespace GUCEF;

/*-------------------------------------------------------------------------//
//                                                                         //
//      UTILITIES                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

CORE::CString
LookForConfigFile( const CORE::CString& configFile )
{GUCEF_TRACE;

    GUCEF_LOG( CORE::LOGLEVEL_BELOW_NORMAL, "Checking for config file @ " + configFile );
    if ( !CORE::FileExists( configFile ) )
    {
        CORE::CString configFilePath = CORE::CombinePath( "$CURWORKDIR$", configFile );
        configFilePath = CORE::RelativePath( configFilePath );

        GUCEF_LOG( CORE::LOGLEVEL_BELOW_NORMAL, "Checking for config file @ " + configFilePath );
        if ( !CORE::FileExists( configFilePath ) )
        {
            configFilePath = CORE::CombinePath( "$MODULEDIR$", configFile );
            configFilePath = CORE::RelativePath( configFilePath );

            GUCEF_LOG( CORE::LOGLEVEL_BELOW_NORMAL, "Checking for config file @ " + configFilePath );
            if ( !FileExists( configFilePath ) )
            {
                configFilePath = CORE::CombinePath( "$TEMPDIR$", configFile );
                configFilePath = CORE::RelativePath( configFilePath );

                GUCEF_LOG( CORE::LOGLEVEL_BELOW_NORMAL, "Checking for config file @ " + configFilePath );
                if ( !FileExists( configFilePath ) )
                {
                    return CORE::CString::Empty;
                }
            }
        }

        return configFilePath;
    }

    return configFile;
}

/*-------------------------------------------------------------------------*/

bool
LoadConfig( const CORE::CString& bootstrapConfigPath   ,
            const CORE::CString& configPath            ,
            CORE::CValueList& keyValueList             ,
            CORE::CDataNode* loadedConfig = GUCEF_NULL )
{GUCEF_TRACE;

    #ifdef GUCEF_DEBUG_MODE
    const CORE::CString bootstrapConfigFile = "MsmqMetrics_bootstrap_d.ini";
    const CORE::CString configFile = "MsmqMetrics_d.ini";
    #else
    const CORE::CString bootstrapConfigFile = "MsmqMetrics_bootstrap.ini";
    const CORE::CString configFile = "MsmqMetrics.ini";
    #endif

    CORE::CConfigStore& configStore = CORE::CCoreGlobal::Instance()->GetConfigStore();

    CORE::CString bootstrapConfigFilePath = LookForConfigFile( bootstrapConfigFile );
    CORE::CString configFilePath = LookForConfigFile( configFile );

    if ( !bootstrapConfigFilePath.IsNULLOrEmpty() )
    {
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Located bootstrap config file @ " + bootstrapConfigFilePath );
        configStore.SetBootstrapConfigFile( bootstrapConfigFilePath );
    }
    if ( !configFilePath.IsNULLOrEmpty() )
    {
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Located config file @ " + configFilePath );
        configStore.SetConfigFile( configFilePath );
    }
    if ( bootstrapConfigFilePath.IsNULLOrEmpty() && configFilePath.IsNULLOrEmpty() )
    {
        GUCEF_WARNING_LOG( CORE::LOGLEVEL_NORMAL, "Unable to locate any config file, will rely on params only" );
    }

    CORE::CGlobalConfigValueList globalCfg;
    globalCfg.SetConfigNamespace( "Main/AppArgs" );
    globalCfg.SetAllowDuplicates( false );
    globalCfg.SetAllowMultipleValues( true );

    bool loadSuccess = configStore.LoadConfig( loadedConfig );

    keyValueList = globalCfg;
    return loadSuccess;
}

/*-------------------------------------------------------------------------*/

void
ParseParams( const int argc                 ,
             char* argv[]                   ,
             CORE::CValueList& keyValueList )
{GUCEF_TRACE;

    GUCEF::CORE::CString argString;
    if ( argc > 0 )
    {
        argString = *argv;

        // Combine the argument strings back into a single string because we don't want to use
        // a space as the seperator
        for ( int i=1; i<argc; ++i )
        {
            argString += ' ' + CORE::CString( argv[ i ] );
        }

        // Parse the param list based on the ' symbol
        GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Application parameters: " + argString );
        keyValueList.SetMultiple( argString, '*' );
    }
}

/*-------------------------------------------------------------------------*/

void
GucefAppSignalHandler( int signal )
{GUCEF_TRACE;

    GUCEF_LOG( CORE::LOGLEVEL_IMPORTANT, "GucefAppSignalHandler: Received signal " + CORE::ToString( signal ) );
    ::GUCEF::CORE::CCoreGlobal::Instance()->GetApplication().Stop();
}

/*-------------------------------------------------------------------------*/

/*
 *      Application entry point
 */
//GUCEF_OSMAIN_BEGIN
GUCEF_OSSERVICEMAIN_BEGIN( "MsmqMetrics" )
{GUCEF_TRACE;

    int returnValue = -100;
    try
    {

    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "This service was compiled on: " __DATE__ " @ " __TIME__ );

    CORE::CCoreGlobal::Instance();
    COMCORE::CComCoreGlobal::Instance();
    COM::CComGlobal::Instance();

    // Check for config param first
    CORE::CValueList keyValueList;
    ParseParams( argc, argv, keyValueList );
    CORE::CString bootstrapConfigPathParam = keyValueList.GetValueAlways( "BootstrapConfigPath" );
    CORE::CString configPathParam = keyValueList.GetValueAlways( "ConfigPath" );
    keyValueList.Clear();

    // Load settings from a config file (if any) and then override with params (if any)
    CORE::CDataNode* globalConfig = new CORE::CDataNode();
    LoadConfig( bootstrapConfigPathParam, configPathParam, keyValueList, globalConfig );
    ParseParams( argc, argv, keyValueList );

    CORE::Int32 minLogLevel = CORE::LOGLEVEL_BELOW_NORMAL;
    CORE::CString valueStr = keyValueList.GetValueAlways( "MinimalLogLevel" );
    if ( !valueStr.IsNULLOrEmpty() )
    {
        minLogLevel = CORE::StringToInt32( valueStr );
        CORE::CCoreGlobal::Instance()->GetLogManager().SetMinLogLevel( minLogLevel );
    }

    CORE::CString outputDir = CORE::RelativePath( keyValueList.GetValueAlways( "outputDir" ) );
    if ( outputDir.IsNULLOrEmpty() )
    {
        outputDir = CORE::RelativePath( "$CURWORKDIR$" );
    }
    CORE::CreateDirs( outputDir );

    CORE::CString logFilename = CORE::CombinePath( outputDir, "MsmqMetrics_log.txt" );

    keyValueList.Set( "logfile", logFilename );

    CORE::CRollingFileAccess logFileAccess( logFilename, "w" );
    logFileAccess.SetMaxRolloverFilesBeforeDeletion( 10 );
    CORE::CStdLogger logger( logFileAccess );
    CORE::CCoreGlobal::Instance()->GetLogManager().AddLogger( &logger );

    CORE::CPlatformNativeConsoleLogger console;
    if ( GUCEF_APP_TYPE == GUCEF_APP_TYPE_CONSOLE )
        CORE::CCoreGlobal::Instance()->GetLogManager().AddLogger( console.GetLogger() );

    CORE::CCoreGlobal::Instance()->GetLogManager().FlushBootstrapLogEntriesToLogs();
    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Flushed to log @ " + logFilename );

    GUCEF_OSMAIN_SIGNAL_HANDLER( GucefAppSignalHandler );

    MsmqMetrics msmqMetrics;
    if ( !msmqMetrics.LoadConfig( keyValueList, *globalConfig ) )
    {
        delete globalConfig;
        GUCEF_ERROR_LOG( CORE::LOGLEVEL_CRITICAL, "MsmqMetrics: Exiting because LoadConfig failed" );
        return -1;
    }
    delete globalConfig;

    if ( !msmqMetrics.Start() )
    {
        GUCEF_ERROR_LOG( CORE::LOGLEVEL_CRITICAL, "MsmqMetrics: Failed to Start()" );
        return -2;
    }

    auto& app = CORE::CCoreGlobal::Instance()->GetApplication();
    app.SetForcedMinimalCycleDeltaInMilliSecs( 500 );
    app.SetDesiredMaximumCycleDeltaInMilliSecs( 10000 );
    returnValue = app.main( argc, argv, true );
    msmqMetrics.SetStandbyMode( true );

    }
    catch ( const std::exception& e )
    {
        GUCEF_EXCEPTION_LOG( CORE::LOGLEVEL_CRITICAL, "MsmqMetrics: Main thread stl exeption: " + CORE::CString( e.what() ) );
        //throw e;
    }
    #ifndef GUCEF_DEBUG_MODE
    catch ( ... )
    {
        GUCEF_EXCEPTION_LOG( CORE::LOGLEVEL_CRITICAL, "MsmqMetrics: Main thread unknown exeption occured. Caught in catch-all" );
        throw;
    }
    #endif

    return returnValue;
}
GUCEF_OSMAIN_END

/*---------------------------------------------------------------------------*/


text:
package com.vaadin.tests.components.loginform;

import java.util.Optional;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractReindeerTestUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.LoginForm;
import com.vaadin.ui.VerticalLayout;

public class LoginFormUI extends AbstractReindeerTestUI {

    private HorizontalLayout loginFormLayout;
    protected LoginForm loginForm;

    @Override
    protected void setup(VaadinRequest request) {
        loginFormLayout = new HorizontalLayout();

        loginForm = new LoginForm();
        loginForm.setSizeUndefined();
        getUsernameCaption().ifPresent(loginForm::setUsernameCaption);
        getPasswordCaption().ifPresent(loginForm::setPasswordCaption);
        getLoginCaption().ifPresent(loginForm::setLoginButtonCaption);
        updateCaption();
        loginForm.addLoginListener(event -> login(event.getSource(),
                event.getLoginParameter("username"),
                event.getLoginParameter("password")));

        loginFormLayout.addComponent(loginForm);

        Button changeWidth = new Button("Change width",
                (ClickListener) event -> {
                    if (loginForm.getWidth() < 0) {
                        loginForm.setWidth("300px");
                    } else {
                        loginForm.setWidth(null);
                    }
                    updateCaption();
                });

        Button changeHeight = new Button("Change height",
                (ClickListener) event -> {
                    if (loginForm.getHeight() < 0) {
                        loginForm.setHeight("200px");
                    } else {
                        loginForm.setHeight(null);
                    }
                    updateCaption();
                });

        addComponent(loginFormLayout);
        addComponent(changeWidth);
        addComponent(changeHeight);

    }

    protected Optional<String> getUsernameCaption() {
        return Optional.empty();
    }

    protected Optional<String> getPasswordCaption() {
        return Optional.empty();
    }

    protected Optional<String> getLoginCaption() {
        return Optional.empty();
    }

    protected void updateCaption() {
        float width = loginForm.getWidth();
        float height = loginForm.getHeight();

        String w = width < 0 ? "auto" : (int) width + "px";
        String h = height < 0 ? "auto" : (int) height + "px";

        loginForm.setCaption("LoginForm (" + w + "/" + h + ")");
    }

    protected void login(LoginForm loginForm, String user, String password) {
        VerticalLayout infoLayout = new VerticalLayout();

        Label info = new Label(
                "User '" + user + "', password='" + password + "' logged in");
        info.setId("info");
        Button logoutButton = new Button("Log out", (ClickListener) event -> {
            Button b = event.getButton();
            loginFormLayout.replaceComponent(b.getParent(),
                    (LoginForm) b.getData());
        });
        logoutButton.setData(loginForm);

        infoLayout.addComponent(info);
        infoLayout.addComponent(logoutButton);

        loginFormLayout.replaceComponent(loginForm, infoLayout);

    }

    @Override
    protected String getTestDescription() {
        return "Basic test for the LoginForm component.";
    }

    @Override
    protected Integer getTicketNumber() {
        return 3597;
    }

}

redpajama_set_name: RedPajamaGithub


text: complete -A command no_sound


text:
package de.rwth.idsg.bikeman.domain;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Type;
import org.joda.time.LocalDateTime;

import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;

@Entity
@Table(name = "T_TRANSACTION",
        indexes = {
                @Index(columnList="pedelec_id", unique = false),
                @Index(columnList="from_slot_id", unique = false),
                @Index(columnList="to_slot_id", unique = false) })
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@TableGenerator(name="transaction_gen", initialValue=0, allocationSize=1)
@EqualsAndHashCode(of = {"transactionId"})
@ToString(includeFieldNames = true, exclude = {"cardAccount"})
@Getter
@Setter
public class Transaction implements Serializable {
    private static final long serialVersionUID = 7444900986847008432L;

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "transaction_gen")
    @Column(name = "transaction_id")
    private long transactionId;

    @Column(name = "start_datetime")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    private LocalDateTime startDateTime;

    @Column(name = "end_datetime")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    private LocalDateTime endDateTime;

    @ManyToOne
    @JoinColumn(name = "pedelec_id")
    private Pedelec pedelec;

    @ManyToOne
    @JoinColumn(name = "from_slot_id")
    private StationSlot fromSlot;

    @ManyToOne
    @JoinColumn(name = "to_slot_id")
    private StationSlot toSlot;

    @ManyToOne
    @JoinColumn(name = "card_account_id")
    private CardAccount cardAccount;

    @ManyToOne
    @JoinColumn(name = "booked_tariff_id")
    private BookedTariff bookedTariff;

    @Column(name = "fees")
    private BigDecimal fees;

}


text:
/*! mediabox v1.1.3 | (c) 2018 Pedro Rogerio | https://github.com/pinceladasdaweb/mediabox */
(function (root, factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.MediaBox = factory();
    }
}(this, function () {
    "use strict";

    var MediaBox = function (element, params) {
        var default_params = { autoplay: '1' },
            params = params || 0;

        if (!this || !(this instanceof MediaBox)) {
            return new MediaBox(element, params);
        }

        if (!element) {
            return false;
        }

        this.params = Object.assign(default_params, params);
        this.selector = element instanceof NodeList ? element : document.querySelectorAll(element);
        this.root     = document.querySelector('body');
        this.run();
    };

    MediaBox.prototype = {
        run: function () {
            Array.prototype.forEach.call(this.selector, function (el) {
                el.addEventListener('click', function (e) {
                    e.preventDefault();

                    var link = this.parseUrl(el.getAttribute('href'));
                    this.render(link);
                    this.events();
                }.bind(this), false);
            }.bind(this));

            this.root.addEventListener('keyup', function (e) {
                if ((e.keyCode || e.which) === 27) {
                    this.close(this.root.querySelector('.mediabox-wrap'));
                }
            }.bind(this), false);
        },
        template: function (s, d) {
            var p;

            for (p in d) {
                if (d.hasOwnProperty(p)) {
                    s = s.replace(new RegExp('{' + p + '}', 'g'), d[p]);
                }
            }
            return s;
        },
        parseUrl: function (url) {
            var service = {},
                matches;

            if (matches = url.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/)) {
                service.provider = "youtube";
                service.id       = matches[2];
            } else if (matches = url.match(/https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/)) {
                service.provider = "vimeo";
                service.id       = matches[3];
            } else {
                service.provider = "Unknown";
                service.id       = '';
            }

            return service;
        },
        render: function (service) {
            var embedLink,
                lightbox,
                urlParams;

            if (service.provider === 'youtube') {
                embedLink = 'https://www.youtube.com/embed/' + service.id;
            } else if (service.provider === 'vimeo') {
                embedLink = 'https://player.vimeo.com/video/' + service.id;
            } else {
                throw new Error("Invalid video URL");
            }

            urlParams = this.serialize(this.params);

            lightbox = this.template(
                '

', {
                    embed: embedLink,
                    params: urlParams
                });

            this.lastFocusElement = document.activeElement;
            this.root.insertAdjacentHTML('beforeend', lightbox);
            document.body.classList.add('stop-scroll');
        },
        events: function () {
            var wrapper = document.querySelector('.mediabox-wrap');
            var content = document.querySelector('.mediabox-content');

            wrapper.addEventListener('click', function (e) {
                if (e.target && e.target.nodeName === 'SPAN' && e.target.className === 'mediabox-close' || e.target.nodeName === 'DIV' && e.target.className === 'mediabox-wrap' || (e.target.className === 'mediabox-content' && e.target.nodeName !== 'IFRAME')) {
                    this.close(wrapper);
                }
            }.bind(this), false);

            document.addEventListener('focus', function(e) {
                if (content && !content.contains(e.target)) {
                    e.stopPropagation();
                    content.focus();
                }
            }, true);

            content.addEventListener('keypress', function(e) {
                if (e.keyCode === 13) {
                    this.close(wrapper);
                }
            }.bind(this), false);
        },
        close: function (el) {
            if (el === null) return true;
            var timer = null;

            if (timer) {
                clearTimeout(timer);
            }

            el.classList.add('mediabox-hide');

            timer = setTimeout(function() {
                var el = document.querySelector('.mediabox-wrap');
                if (el !== null) {
                    document.body.classList.remove('stop-scroll');
                    this.root.removeChild(el);
                    this.lastFocusElement.focus();
                }
            }.bind(this), 500);
        },
        serialize: function (obj) {
            return '?'+Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
        }
    };

    return MediaBox;
}));

/**
 * Object.assign polyfill for IE support
 * Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
 */
if (typeof Object.assign != 'function') {
    // Must be writable: true, enumerable: false, configurable: true
    Object.defineProperty(Object, "assign", {
        value: function assign(target, varArgs) { // .length of function is 2
        'use strict';
        if (target == null) { // TypeError if undefined or null
            throw new TypeError('Cannot convert undefined or null to object');
        }

        var to = Object(target);

        for (var index = 1; index < arguments.length; index++) {
            var nextSource = arguments[index];

            if (nextSource != null) { // Skip over if undefined or null
            for (var nextKey in nextSource) {
                // Avoid bugs when hasOwnProperty is shadowed
                if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                to[nextKey] = nextSource[nextKey];
                }
            }
            }
        }
        return to;
        },
        writable: true,
        configurable: true
    });
}


text:
<?php
/**
 * @author    MyBB Group
 * @version   2.0.0
 * @package   mybb/core
 * @license   http://www.mybb.com/licenses/bsd3 BSD-3
 */

namespace MyBB\Core\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use MyBB\Core\Database\Models\Forum;
use MyBB\Core\Database\Models\Post;
use MyBB\Core\Database\Models\Topic;
use MyBB\Core\Database\Models\User;
use Symfony\Component\Console\Input\InputOption;

class RecountCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'mybb:recount';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Recounts some of MyBB\'s counters. If called without options all recounts are run';

    /**
     * @var CacheRepository
     */
    private $cache;

    /**
     * @param CacheRepository $cache
     */
    public function __construct(CacheRepository $cache)
    {
        parent::__construct();

        $this->cache = $cache;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $options = $this->option();

        $runAll = !$options['forums'] && !$options['topics'] && !$options['users'];

        // If we want to recount topics and forums we should recount topics first
        // otherwise the forum counter will go crazy
        if ($runAll || $options['topics']) {
            $this->recountTopics();
        }

        if ($runAll || $options['forums']) {
            $this->recountForums();
        }

        if ($runAll || $options['users']) {
            $this->recountUsers();
        }
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['forums', 'f', InputOption::VALUE_NONE, 'Recount forum counters', null],
            ['topics', 't', InputOption::VALUE_NONE, 'Recount topic counters', null],
            ['users', 'u', InputOption::VALUE_NONE, 'Recount user counters', null],
        ];
    }

    private function recountForums()
    {
        $this->info('Recounting forum counters...');

        // We're calling the model directly to avoid caching issues
        $forums = Forum::all();
        foreach ($forums as $forum) {
            // We need the topics later to calculate the post number and the last post
            $topics = Topic::where('forum_id', '=', $forum->id)->orderBy('created_at', 'desc');
            $forum->num_topics = $topics->count();
            $numPosts = 0;
            $lastPost = null;
            $lastPostUser = null;

            foreach ($topics->get() as $topic) {
                $numPosts += $topic->num_posts;
                // We can simply override this variable all the time.
                // The topics are sorted so the last time we override this we have our last post
                $lastPost = $topic->last_post_id;
                $lastPostUser = $topic->lastPost->user_id;
            }

            $forum->num_posts = $numPosts;
            $forum->last_post_id = $lastPost;
            $forum->last_post_user_id = $lastPostUser;

            $forum->save();
        }

        // Override our old cache to populate our new numbers
        $this->cache->forever('forums.all', $forums);
        // We could also recache this cache but the recount tool is already busy
        // so probably better to leave it to the first user
        $this->cache->forget('forums.index_tree');

        $this->info('Done' . PHP_EOL);
    }

    private function recountTopics()
    {
        $this->info('Recounting topic counters...');

        $topics = Topic::all();
        foreach ($topics as $topic) {
            $posts = Post::where('topic_id', '=', $topic->id)->orderBy('created_at', 'desc');
            $topic->num_posts = $posts->count();
            // We could also update the first_post_id easily with the above query
            // but if that column is wrong everything is wrong
            $topic->last_post_id = $posts->first()->id;

            $topic->save();
        }

        $this->info('Done' . PHP_EOL);
    }

    private function recountUsers()
    {
        $this->info('Recounting user counters...');

        $users = User::all();
        foreach ($users as $user) {
            $user->num_posts = Post::where('user_id', '=', $user->id)->count();
            $user->num_topics = Topic::where('user_id', '=', $user->id)->count();

            $user->save();
        }

        $this->info('Done' . PHP_EOL);
    }
}


text:
package org.apache.ambari.server.audit.request.creator;

import java.util.HashMap;
import java.util.Map;

import org.apache.ambari.server.api.services.Request;
import org.apache.ambari.server.api.services.Result;
import org.apache.ambari.server.api.services.ResultStatus;
import org.apache.ambari.server.api.util.TreeNode;
import org.apache.ambari.server.api.util.TreeNodeImpl;
import org.apache.ambari.server.audit.event.AuditEvent;
import org.apache.ambari.server.audit.event.request.ClusterNameChangeRequestAuditEvent;
import org.apache.ambari.server.audit.event.request.ConfigurationChangeRequestAuditEvent;
import org.apache.ambari.server.audit.request.eventcreator.ConfigurationChangeEventCreator;
import org.apache.ambari.server.controller.internal.ClusterResourceProvider;
import org.apache.ambari.server.controller.internal.ResourceImpl;
import org.apache.ambari.server.controller.internal.ServiceConfigVersionResourceProvider;
import org.apache.ambari.server.controller.spi.Resource;
import org.junit.Test;

import junit.framework.Assert;

public class ConfigurationChangeEventCreatorTest extends AuditEventCreatorTestBase {

  @Test
  public void clusterNameChangeTest() {
    ConfigurationChangeEventCreator creator = new ConfigurationChangeEventCreator();

    Map<String,Object> properties = new HashMap<>();
    properties.put(ClusterResourceProvider.CLUSTER_NAME_PROPERTY_ID, "newname");

    Map<Resource.Type,String> resource = new HashMap<>();
    resource.put(Resource.Type.Cluster, "oldname");

    Request request = AuditEventCreatorTestHelper.createRequest(Request.Type.PUT, Resource.Type.Cluster, properties, resource);
    Result result = AuditEventCreatorTestHelper.createResult(new ResultStatus(ResultStatus.STATUS.OK));

    AuditEvent event = AuditEventCreatorTestHelper.getEvent(creator, request, result);

    String actual = event.getAuditMessage();
    String expected = "User(" + userName + "), RemoteIp(1.2.3.4), Operation(Cluster name change), RequestType(PUT), url(http://example.com:8080/api/v1/test), ResultStatus(200 OK), Old name(oldname), New name(newname)";

    Assert.assertTrue("Class mismatch", event instanceof ClusterNameChangeRequestAuditEvent);
    Assert.assertEquals(expected, actual);
    Assert.assertTrue(actual.contains(userName));
  }

  @Test
  public void configurationChangeTest() {
    ConfigurationChangeEventCreator creator = new ConfigurationChangeEventCreator();

    TreeNode<Resource> resultTree = new TreeNodeImpl<>(null, null, null);
    Resource resource = new ResourceImpl(Resource.Type.Cluster);
    TreeNode<Resource> resourceNode = new TreeNodeImpl<>(resultTree, resource, "resources");
    Resource version = new ResourceImpl(Resource.Type.Cluster);
    version.setProperty(ServiceConfigVersionResourceProvider.SERVICE_CONFIG_VERSION_PROPERTY_ID, "1");
    version.setProperty(ServiceConfigVersionResourceProvider.SERVICE_CONFIG_VERSION_NOTE_PROPERTY_ID, "note");
    TreeNode<Resource> versionNode = new TreeNodeImpl<>(resourceNode, version, "");
    resourceNode.addChild(versionNode);
    resultTree.addChild(resourceNode);

    Request request = AuditEventCreatorTestHelper.createRequest(Request.Type.PUT, Resource.Type.Cluster, new HashMap<>(), null);
    Result result = AuditEventCreatorTestHelper.createResult(new ResultStatus(ResultStatus.STATUS.OK), resultTree);

    AuditEvent event = AuditEventCreatorTestHelper.getEvent(creator, request, result);

    String actual = event.getAuditMessage();
    String expected = "User(" + userName + "), RemoteIp(1.2.3.4), Operation(Configuration change), RequestType(PUT), url(http://example.com:8080/api/v1/test), ResultStatus(200 OK), VersionNumber(V1), VersionNote(note)";

    Assert.assertTrue("Class mismatch", event instanceof ConfigurationChangeRequestAuditEvent);
    Assert.assertEquals(expected, actual);
    Assert.assertTrue(actual.contains(userName));
  }
}


text:
package org.apereo.cas.config;

import org.apereo.cas.CentralAuthenticationService;
import org.apereo.cas.audit.AuditTrailConstants;
import org.apereo.cas.audit.AuditTrailRecordResolutionPlanConfigurer;
import org.apereo.cas.authentication.AuthenticationSystemSupport;
import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.rest.audit.RestResponseEntityAuditResourceResolver;
import org.apereo.cas.rest.factory.CasProtocolServiceTicketResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.ChainingRestHttpRequestCredentialFactory;
import org.apereo.cas.rest.factory.CompositeServiceTicketResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.DefaultTicketGrantingTicketResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.DefaultUserAuthenticationResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.RestHttpRequestCredentialFactory;
import org.apereo.cas.rest.factory.ServiceTicketResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.TicketGrantingTicketResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.UserAuthenticationResourceEntityResponseFactory;
import org.apereo.cas.rest.factory.UsernamePasswordRestHttpRequestCredentialFactory;
import org.apereo.cas.rest.plan.DefaultServiceTicketResourceEntityResponseFactoryPlan;
import org.apereo.cas.rest.plan.RestHttpRequestCredentialFactoryConfigurer;
import org.apereo.cas.rest.plan.ServiceTicketResourceEntityResponseFactoryConfigurer;
import org.apereo.cas.support.rest.resources.ServiceTicketResource;
import org.apereo.cas.support.rest.resources.TicketGrantingTicketResource;
import org.apereo.cas.support.rest.resources.TicketStatusResource;
import org.apereo.cas.support.rest.resources.UserAuthenticationResource;
import org.apereo.cas.throttle.AuthenticationThrottlingExecutionPlan;
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
import org.apereo.cas.web.support.ArgumentExtractor;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apereo.inspektr.audit.spi.support.DefaultAuditActionResolver;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * This is {@link CasRestConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Configuration("casRestConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Slf4j
public class CasRestConfiguration {

    @Autowired
    @Qualifier("centralAuthenticationService")
    private ObjectProvider<CentralAuthenticationService> centralAuthenticationService;

    @Autowired
    @Qualifier("defaultAuthenticationSystemSupport")
    private ObjectProvider<AuthenticationSystemSupport> authenticationSystemSupport;

    @Autowired
    @Qualifier("webApplicationServiceFactory")
    private ObjectProvider<ServiceFactory> webApplicationServiceFactory;

    @Autowired
    @Qualifier("defaultTicketRegistrySupport")
    private ObjectProvider<TicketRegistrySupport> ticketRegistrySupport;

    @Autowired
    @Qualifier("argumentExtractor")
    private ObjectProvider<ArgumentExtractor> argumentExtractor;

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    @Bean
    public TicketStatusResource ticketStatusResource() {
        return new TicketStatusResource(centralAuthenticationService.getObject());
    }

    @Bean
    @Autowired
    public ServiceTicketResource serviceTicketResource(
        @Qualifier("serviceTicketResourceEntityResponseFactory") final ServiceTicketResourceEntityResponseFactory serviceTicketResourceEntityResponseFactory,
        @Qualifier("restHttpRequestCredentialFactory") final RestHttpRequestCredentialFactory restHttpRequestCredentialFactory) {
        return new ServiceTicketResource(authenticationSystemSupport.getObject(),
            ticketRegistrySupport.getObject(),
            argumentExtractor.getObject(),
            serviceTicketResourceEntityResponseFactory,
            restHttpRequestCredentialFactory,
            applicationContext);
    }

    @Bean
    @ConditionalOnMissingBean(name = "serviceTicketResourceEntityResponseFactory")
    @Autowired
    public ServiceTicketResourceEntityResponseFactory serviceTicketResourceEntityResponseFactory(
        final List<ServiceTicketResourceEntityResponseFactoryConfigurer> configurers) {
        val plan = new DefaultServiceTicketResourceEntityResponseFactoryPlan();
        configurers.forEach(c -> c.configureEntityResponseFactory(plan));
        return new CompositeServiceTicketResourceEntityResponseFactory(plan.getFactories());
    }

    @Bean
    @ConditionalOnMissingBean(name = "ticketGrantingTicketResourceEntityResponseFactory")
    public TicketGrantingTicketResourceEntityResponseFactory ticketGrantingTicketResourceEntityResponseFactory() {
        return new DefaultTicketGrantingTicketResourceEntityResponseFactory();
    }

    @Bean
    @ConditionalOnMissingBean(name = "userAuthenticationResourceEntityResponseFactory")
    public UserAuthenticationResourceEntityResponseFactory userAuthenticationResourceEntityResponseFactory() {
        return new DefaultUserAuthenticationResourceEntityResponseFactory();
    }

    @Autowired
    @Bean
    public TicketGrantingTicketResource ticketGrantingTicketResource(
        @Qualifier("restHttpRequestCredentialFactory") final RestHttpRequestCredentialFactory restHttpRequestCredentialFactory) {
        return new TicketGrantingTicketResource(authenticationSystemSupport.getObject(),
            restHttpRequestCredentialFactory,
            centralAuthenticationService.getObject(),
            webApplicationServiceFactory.getObject(),
            ticketGrantingTicketResourceEntityResponseFactory(),
            applicationContext);
    }

    @Autowired
    @Bean
    public UserAuthenticationResource userAuthenticationRestController(
        @Qualifier("restHttpRequestCredentialFactory") final RestHttpRequestCredentialFactory restHttpRequestCredentialFactory) {
        return new UserAuthenticationResource(authenticationSystemSupport.getObject(),
            restHttpRequestCredentialFactory,
            webApplicationServiceFactory.getObject(),
            userAuthenticationResourceEntityResponseFactory(),
            applicationContext);
    }

    @Autowired
    @Bean
    public RestHttpRequestCredentialFactory restHttpRequestCredentialFactory(final List<RestHttpRequestCredentialFactoryConfigurer> configurers) {
        LOGGER.trace("building REST credential factory from [{}]", configurers);

        val factory = new ChainingRestHttpRequestCredentialFactory();
        AnnotationAwareOrderComparator.sortIfNecessary(configurers);

        configurers.forEach(c -> {
            LOGGER.trace("Configuring credential factory: [{}]", c);
            c.configureCredentialFactory(factory);
        });
        return factory;
    }

    @ConditionalOnMissingBean(name = "restHttpRequestCredentialFactoryConfigurer")
    @Bean
    public RestHttpRequestCredentialFactoryConfigurer restHttpRequestCredentialFactoryConfigurer() {
        return factory -> factory.registerCredentialFactory(new UsernamePasswordRestHttpRequestCredentialFactory());
    }

    @Bean
    public ServiceTicketResourceEntityResponseFactoryConfigurer restServiceTicketResourceEntityResponseFactoryConfigurer() {
        return plan -> plan.registerFactory(new CasProtocolServiceTicketResourceEntityResponseFactory(centralAuthenticationService.getObject()));
    }

    @Bean
    @ConditionalOnMissingBean(name = "restAuditTrailRecordResolutionPlanConfigurer")
    public AuditTrailRecordResolutionPlanConfigurer restAuditTrailRecordResolutionPlanConfigurer() {
        return plan -> {
            plan.registerAuditActionResolver("REST_API_TICKET_GRANTING_TICKET_ACTION_RESOLVER",
                new DefaultAuditActionResolver(AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED, AuditTrailConstants.AUDIT_ACTION_POSTFIX_FAILED));
            plan.registerAuditResourceResolver("REST_API_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER",
                new RestResponseEntityAuditResourceResolver(false));

            plan.registerAuditActionResolver("REST_API_SERVICE_TICKET_ACTION_RESOLVER",
                new DefaultAuditActionResolver(AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED, AuditTrailConstants.AUDIT_ACTION_POSTFIX_FAILED));
            plan.registerAuditResourceResolver("REST_API_SERVICE_TICKET_RESOURCE_RESOLVER",
                new RestResponseEntityAuditResourceResolver(true));
        };
    }

    /**
     * This is {@link CasRestThrottlingConfiguration}.
     *
     * @author Misagh Moayyed
     * @since 5.3.0
     */
    @Configuration("casRestThrottlingConfiguration")
    @ConditionalOnMissingBean(name = "restAuthenticationThrottle")
    @Slf4j
    public static class CasRestThrottlingConfiguration implements WebMvcConfigurer {

        @Autowired
        @Qualifier("authenticationThrottlingExecutionPlan")
        private ObjectProvider<AuthenticationThrottlingExecutionPlan> authenticationThrottlingExecutionPlan;

        @Override
        public void addInterceptors(final InterceptorRegistry registry) {
            val plan = authenticationThrottlingExecutionPlan.getObject();
            LOGGER.debug("Activating authentication throttling for REST endpoints...");
            plan.getAuthenticationThrottleInterceptors().forEach(handler -> registry.addInterceptor(handler).addPathPatterns("/v1/**"));
        }
    }
}


text:
package org.sosy_lab.java_smt.basicimpl;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess.TraversalType;

final class RecursiveFormulaVisitorImpl implements FormulaVisitor<TraversalProcess> {

  private final Set<Formula> seen = new HashSet<>();
  private final Deque<Formula> toVisit = new ArrayDeque<>();

  private final FormulaVisitor<TraversalProcess> delegate;

  RecursiveFormulaVisitorImpl(FormulaVisitor<TraversalProcess> pDelegate) {
    delegate = checkNotNull(pDelegate);
  }

  void addToQueue(Formula f) {
    if (seen.add(f)) {
      toVisit.push(f);
    }
  }

  boolean isQueueEmpty() {
    return toVisit.isEmpty();
  }

  private void addToQueueIfNecessary(TraversalProcess result, List<? extends Formula> pOperands) {
    if (result == TraversalProcess.CONTINUE) {
      for (Formula f : pOperands) {
        addToQueue(f);
      }
    } else if (result.getType() == TraversalType.CUSTOM_TYPE) {
      pOperands.stream().filter(result::contains).forEach(this::addToQueue);
    }
  }

  Formula pop() {
    return toVisit.pop();
  }

  @Override
  public TraversalProcess visitFreeVariable(Formula pF, String pName) {
    return delegate.visitFreeVariable(pF, pName);
  }

  @Override
  public TraversalProcess visitBoundVariable(Formula pF, int pDeBruijnIdx) {
    return delegate.visitBoundVariable(pF, pDeBruijnIdx);
  }

  @Override
  public TraversalProcess visitConstant(Formula pF, Object pValue) {
    return delegate.visitConstant(pF, pValue);
  }

  @Override
  public TraversalProcess visitFunction(
      Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
    TraversalProcess result = delegate.visitFunction(pF, pArgs, pFunctionDeclaration);
    addToQueueIfNecessary(result, pArgs);
    return result;
  }

  @Override
  public TraversalProcess visitQuantifier(
      BooleanFormula pF, Quantifier pQuantifier, List<Formula> boundVars, BooleanFormula pBody) {
    TraversalProcess result = delegate.visitQuantifier(pF, pQuantifier, boundVars, pBody);
    addToQueueIfNecessary(result, ImmutableList.of(pBody));
    return result;
  }
}


text:
import sys
import logging
import collections
import numpy as np

#scores
from sklearn.metrics import roc_auc_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score

log = logging.getLogger(__name__)

#Classification results namedtuple
classif_results_varnames = ['predictions', 'probabilities', 'cv_targets',
                            'best_parameters', 'cv_folds',
                            'features_importance', 'targets', 'labels']

class ClassificationResult(collections.namedtuple('Classification_Result',
                                                  classif_results_varnames)):
    """
    Namedtuple to store classification results.
    """
    pass

#Classification metrics namedtuple
classif_metrics_varnames = ['accuracy', 'sensitivity', 'specificity',
                            'precision', 'f1_score', 'area_under_curve']

class ClassificationMetrics(collections.namedtuple('Classification_Metrics',
                                                   classif_metrics_varnames)):
    """
    Namedtuple to store classifcation CV results metrics.
    """
    pass

# class Result(collections.namedtuple('Result', ['metrics', 'cl', 'prefs_thr',
#                                               'subjsf', 'presels', 'prefs',
#                                               'fs1', 'fs2',
#                                               'y_true', 'y_pred'])):
#    pass

def classification_metrics(targets, preds, probs=None, labels=None):
    """Calculate Accuracy, Sensitivity, Specificity, Precision, F1-Score
    and Area-under-ROC of given classification results.

    Parameters
    ----------
    targets:
    preds:
    probs:
    labels:

    Returns
    -------
    (acc, sens, spec, prec, f1, auc)
    """

#    if probs != None and len(probs) > 0:
#        fpr, tpr, thresholds = roc_curve(targets, probs[:, 1], 1)
#        roc_auc = roc_auc_score(fpr, tpr)
#    else:
#        fpr, tpr, thresholds = roc_curve(targets, preds, 1)
#        roc_auc = roc_auc_score(targets, preds)

    auc = 0
    if len(targets) > 1:
        auc = roc_auc_score(targets, preds)

    cm = confusion_matrix(targets, preds, labels)

    #accuracy
    acc = accuracy_score(targets, preds)

    #recall? True Positive Rate or Sensitivity or Recall
    sens = recall_score(targets, preds)

    #precision
    prec = precision_score(targets, preds)

    #f1-score
    f1 = f1_score(targets, preds, np.unique(targets), 1)

    tnr  = 0.0
    spec = 0.0
    #True Negative Rate or Specificity (tn / (tn+fp))
    if len(cm) == 2:
        if (cm[0, 0] + cm[0, 1]) != 0:
            spec = float(cm[0, 0])/(cm[0, 0] + cm[0, 1])

    return acc, sens, spec, prec, f1, auc

def enlist_cv_results_from_dict(cv_targets, cv_preds, cv_probs=None):
    """Put cv_targets, cv_preds and cv_probs in lists for performance measures.
    Also returns the set of target labels.

    Parameters
    ----------
    cv_targets: dict
    cv_preds: dict
    cv_probs: dict

    Returns
    -------
    targets, preds, probs, labels
    """
    targets = []
    preds = []
    labels = set()

    if cv_probs is None:
        probs = None
    elif len(cv_probs) == 0:
        probs = None
    else:
        probs = []

    #see if it is a LOO result set
    fold_len = 1
    for fold in cv_targets:
        if len(cv_targets[fold]) != fold_len:
            fold_len = len(cv_targets[fold])
            break

    #read results
    for fold in cv_targets:
        try:
            if fold_len == 1:
                trgt = cv_targets[fold][0]
                pred = cv_preds[fold][0]
            else:
                trgt = cv_targets[fold]
                pred = cv_preds[fold]

            targets.append(trgt)
            preds.append(pred)
        except:
            log.exception('Error accessing classification results.')
            raise

        if cv_probs is not None:
            try:
                if fold_len == 1:
                    prob = cv_probs[fold][0]
                else:
                    prob = cv_probs[fold]

                probs.append(prob)
            except:
                log.exception('Error accessing cv_probs.')
                raise

        for t in np.unique(trgt):
            labels.add(t)

    return targets, preds, probs, list(labels)

def enlist_cv_results(cv_targets, cv_preds, cv_probs=None):
    """Put cv_targets, cv_preds and cv_probs in lists for performance measures.
     Also returns the set of target labels.

    Parameters
    ----------
    cv_targets:
    cv_preds:
    cv_probs:

    Returns
    -------
    targets, preds, probs, labels
    """
    if isinstance(cv_targets, dict):
        return enlist_cv_results_from_dict(cv_targets, cv_preds, cv_probs)

    else:
        targets = []
        preds = []
        probs = []
        labels = set()

        try:
            for fold in np.arange(cv_targets.shape[0]):
                targets.append(cv_targets[fold, :])
                preds.append(cv_preds[fold, :])

                for t in np.unique(cv_targets[fold, :]):
                    labels.add(t)

                if cv_probs is not None:
                    probs.append(cv_probs[fold, :, :])
        except:
            log.exception("Error joining CV results.")
            raise

    if cv_probs is None:
        probs = None
    elif len(cv_probs) == 0:
        probs = None

    return targets, preds, probs, list(labels)

def get_cv_classification_metrics(cv_targets, cv_preds, cv_probs=None):
    """
    Returns a matrix of size [n_folds x 6],
    where 6 are: acc, sens, spec, prec, f1, roc_auc

    Parameters
    ----------
    cv_targets:
    cv_preds:
    cv_probs:

    Returns
    -------
    array_like: metrics
    """

    targets, preds, probs, labels = enlist_cv_results(cv_targets,
                                                      cv_preds,
                                                      cv_probs)

    metrics = np.zeros((len(targets), 6))

    for i in range(len(targets)):
        y_true = targets[i]
        y_pred = preds[i]

        y_prob = None
        if probs is not None:
            y_prob = probs[i]

        acc, sens, spec, prec, \
        f1, roc_auc = classification_metrics(y_true, y_pred, y_prob, labels)

        metrics[i, :] = np.array([acc, sens, spec, prec, f1, roc_auc])

    return metrics

def get_cv_significance(cv_targets, cv_preds):
    """
    Calculates the mean significance across the significance of each
    CV fold confusion matrix.

    Parameters
    ----------
    cv_targets:

    cv_preds:

    Returns
    -------
    p_value : float
        P-value, the probability of obtaining a distribution at least as
        extreme as the one that was actually observed, assuming that the null
        hypothesis is true.

    Notes
    -----
    I doubt this is a good method of measuring the significance of a
    classification.

    See a better test here:
    http://scikit-learn.org/stable/auto_examples/plot_permutation_test_for_classification.html

    """

    targets, preds, probs, labels = enlist_cv_results(cv_targets, cv_preds)

    signfs = []
    for i in range(len(targets)):
        y_true   = targets[i]
        y_pred   = preds  [i]
        conf_mat = confusion_matrix(y_true, y_pred, labels)
        signfs.append(get_confusion_matrix_fisher_significance(conf_mat)[1])

    return np.mean(signfs)

def get_confusion_matrix_fisher_significance(table, alternative='two-sided'):
    """
    Returns the value of fisher_exact test on table.

    Parameters
    ----------
    table : array_like of ints
        A 2x2 contingency table. Elements should be non-negative integers.

    alternative : {'two-sided', 'less', 'greater'}, optional
        Which alternative hypothesis to the null hypothesis the test uses.
        Default is 'two-sided'.

    Returns
    -------
    oddsratio : float
        This is prior odds ratio and not a posterior estimate.

    p_value : float
        P-value, the probability of obtaining a distribution at least as extreme
        as the one that was actually observed, assuming that the null hypothesis
        is true.
    """
    from scipy.stats import fisher_exact
    return fisher_exact(table, alternative)


text:
#ifndef __ARM_COMM_DEF_H
#define __ARM_COMM_DEF_H

//Keil MDK-ARM compiler?
#if defined(__CC_ARM)
   #pragma anon_unions
#endif

#define MHZ           *1000000l
#define KHZ           *1000l
#define HZ            *1l

#ifndef FALSE
#define FALSE (1 == 0)
#endif

#ifndef TRUE
#define TRUE  (1 == 1)
#endif

#ifndef NULL
#define NULL ((void*)0)
#endif

typedef double                Flo64;    // Double precision floating point
typedef double              * pFlo64;
typedef float                 Flo32;    // Single precision floating point
typedef float               * pFlo32;
typedef signed   long long    Int64S;   // Signed   64 bit quantity
typedef signed   long long  * pInt64S;
typedef unsigned long long    Int64U;   // Unsigned 64 bit quantity
typedef unsigned long long  * pInt64U;
typedef signed   int          Int32S;   // Signed   32 bit quantity
typedef signed   int        * pInt32S;
typedef unsigned int          Int32U;   // Unsigned 32 bit quantity
typedef unsigned int        * pInt32U;
typedef signed   short        Int16S;   // Signed   16 bit quantity
typedef signed   short      * pInt16S;
typedef unsigned short        Int16U;   // Unsigned 16 bit quantity
typedef unsigned short      * pInt16U;
typedef signed   char         Int8S;    // Signed    8 bit quantity
typedef signed   char       * pInt8S;
typedef unsigned char         Int8U;    // Unsigned  8 bit quantity
typedef unsigned char       * pInt8U;
typedef unsigned int          Boolean;  // Boolean
typedef unsigned int        * pBoolean;

#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define _2BL(a)   (Int8U)(a),(Int8U)(a>>8)
#define _2BB(a)   (Int8U)(a>>8),(Int8U)(a),
#define _3BL(a)   (Int8U)(a),(Int8U)(a>>8),(Int8U)(a>>16)
#define _3BB(a)   (Int8U)(a>>16),(Int8U)(a>>8),(Int8U)(a)
#define _4BL(a)   (Int8U)(a),(Int8U)(a>>8),(Int8U)(a>>16),(Int8U)(a>>24)
#define _4BB(a)   (Int8U)(a>>24),(Int8U)(a>>16),(Int8U)(a>>8),(Int8U)(a)

#endif // __ARM_COMM_DEF_H


text:
package com.home.rxtwitch.settings.suggestion;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

import com.home.rxtwitch.BasePresenter;
import com.home.rxtwitch.BaseView;

/**
 * Created by xmax on 7/13/16.
 */

public interface SuggestionContract {

    interface View extends BaseView<Presenter> {
        //Gallery
        void showImgChooserUI();
        Bitmap getImgBitmap(Uri uri);
        Bitmap getThumbnailBitmap(Bitmap bitmap);

        //thumbnail RecyclerView
        void showThumbnail(Bitmap bitmap);
        void hideThumbnail(int position);

        //EditText suggestion
        String getSuggestion();

        //EditText Email
        String getEmail();

        //feed back TextView
        void showFeedBackText();
        void hideFeedBackText();

        //thumbnail count
        int getThumbnailCount();
        void showThumbnailExistsTip();

        //activity finish
        void closeSuggestionUI();
        void closeSuggestionUIDelay();

        // uploading progress
        void buildUploadingProgress();
        void showUploadingProgress();
        void hideUploadingProgress();

        //enable submit layout
        void enableSubmitBtn();
        void disableSubmitBtn();
        void showUploadingSuccessTip();
        void showUploadingFailedTip();

        //cancel suggestion
        void buildCancelSuggestionDialog();
        void showCancelSuggestionDialog();
        void dismissCancelSuggestionDialog();
        boolean isCancelSuggestionDialogShowing();
    }

    interface Presenter extends BasePresenter {
        void result(int requestCode, int resultCode, Intent data);
        void addImg();
        void removeImg(int position);
        void uploadFile();
        void setupCancelSuggestion();
        void giveUpSuggestion();
        void goOnSuggestion();
        void onBack();

    }
}


text:
/**
 * Prophet 2.5
 * 版权所有:(C)2003-2010 吉贝克
 *
 *
 */
package com.gbicc.cfl.util;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

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

/**
 * @作者: 张彦龙
 * @作者: 2010-7-5
 * @描述: Http与Servlet工具类.
 */
public class ServletUtils {

	//-- Content Type 定义 --//
	public static final String TEXT_TYPE = "text/plain";
	public static final String JSON_TYPE = "application/json";
	public static final String XML_TYPE = "text/xml";
	public static final String HTML_TYPE = "text/html";
	public static final String JS_TYPE = "text/javascript";
	public static final String EXCEL_TYPE = "application/vnd.ms-excel";

	//-- Header 定义 --//
	public static final String AUTHENTICATION_HEADER = "Authorization";

	//-- 常用数值定义 --//
	public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;

	/**
	 * 设置客户端缓存过期时间 Header.
	 */
	public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
		//Http 1.0 header
		response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000);
		//Http 1.1 header
		response.setHeader("Cache-Control", "private, max-age=" + expiresSeconds);
	}

	/**
	 * 设置客户端无缓存Header.
	 */
	public static void setNoCacheHeader(HttpServletResponse response) {
		//Http 1.0 header
		response.setDateHeader("Expires", 0);
		response.addHeader("Pragma", "no-cache");
		//Http 1.1 header
		response.setHeader("Cache-Control", "no-cache");
	}

	/**
	 * 设置LastModified Header.
	 */
	public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
		response.setDateHeader("Last-Modified", lastModifiedDate);
	}

	/**
	 * 设置Etag Header.
	 */
	public static void setEtag(HttpServletResponse response, String etag) {
		response.setHeader("ETag", etag);
	}

	/**
	 * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
	 *
	 * 如果无修改, checkIfModify返回false ,设置304 not modify status.
	 *
	 * @param lastModified 内容的最后修改时间.
	 */
	public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
			long lastModified) {
		long ifModifiedSince = request.getDateHeader("If-Modified-Since");
		if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return false;
		}
		return true;
	}

	/**
	 * 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
	 *
	 * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
	 *
	 * @param etag 内容的ETag.
	 */
	public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
		String headerValue = request.getHeader("If-None-Match");
		if (headerValue != null) {
			boolean conditionSatisfied = false;
			if (!"*".equals(headerValue)) {
				StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

				while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
					String currentToken = commaTokenizer.nextToken();
					if (currentToken.trim().equals(etag)) {
						conditionSatisfied = true;
					}
				}
			} else {
				conditionSatisfied = true;
			}

			if (conditionSatisfied) {
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				response.setHeader("ETag", etag);
				return false;
			}
		}
		return true;
	}

	/**
	 * 设置让浏览器弹出下载对话框的Header.
	 *
	 * @param fileName 下载后的文件名.
	 */
	public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
		try {
			//中文文件名支持
			String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
		} catch (UnsupportedEncodingException e) {
		}
	}

	/**
	 * 取得带相同前缀的Request Parameters.
	 *
	 * 返回的结果Parameter名已去除前缀.
	 */
	@SuppressWarnings("unchecked")
	public static Map getParametersStartingWith(HttpServletRequest request, String prefix) {
		Enumeration paramNames = request.getParameterNames();
		Map params = new TreeMap();
		if (prefix == null) {
			prefix = "";
		}
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if (values == null || values.length == 0) {//NOSONAR
					// Do nothing, no values found at all.
				} else if (values.length > 1) {
					params.put(unprefixed, values);
				} else {
					params.put(unprefixed, values[0]);
				}
			}
		}
		return params;
	}

	/**
	 * 对Http Basic验证的 Header进行编码.
	 */
	public static String encodeHttpBasic(String userName, String password) {
		String encode = userName + ":" + password;
		return "Basic " + EncodeUtils.base64Encode(encode.getBytes());
	}
}


text:
class CreateMediumTagJoins < ActiveRecord::Migration[5.1]
  def change
    create_table :medium_tag_joins do |t|
      t.references :medium, foreign_key: true
      t.references :tag, foreign_key: true

      t.timestamps
    end
  end
end


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

namespace Com.Aspose.Slides.Model {
  public class SlideComment {
    public string Author { get; set; }

    public string Text { get; set; }

    public string CreatedTime { get; set; }

    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class SlideComment {\n");
      sb.Append("  Author: ").Append(Author).Append("\n");
      sb.Append("  Text: ").Append(Text).Append("\n");
      sb.Append("  CreatedTime: ").Append(CreatedTime).Append("\n");
      sb.Append("}\n");
      return sb.ToString();
    }
  }
  }


text:
package com.amazonaws.services.iotfleetwise.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum VehicleState {

    CREATED("CREATED"),
    READY("READY"),
    HEALTHY("HEALTHY"),
    SUSPENDED("SUSPENDED"),
    DELETING("DELETING");

    private String value;

    private VehicleState(String value) {
        this.value = value;
    }

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

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return VehicleState corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static VehicleState fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (VehicleState enumEntry : VehicleState.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package de.hska.ld.oidc.persistence.repository;

import de.hska.ld.content.persistence.domain.Document;
import de.hska.ld.oidc.persistence.domain.DocumentSSSInfo;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface DocumentSSSInfoRepository extends CrudRepository<DocumentSSSInfo, Long> {
    DocumentSSSInfo findByDocument(Document document);

    DocumentSSSInfo findByEpisodeId(String episodeId);

    @Query("FROM DocumentSSSInfo dsi WHERE dsi.document.id = :documentId")
    DocumentSSSInfo findByDocumentId(@Param("documentId") Long documentId);
}


text:
package tests

import (
	"errors"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/avast/retry-go"
	"github.com/tebeka/selenium"

	"github.com/skydive-project/skydive/api/client"
	"github.com/skydive-project/skydive/flow"
	shttp "github.com/skydive-project/skydive/graffiti/http"
	g "github.com/skydive-project/skydive/gremlin"
)

type seleniumHelper struct {
	addr             string
	port             int
	webdriver        selenium.WebDriver
	gh               *client.GremlinQueryHelper
	fakeMousePointer bool
	activeTabID      string
	t                *testing.T
	currVideoName    string
	authOptions      *shttp.AuthenticationOpts
}

func (s *seleniumHelper) connect() error {
	return s.webdriver.Get(fmt.Sprintf("http://%s:%d", s.addr, s.port))
}

func (s *seleniumHelper) login() error {
	if err := s.fillTextBoxByID("username", s.authOptions.Username); err != nil {
		return err
	}

	if err := s.fillTextBoxByID("password", s.authOptions.Password); err != nil {
		return err
	}

	signin, err := s.findElement(selenium.ByID, "signin")
	if err != nil {
		return err
	}

	return signin.Click()
}

func (s *seleniumHelper) findElement(selection, xpath string) (el selenium.WebElement, err error) {
	retry.Do(func() error {
		el, err = s.webdriver.FindElement(selection, xpath)
		if err != nil || el == nil {
			return fmt.Errorf("Failed to find element for %s (error: %+v)", xpath, err)
		}
		return nil
	}, retry.Attempts(10), retry.Delay(time.Second), retry.DelayType(retry.FixedDelay))

	return
}

func (s *seleniumHelper) screenshot(path string) error {
	content, err := s.webdriver.Screenshot()
	if err != nil {
		return err
	}

	f, err := os.Create(path)
	if err != nil {
		return err
	}

	if _, err = f.Write(content); err != nil {
		return err
	}

	return f.Close()
}

func (s *seleniumHelper) zoomFit() error {
	fit, err := s.findElement(selenium.ByID, "zoom-fit")
	if err != nil {
		return err
	}
	return fit.Click()
}

func (s *seleniumHelper) zoomOut() error {
	for i := 0; i != 5; i++ {
		zo, err := s.findElement(selenium.ByID, "zoom-out")
		if err != nil {
			return err
		}
		if err = zo.Click(); err != nil {
			return err
		}
	}
	return nil
}

func (s *seleniumHelper) clickOnNode(gremlin g.QueryString) error {
	node, err := s.gh.GetNode(gremlin)
	if err != nil {
		return err
	}

	return retry.Do(func() error {
		el, err := s.webdriver.FindElement(selenium.ByXPATH, ".//*[@id='node-img-"+string(node.ID)+"']")
		if err != nil {
			return err
		}
		if err := s.clickOn(el); err != nil {
			return fmt.Errorf("Failed to click on source node: %s", err.Error())
		}
		return nil
	}, retry.Attempts(20), retry.Delay(200*time.Millisecond), retry.DelayType(retry.FixedDelay))
}

func (s *seleniumHelper) expand() error {
	expand, err := s.findElement(selenium.ByID, "expand")
	if err != nil {
		return err
	}

	return s.clickOn(expand)
}

func (s *seleniumHelper) expandPanel(id string) error {
	panel, err := s.findElement(selenium.ByID, id)
	if err != nil {
		return err
	}

	return s.clickOn(panel)
}

func (s *seleniumHelper) expandGroup(gremlin g.QueryString) error {
	node, err := s.gh.GetNode(gremlin)
	if err != nil {
		return err
	}
	if err = s.webdriver.KeyDown(selenium.AltKey); err != nil {
		return err
	}

	err = retry.Do(func() error {
		el, err := s.findElement(selenium.ByXPATH, ".//*[@id='node-img-"+string(node.ID)+"']")
		if err != nil {
			return err
		}

		if err = s.clickOn(el); err != nil {
			return err
		}

		el, err = s.findElement(selenium.ByXPATH, ".//*[@id='node-"+string(node.ID)+"']")
		if err != nil {
			return err
		}

		if collapsed, err := el.GetAttribute("collapsed"); err != nil || collapsed != "false" {
			return errors.New("group still collapsed")
		}

		return nil
	}, retry.Attempts(40), retry.Delay(5*time.Millisecond), retry.DelayType(retry.FixedDelay))

	if err != nil {
		return err
	}

	return s.webdriver.KeyUp(selenium.AltKey)
}

func (s *seleniumHelper) getFlowRow(gremlin g.QueryString) (selenium.WebElement, error) {
	var flows []*flow.Flow
	var err error

	retryFn := func() error {
		flows, err = s.gh.GetFlows(gremlin)
		if err != nil {
			return err
		}

		if len(flows) == 0 {
			return errors.New("No flow found")
		}

		return nil
	}
	if err = retry.Do(retryFn, retry.Attempts(20), retry.Delay(200*time.Millisecond)); err != nil {
		time.Sleep(5 * time.Minute)

		return nil, err
	}

	// try to move to one of the flow
	var el selenium.WebElement
	retryFn = func() error {
		for _, f := range flows {
			el, err = s.webdriver.FindElement(selenium.ByXPATH, fmt.Sprintf(".//*[@id='flow-%s']", f.UUID))
			if el != nil {
				return nil
			}
		}
		return errors.New("Not found")
	}
	if err := retry.Do(retryFn); err != nil {
		return nil, err
	}

	return el, nil
}

func (s *seleniumHelper) highlightFlow(gremlin g.QueryString) error {
	el, err := s.getFlowRow(gremlin)
	if err != nil {
		return err
	}

	return s.moveOn(el)
}

func (s *seleniumHelper) scrollDownRightPanel() error {
	s.webdriver.ExecuteScript("$('#info-panel').animate({scrollTop: $('#info-panel').get(0).scrollHeight}, 500);", nil)
	return nil
}

func (s *seleniumHelper) clickOnFlow(gremlin g.QueryString) error {
	el, err := s.getFlowRow(gremlin)
	if err != nil {
		return err
	}

	return s.clickOn(el)
}

func (s *seleniumHelper) showNodeFlowTable(gremlin g.QueryString) error {
	if err := s.clickOnNode(gremlin); err != nil {
		return err
	}

	s.scrollDownRightPanel()
	s.expandPanel("flow-table")
	s.scrollDownRightPanel()

	return nil
}

func (s *seleniumHelper) selectNode(id string, gremlin g.QueryString) error {
	if err := s.clickOnByID(id); err != nil {
		return err
	}
	if err := s.clickOnNode(gremlin); err != nil {
		return err
	}

	return nil
}

func (s *seleniumHelper) fillTextBoxByID(id string, text string) error {
	box, err := s.findElement(selenium.ByXPATH, fmt.Sprintf(".//*[@id='%s']", id))
	if err != nil || box == nil {
		return fmt.Errorf("Not found text box: %v", err)
	}

	if err = box.Clear(); err != nil {
		return err
	}

	return box.SendKeys(text)
}

func (s *seleniumHelper) activateTab(id string) error {
	if id == s.activeTabID {
		return nil
	}

	if err := s.clickOnByID(id); err != nil {
		return err
	}
	s.activeTabID = id

	return nil
}

func (s *seleniumHelper) startShortestPathCapture(g1, g2 g.QueryString, bpf string) error {
	if err := s.activateTab("Captures"); err != nil {
		return err
	}

	if err := s.clickOnByID("create-capture"); err != nil {
		return err
	}

	if err := s.selectNode("node-selector-1", g1); err != nil {
		return err
	}

	if err := s.selectNode("node-selector-2", g2); err != nil {
		return err
	}

	if bpf != "" {
		if err := s.clickOnByID("capture-bpf"); err != nil {
			return err
		}
		if err := s.fillTextBoxByID("capture-bpf", bpf); err != nil {
			return err
		}
	}

	if err := s.clickOnByID("start-capture"); err != nil {
		return err
	}

	return s.waitNotificationClose()
}

func (s *seleniumHelper) startGremlinCapture(gremlin g.QueryString) error {
	if err := s.activateTab("Captures"); err != nil {
		return err
	}

	if err := s.clickOnByID("create-capture"); err != nil {
		return err
	}

	if err := s.clickOnByID("by-gremlin"); err != nil {
		return err
	}

	if err := s.fillTextBoxByID("capture-query", gremlin.String()); err != nil {
		return err
	}

	if err := s.clickOnByID("start-capture"); err != nil {
		return err
	}

	time.Sleep(1 * time.Second)

	if err := s.waitNotificationClose(); err != nil {
		return err
	}

	//check capture created with the given query
	captures, err := s.webdriver.FindElements(selenium.ByClassName, "query")
	if err != nil {
		return err
	}
	var foundCapture bool
	for _, capture := range captures {
		if txt, _ := capture.Text(); txt == gremlin.String() {
			foundCapture = true
			break
		}

	}
	if !foundCapture {
		return fmt.Errorf("Capture not found in the list")
	}
	return nil
}

func (s *seleniumHelper) waitNotificationClose() error {
	var notification selenium.WebElement
	err := retry.Do(func() error {
		var err error
		notification, err = s.findElement(selenium.ByXPATH, ".//*[@id='notification']")
		return err
	}, retry.Attempts(50), retry.Delay(time.Millisecond*100), retry.DelayType(retry.FixedDelay))

	// notification not found thus no need to wait
	if err != nil {
		return nil
	}

	err = retry.Do(func() error {
		el, _ := notification.FindElement(selenium.ByClassName, "close")
		if el != nil {
			return errors.New("notification still there")
		}
		return nil
	}, retry.Attempts(10), retry.Delay(time.Second), retry.DelayType(retry.FixedDelay))
	if err != nil {
		return err
	}

	return nil
}

func (s *seleniumHelper) injectPacket(g1, g2 g.QueryString, count int) error {
	if err := s.activateTab("Generator"); err != nil {
		return err
	}

	if err := s.selectNode("inject-src", g1); err != nil {
		return err
	}

	if err := s.selectNode("inject-dst", g2); err != nil {
		return err
	}

	if count != 0 {
		if err := s.clickOnByID("inject-count"); err != nil {
			return err
		}

		if err := s.fillTextBoxByID("inject-count", fmt.Sprintf("%d", count)); err != nil {
			return err
		}
	}

	return s.clickOnByID("inject")
}

func (s *seleniumHelper) flowQuery(gremlin g.QueryString) error {
	if err := s.activateTab("Flows"); err != nil {
		return err
	}

	flowQuery, err := s.findElement(selenium.ByXPATH, ".//*[@id='flow-table-query']")
	if err != nil {
		return err
	}
	if err := flowQuery.Clear(); err != nil {
		return err
	}

	return flowQuery.SendKeys(gremlin.String())
}

func (s *seleniumHelper) enableFakeMousePointer() error {
	script := `
		var css = document.createElement("link");
		css.type = 'text/css';
		css.rel = 'stylesheet';
		css.onload = function() {
			var js = document.createElement("script");
			js.type = "application/javascript";
			js.onload = function() {
				fakeMousePointer = new FakeMousePointer();
			};
			js.src = "/ui/js/fake-mouse.js";
			document.body.appendChild(js);
		}
		css.href = "/ui/css/fake-mouse.css";
		document.body.appendChild(css);
	`
	if _, err := s.webdriver.ExecuteScript(script, nil); err != nil {
		return err
	}
	s.fakeMousePointer = true

	return nil
}

func (s *seleniumHelper) fakeMousePointerMoveTo(x int, y int) error {
	script := fmt.Sprintf("fakeMousePointer.moveTo(%d, %d, arguments[0]);", x, y)
	if _, err := s.webdriver.ExecuteScriptAsync(script, nil); err != nil {
		return err
	}
	return nil
}

func (s *seleniumHelper) fakeMousePointerClickOn(el selenium.WebElement) error {
	if _, err := s.webdriver.ExecuteScriptAsync("fakeMousePointer.clickOn(arguments[0], arguments[1]);", []interface{}{el}); err != nil {
		return err
	}
	return nil
}

func (s *seleniumHelper) fakeMousePointerMoveOn(el selenium.WebElement) error {
	if _, err := s.webdriver.ExecuteScriptAsync("fakeMousePointer.moveOn(arguments[0], arguments[1]);", []interface{}{el}); err != nil {
		return err
	}
	return nil
}

func (s *seleniumHelper) fakeMousePointerClickTo(x int, y int) error {
	script := fmt.Sprintf("fakeMousePointer.clickTo(%d, %d, arguments[0]);", x, y)
	if _, err := s.webdriver.ExecuteScriptAsync(script, nil); err != nil {
		return err
	}
	return nil
}

func (s *seleniumHelper) clickOn(el selenium.WebElement) error {
	if s.fakeMousePointer {
		if err := s.fakeMousePointerClickOn(el); err != nil {
			return err
		}
	}

	return el.Click()
}

func (s *seleniumHelper) moveOn(el selenium.WebElement) error {
	if s.fakeMousePointer {
		if err := s.fakeMousePointerMoveOn(el); err != nil {
			return err
		}
	}

	return el.MoveTo(0, 0)
}

func (s *seleniumHelper) clickOnByID(id string) error {
	el, err := s.findElement(selenium.ByXPATH, fmt.Sprintf(".//*[@id='%s']", id))
	if err != nil || el == nil {
		return fmt.Errorf("%s: %s", id, err)
	}

	return s.clickOn(el)
}

func (s *seleniumHelper) moveOnByID(id string) error {
	el, err := s.findElement(selenium.ByXPATH, fmt.Sprintf(".//*[@id='%s']", id))
	if err != nil || el == nil {
		return fmt.Errorf("%s: %s", id, err)
	}

	return s.moveOn(el)
}

func (s *seleniumHelper) startVideoRecord(name string) {
	cmds := []Cmd{
		{"docker exec grid start-video", true},
	}
	execCmds(s.t, cmds...)
	s.currVideoName = name
}

func (s *seleniumHelper) stopVideoRecord() {
	cmds := []Cmd{
		{"docker exec grid stop-video", true},
		{"docker cp grid:/videos/. .", true},
		{fmt.Sprintf("mv cdd.mp4 %s.mp4", s.currVideoName), true},
	}
	execCmds(s.t, cmds...)

	s.currVideoName = ""
}

func (s *seleniumHelper) quit() {
	s.webdriver.Quit()

	tearDownCmds := []Cmd{
		{"docker stop grid", true},
		{"docker rm -f grid", true},
	}
	execCmds(s.t, tearDownCmds...)
}

func newSeleniumHelper(t *testing.T, analyzerAddr string, analyzerPort int, authOptions *shttp.AuthenticationOpts) (*seleniumHelper, error) {
	setupCmds := []Cmd{
		{"docker pull skydive/cdd-docker-selenium", true},
		{"docker run -d --name=grid -p 4444:24444 -p 5900:25900 -e --shm-size=1g -p 6080:26080 -e SCREEN_WIDTH=1600 -e SCREEN_HEIGHT=1000 -e NOVNC=true -e VIDEO_FILE_NAME=cdd skydive/cdd-docker-selenium", true},
		{"docker exec grid wait_all_done 60s", true},
	}
	execCmds(t, setupCmds...)

	var webdriver selenium.WebDriver
	err := retry.Do(func() error {
		var err error

		caps := selenium.Capabilities{"browserName": "chrome"}
		webdriver, err = selenium.NewRemote(caps, "http://localhost:4444/wd/hub")
		if err != nil {
			return err
		}
		webdriver.MaximizeWindow("")
		webdriver.SetAsyncScriptTimeout(5 * time.Second)

		return nil
	}, retry.Attempts(60), retry.Delay(time.Second), retry.DelayType(retry.FixedDelay))

	if err != nil {
		return nil, err
	}

	os.Setenv("SKYDIVE_ANALYZERS", fmt.Sprintf("%s:%d", analyzerAddr, analyzerPort))

	gh, err := client.NewGremlinQueryHelperFromConfig(authOptions)
	if err != nil {
		return nil, err
	}

	sh := &seleniumHelper{
		addr:        analyzerAddr,
		port:        analyzerPort,
		webdriver:   webdriver,
		gh:          gh,
		activeTabID: "Captures",
		t:           t,
		authOptions: authOptions,
	}

	return sh, nil
}


text:
/**
 * Parse multipart form data sent via POST requests.
 */
export default function parsePostForm(requestBody: ArrayBuffer) {
  type ParsedFields = Record<string, string[] | string>;
  if (requestBody.constructor.name !== 'ArrayBuffer') {
    return requestBody;
  }
  const lines = new TextDecoder('utf-8').decode(requestBody).split('\n');
  const fields: ParsedFields = {};
  let key = '';
  let value: string[] = [];

  function addField(key: string, value: string) {
    if (key in fields) {
      if (Array.isArray(fields[key])) {
        (fields[key] as string[]).push(value);
      } else {
        fields[key] = [fields[key] as string, value];
      }
    } else {
      fields[key] = value;
    }
  }

  lines.forEach(line => {
    const nameMatch = line.match(/Content-Disposition: form-data; name="(.*)"/);
    if (nameMatch) {
      if (key) {
        addField(key, value.join('\n'));
      }
      key = nameMatch[1];
      value = [];
    } else if (!/----.*FormBoundary/.test(line)) {
      value.push(line);
    }
  });
  if (key && value) {
    addField(key, value.join('\n'));
  }
  return fields;
}


text:
class NotificationQueue {
  std::deque<std::function<void()>> q_{};
  bool done_{false};
  std::mutex mutex_{};
  std::condition_variable ready_{};

public:
  void done();
  bool pop(std::function<void()> &x);
  bool try_pop(std::function<void()> &x);

  template <typename F>
  void push(F &&f) {
    {
      std::unique_lock<std::mutex> lock{mutex_};
      q_.emplace_back(std::forward<F>(f));
    }
    ready_.notify_one();
  }

  template <typename F>
  bool try_push(F &&f) {
    {
      std::unique_lock<std::mutex> lock{mutex_, std::try_to_lock};
      if (!lock) {
        return false;
      }
      q_.emplace_back(std::forward<F>(f));
    }
    ready_.notify_one();
    return true;
  }
};


text:
@interface EMJoinGroupViewController ()<EMAvatarNameCellDelegate>

@property (nonatomic, strong) NSMutableArray *joinedIdArray;
@property (nonatomic, strong) NSMutableArray *applyedIdArray;

@property (nonatomic, strong) NSString *cursor;

@end

@implementation EMJoinGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.joinedIdArray = [[NSMutableArray alloc] init];
    self.applyedIdArray = [[NSMutableArray alloc] init];

    [self _setupSubviews];
    [self _fetchPublicGroupsWithIsHeader:YES isShowHUD:YES];
}

#pragma mark - Subviews

- (void)_setupSubviews
{
    [self addPopBackLeftItem];
    self.title = @"加入群组";

    self.showRefreshHeader = YES;
    self.searchBar.textField.placeholder = @"搜索群组ID";
    self.tableView.rowHeight = 60;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (tableView == self.tableView) {
        return [self.dataArray count];
    } else {
        return [self.searchResults count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EMAvatarNameCell";
    EMAvatarNameCell *cell = (EMAvatarNameCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    if (cell == nil) {
        cell = [[EMAvatarNameCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.delegate = self;

        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 35)];
        rightButton.clipsToBounds = YES;
        rightButton.backgroundColor = kColor_Blue;
        rightButton.titleLabel.font = [UIFont systemFontOfSize:16];
        rightButton.layer.cornerRadius = 5;
        [rightButton setTitle:@"加入" forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [rightButton setTitle:@"已申请" forState:UIControlStateDisabled];
        [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        cell.accessoryButton = rightButton;
    }

    EMGroup *group = nil;
    if (tableView == self.tableView) {
        group = [self.dataArray objectAtIndex:indexPath.row];
    } else {
        group = [self.searchResults objectAtIndex:indexPath.row];
    }

    cell.avatarView.image = [UIImage imageNamed:@"group_avatar"];
    if ([group.subject length]) {
        cell.nameLabel.text = group.subject;
    } else {
        cell.nameLabel.text = group.groupId;
    }
    cell.detailLabel.text = group.groupId;
    cell.indexPath = indexPath;

    if ([self.applyedIdArray containsObject:group.groupId]) {
        cell.accessoryButton.enabled = NO;
        [cell.accessoryButton setTitle:@"已申请" forState:UIControlStateDisabled];
        cell.accessoryButton.backgroundColor = kColor_Gray;
    } else if ([self.joinedIdArray containsObject:group.groupId]) {
        cell.accessoryButton.enabled = NO;
        [cell.accessoryButton setTitle:@"已加入" forState:UIControlStateDisabled];
        cell.accessoryButton.backgroundColor = kColor_Gray;
    } else {
        cell.accessoryButton.enabled = YES;
        cell.accessoryButton.backgroundColor = kColor_Blue;
    }

    return cell;
}

#pragma mark - EMAvatarNameCellDelegate

- (void)_joinGroup:(EMGroup *)aGroup
   accessoryButton:(UIButton *)aButton
{
    __weak typeof(self) weakself = self;
    if (aGroup.setting.style == EMGroupStylePublicOpenJoin) {
        [self showHudInView:self.view hint:@"加入群组..."];
        [[EMClient sharedClient].groupManager joinPublicGroup:aGroup.groupId completion:^(EMGroup *aGroup1, EMError *aError) {
            [weakself hideHud];
            if (aError) {
                [EMAlertController showErrorAlert:@"加入群组失败"];
            } else {
                [weakself.joinedIdArray addObject:aGroup1.groupId];
                aButton.enabled = NO;
                [aButton setTitle:@"已加入" forState:UIControlStateDisabled];
                aButton.backgroundColor = kColor_Gray;
            }
        }];
    } else if (aGroup.setting.style == EMGroupStylePublicJoinNeedApproval) {
        [self showHudInView:self.view hint:@"发送入群申请..."];
        [[EMClient sharedClient].groupManager requestToJoinPublicGroup:aGroup.groupId message:nil completion:^(EMGroup *aGroup1, EMError *aError) {
            [weakself hideHud];
            if (aError) {
                [EMAlertController showErrorAlert:@"发送申请失败"];
            } else {
                [weakself.applyedIdArray addObject:aGroup1.groupId];
                aButton.enabled = NO;
                [aButton setTitle:@"已申请" forState:UIControlStateDisabled];
                aButton.backgroundColor = kColor_Gray;
            }
        }];
    }
}

- (void)cellAccessoryButtonAction:(EMAvatarNameCell *)aCell
{
    __weak typeof(self) weakself = self;
    EMGroup *group = nil;
    if (!self.isSearching) {
        group = [self.dataArray objectAtIndex:aCell.indexPath.row];
    } else {
        group = [self.searchResults objectAtIndex:aCell.indexPath.row];
    }

    [self showHudInView:self.view hint:@"获取群组信息..."];
    [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:group.groupId completion:^(EMGroup *aGroup, EMError *aError) {
        [weakself hideHud];
        if (aError) {
            [EMAlertController showErrorAlert:aError.errorDescription];
        } else {
            [weakself _joinGroup:aGroup accessoryButton:aCell.accessoryButton];
        }
    }];
}

#pragma mark - EMSearchBarDelegate

- (void)searchBarSearchButtonClicked:(NSString *)aString
{
    [self.view endEditing:YES];
    [self _searchGroupWithId:aString];
}

- (void)searchTextDidChangeWithString:(NSString *)aString
{
    __weak typeof(self) weakself = self;
    [[EMRealtimeSearch shared] realtimeSearchWithSource:self.dataArray searchText:aString collationStringSelector:@selector(groupId) resultBlock:^(NSArray *results) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.searchResults removeAllObjects];
            [weakself.searchResults addObjectsFromArray:results];
            [weakself.searchResultTableView reloadData];
        });
    }];
}

#pragma mark - data

- (void)_fetchPublicGroupsWithIsHeader:(BOOL)aIsHeader
                         isShowHUD:(BOOL)aIsShowHUD
{
    if (aIsShowHUD) {
        [self showHudInView:self.view hint:@"获取公开群组..."];
    }

    __weak typeof(self) weakself = self;
    [[EMClient sharedClient].groupManager getPublicGroupsFromServerWithCursor:self.cursor pageSize:50 completion:^(EMCursorResult *aResult, EMError *aError) {
        [weakself hideHud];

        if (aError) {
            [EMAlertController showErrorAlert:aError.errorDescription];
        } else {
            if (aIsHeader) {
                [weakself.dataArray removeAllObjects];
            }

            weakself.cursor = aResult.cursor;
            [weakself.dataArray addObjectsFromArray:aResult.list];

            if ([aResult.list count] == 0 || [aResult.cursor length] == 0) {
                weakself.showRefreshFooter = NO;
            } else {
                weakself.showRefreshFooter = YES;
            }

            [weakself.tableView reloadData];
        }

        [weakself tableViewDidFinishTriggerHeader:aIsHeader reload:NO];
    }];
}

- (void)tableViewDidTriggerHeaderRefresh
{
    self.cursor = nil;
    [self _fetchPublicGroupsWithIsHeader:YES isShowHUD:NO];
}

- (void)tableViewDidTriggerFooterRefresh
{
    [self _fetchPublicGroupsWithIsHeader:NO isShowHUD:NO];
}

#pragma mark - Action

- (BOOL)_isJoined:(EMGroup *)aGroup
{
    if (aGroup) {
        NSArray *groupList = [[EMClient sharedClient].groupManager getJoinedGroups];
        for (EMGroup *tmpGroup in groupList) {
            if (tmpGroup.isPublic == aGroup.isPublic && [aGroup.groupId isEqualToString:tmpGroup.groupId]) {
                return YES;
            }
        }
    }

    return NO;
}

- (void)_searchGroupWithId:(NSString *)aId
{
    __weak typeof(self) weakself = self;
    [self showHudInView:self.view hint:@"搜索群组..."];
    [[EMClient sharedClient].groupManager searchPublicGroupWithId:aId completion:^(EMGroup *aGroup, EMError *aError) {
        [weakself hideHud];
        if (!aError) {
            [weakself.searchResults removeAllObjects];
            [weakself.searchResults addObject:aGroup];
            [weakself.searchResultTableView reloadData];
        } else {
            [EMAlertController showErrorAlert:@"未搜索到群组"];
        }
    }];
}

@end