text:
//---------------------------------------------------------------------------
//
// <copyright file="GeneralTransformGroup.cs" company="Microsoft">
//    Copyright (C) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------

using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;

namespace System.Windows.Media
{

    sealed partial class GeneralTransformGroup : GeneralTransform
    {
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region Public Methods

        /// <summary>
        ///     Shadows inherited Clone() with a strongly typed
        ///     version for convenience.
        /// </summary>
        public new GeneralTransformGroup Clone()
        {
            return (GeneralTransformGroup)base.Clone();
        }

        /// <summary>
        ///     Shadows inherited CloneCurrentValue() with a strongly typed
        ///     version for convenience.
        /// </summary>
        public new GeneralTransformGroup CloneCurrentValue()
        {
            return (GeneralTransformGroup)base.CloneCurrentValue();
        }

        #endregion Public Methods

        //------------------------------------------------------
        //
        //  Public Properties
        //
        //------------------------------------------------------

        #region Public Properties

        /// <summary>
        ///     Children - GeneralTransformCollection.  Default value is new FreezableDefaultValueFactory(GeneralTransformCollection.Empty).
        /// </summary>
        public GeneralTransformCollection Children
        {
            get
            {
                return (GeneralTransformCollection) GetValue(ChildrenProperty);
            }
            set
            {
                SetValueInternal(ChildrenProperty, value);
            }
        }

        #endregion Public Properties

        //------------------------------------------------------
        //
        //  Protected Methods
        //
        //------------------------------------------------------

        #region Protected Methods

        /// <summary>
        /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
        /// </summary>
        /// <returns>The new Freezable.</returns>
        protected override Freezable CreateInstanceCore()
        {
            return new GeneralTransformGroup();
        }

        #endregion ProtectedMethods

        //------------------------------------------------------
        //
        //  Internal Methods
        //
        //------------------------------------------------------

        #region Internal Methods

        #endregion Internal Methods

        //------------------------------------------------------
        //
        //  Internal Properties
        //
        //------------------------------------------------------

        #region Internal Properties

        #endregion Internal Properties

        //------------------------------------------------------
        //
        //  Dependency Properties
        //
        //------------------------------------------------------

        #region Dependency Properties

        /// <summary>
        ///     The DependencyProperty for the GeneralTransformGroup.Children property.
        /// </summary>
        public static readonly DependencyProperty ChildrenProperty;

        #endregion Dependency Properties

        //------------------------------------------------------
        //
        //  Internal Fields
        //
        //------------------------------------------------------

        #region Internal Fields

        internal static GeneralTransformCollection s_Children = GeneralTransformCollection.Empty;

        #endregion Internal Fields

        #region Constructors

        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        static GeneralTransformGroup()
        {
            // We check our static default fields which are of type Freezable
            // to make sure that they are not mutable, otherwise we will throw
            // if these get touched by more than one thread in the lifetime
            // of your app.  (Windows OS Bug #947272)
            //
            Debug.Assert(s_Children == null || s_Children.IsFrozen,
                "Detected context bound default value GeneralTransformGroup.s_Children (See OS Bug #947272).");

            // Initializations
            Type typeofThis = typeof(GeneralTransformGroup);
            ChildrenProperty =
                  RegisterProperty("Children",
                                   typeof(GeneralTransformCollection),
                                   typeofThis,
                                   new FreezableDefaultValueFactory(GeneralTransformCollection.Empty),
                                   null,
                                   null,
                                   /* isIndependentlyAnimated  = */ false,
                                   /* coerceValueCallback */ null);
        }

        #endregion Constructors

    }
}


text:
package polka.lfds;

/**
 * Superclass for all LFD exceptions
 */
public class LFDException extends Exception {
	public LFDException(String reason) {
		super(reason);
	}
	public LFDException() { super(); };
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var inputOutputParameter = require('./implementation/InputOutputParameter');

var assign = require('lodash/object/assign');

module.exports = function(group, element, bpmnFactory, options) {

  group.entries = group.entries.concat(inputOutputParameter(element, bpmnFactory, assign({}, options)));

};


text:
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------

using System.Globalization;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Microsoft.Identity.Core.Helpers;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal;
using Microsoft.Identity.Core.Http;
using Microsoft.Identity.Json.Linq;

namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{

    /// <summary>
    /// The exception type thrown when the server returns an error. It's required to look at the internal details of the exception for a more information.
    /// </summary>
    public class AdalServiceException : AdalException
    {
        /// <summary>
        ///  Initializes a new instance of the exception class with a specified
        ///  error code and error message.
        /// </summary>
        /// <param name="errorCode">The protocol error code returned by the service or generated by client. This is the code you can rely on for exception handling.</param>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        public AdalServiceException(string errorCode, string message)
            : base(errorCode, message)
        {
        }

        /// <summary>
        ///  Initializes a new instance of the exception class with a specified
        ///  error code and a reference to the inner exception that is the cause of
        ///  this exception.
        /// </summary>
        /// <param name="errorCode">The protocol error code returned by the service or generated by client. This is the code you can rely on for exception handling.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified. It may especially contain the actual error message returned by the service.</param>
        internal AdalServiceException(string errorCode, Exception innerException)
            : this(errorCode, GetErrorMessage(errorCode), null, null, innerException)
        {
        }

        /// <summary>
        ///  Initializes a new instance of the exception class with a specified
        ///  error code, error message and a reference to the inner exception that is the cause of
        ///  this exception.
        /// </summary>
        /// <param name="errorCode">The protocol error code returned by the service or generated by client. This is the code you can rely on for exception handling.</param>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="serviceErrorCodes">The specific error codes that may be returned by the service.</param>
        /// <param name="response">The HttpResponse returned by the service.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified. It may especially contain the actual error message returned by the service.</param>
        internal AdalServiceException(string errorCode, string message, string[] serviceErrorCodes, IHttpWebResponse response, Exception innerException)
            : base(errorCode, message, innerException)
        {
            if (response != null)
            {
                StatusCode = (int)response.StatusCode;
                Headers = response.Headers;
            }
            else if (innerException?.InnerException is TaskCanceledException)
            {
                var taskCanceledException = ((TaskCanceledException)(innerException.InnerException));
                if (!taskCanceledException.CancellationToken.IsCancellationRequested)
                {
                    StatusCode = (int)HttpStatusCode.RequestTimeout;
                }
                else
                {
                    // There is no HttpStatusCode for user cancelation
                    StatusCode = 0;
                }
            }
            else
            {
                StatusCode = 0;
            }

            Response = response;
            ServiceErrorCodes = serviceErrorCodes;
        }

        /// <summary>
        /// Gets the status code returned from http layer. This status code is either the HttpStatusCode in the inner HttpRequestException response or
        /// NavigateError Event Status Code in browser based flow (See http://msdn.microsoft.com/en-us/library/bb268233(v=vs.85).aspx).
        /// You can use this code for purposes such as implementing retry logic or error investigation.
        /// </summary>
        public int StatusCode { get; set; }

        /// <summary>
        /// Gets the specific error codes that may be returned by the service.
        /// </summary>
        public string[] ServiceErrorCodes { get; set; }

        /// <summary>
        /// Contains headers from the response that indicated an error
        /// </summary>
        public HttpResponseHeaders Headers { get; set; }

        /// <summary>
        /// Contains the HttpResponse that indicated an error
        /// </summary>
        internal IHttpWebResponse Response { get; set; }

        /// <summary>
        /// Creates and returns a string representation of the current exception.
        /// </summary>
        /// <returns>A string representation of the current exception.</returns>
        public override string ToString()
        {
            return base.ToString() + string.Format(CultureInfo.CurrentCulture, "\n\tStatusCode: {0}", StatusCode);
        }

        private const string StatusCodeKey = "status_code";

        internal override void PopulateJson(JObject jobj)
        {
            base.PopulateJson(jobj);

            jobj[StatusCodeKey] = StatusCode.ToString(CultureInfo.InvariantCulture);
        }

        internal override void PopulateObjectFromJson(JObject jobj)
        {
            base.PopulateObjectFromJson(jobj);

            StatusCode = int.Parse(JsonUtils.GetExistingOrEmptyString(jobj, StatusCodeKey), CultureInfo.InvariantCulture);
        }
    }
}


text:
#ifndef NCSCNET_H
#define NCSCNET_H

#include "NCSTypes.h"
#include "NCSErrors.h"

#ifdef NCSCNET3
	#ifdef __cplusplus
	#include "NCSUrlStream.h"
	#endif
#endif

#ifdef WIN32
typedef SIZE_T DWORD_PTR, *PDWORD_PTR;
#include "WinInet.h"
#endif //WIN32

#ifndef NCS_MAX_PACKET_SIZE
#define NCS_MAX_PACKET_SIZE (1024*1024)
#endif
#ifndef NCS_PROTOCOL_VERSION
/*
** Version of the wire protocol.  keep in sync with NCSsnet.h [01]
*/
#define NCS_PROTOCOL_VERSION	4 /**[07]**/
#endif

typedef void *pNCSnetClient;
typedef void NCSnetPacketRecvCB(void *, INT32, pNCSnetClient, void *, NCSError eError);	 /**[06]**/	// pPacket, nLength, pClient, pUserData, eError
typedef void NCSnetPacketSentCB(NCSError, void *, void *);					// eError, pPacket, pUserData

/////

#ifdef __cplusplus
extern "C" {
#endif

BOOLEAN NCScnetVerifyURL(char *szURL);

void NCScnetSetIISDLLName(char *szDLLname);
NCSError NCScnetCreate(char *szURL, void **ppClient, void *pPacketIn, int nLengthIn, void **ppPacketOut, INT32 *pLengthOut, NCSnetPacketRecvCB *pRecvCB, void *pRecvUserdata);
NCSError NCScnetCreateEx(char *szURL, void **ppClient, void *pPacketIn, int nLengthIn, void **ppPacketOut, INT32 *pLengthOut, NCSnetPacketRecvCB *pRecvCB, void *pRecvUserdata, char *pszIISDLLName);
NCSError NCScnetCreateProxy(char *szURL, void **ppClient, void *pPacketIn, int nLengthIn, void **ppPacketOut, INT32 *pLengthOut, NCSnetPacketRecvCB *pRecvCB, void *pRecvUserdata, char *pszIISDLLName, char *pszUsername, char *pszPassword );
void NCScnetSetSendBlocking(void *pConnection, BOOLEAN bOn);
void NCScnetSetRecvCB(pNCSnetClient pClient, NCSnetPacketRecvCB *pRecvCB, void *pUserdata);
void NCScnetSetSentCB(pNCSnetClient pClient, NCSnetPacketSentCB *pSentCB);
BOOLEAN NCScnetSendPacket(pNCSnetClient pClient, void *pPacket, int nLength, void *pUserdata, BOOLEAN *bIsConnected);
//#ifdef NCS_POST_VERSION2
NCSError NCScnetPostURL(char *szURL, char *szBody, char *szHeaders, char **ppAccept,
							   BOOLEAN bIsPost, BOOLEAN bUseCache, UINT8**szResponse, int *nRespLength,
							   UINT32 *pnStatusCode, UINT32 *pnContentLength);		/**[04]**/
//#endif
void NCScnetDestroy(pNCSnetClient pClient);
void NCScnetInit();
void NCScnetShutdown();

void NCScnetSetProxy( char *pProxy, INT32 nPort, char *pProxyBypass );

//
// Function specifically required for use by the IWS Proxy
//
#ifdef PROXYSERVER
void NCSUseWinHTTP( BOOL bValue );
#endif //PROXYSERVER

#ifdef _DEBUG
__declspec(dllexport) void NCScnetSetTimeout(BOOLEAN bTimeout);
#endif

#ifdef __cplusplus
};
#endif

#endif


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/material_drawer_account_header_height">

    <ImageView
        android:id="@+id/material_drawer_account_header_background"
        android:layout_width="match_parent"
        android:layout_height="@dimen/material_drawer_account_header_height"
        android:scaleType="fitXY" />

    <RelativeLayout
        android:id="@+id/material_drawer_account_header"
        android:layout_width="match_parent"
        android:layout_height="@dimen/material_drawer_account_header_height">

        <com.example.chenpan.library.view.BezelImageView
            android:id="@+id/material_drawer_account_header_current"
            android:layout_width="@dimen/material_drawer_account_header_selected"
            android:layout_height="@dimen/material_drawer_account_header_selected"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="@dimen/material_drawer_account_header_horizontal_bottom"
            android:layout_marginLeft="@dimen/material_drawer_vertical_padding"
            android:layout_marginTop="@dimen/material_drawer_account_header_horizontal_top"
            android:clickable="true"
            android:elevation="2dp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/material_drawer_account_header_current"
            android:gravity="right">

            <com.example.chenpan.library.view.BezelImageView
                android:id="@+id/material_drawer_account_header_small_first"
                android:layout_width="@dimen/material_drawer_account_header_secondary"
                android:layout_height="@dimen/material_drawer_account_header_secondary"
                android:layout_marginRight="@dimen/material_drawer_vertical_padding"
                android:clickable="true"
                android:elevation="2dp"
                android:visibility="gone" />

            <com.example.chenpan.library.view.BezelImageView
                android:id="@+id/material_drawer_account_header_small_second"
                android:layout_width="@dimen/material_drawer_account_header_secondary"
                android:layout_height="@dimen/material_drawer_account_header_secondary"
                android:layout_marginRight="@dimen/material_drawer_vertical_padding"
                android:clickable="true"
                android:elevation="2dp"
                android:visibility="gone" />

            <com.example.chenpan.library.view.BezelImageView
                android:id="@+id/material_drawer_account_header_small_third"
                android:layout_width="@dimen/material_drawer_account_header_secondary"
                android:layout_height="@dimen/material_drawer_account_header_secondary"
                android:layout_marginRight="@dimen/material_drawer_vertical_padding"
                android:clickable="true"
                android:elevation="2dp"
                android:visibility="gone" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/material_drawer_account_header_text_section"
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="@dimen/material_drawer_padding"
            android:layout_toLeftOf="@+id/material_drawer_account_header_text_switcher"
            android:gravity="center_vertical"
            android:orientation="vertical"
            android:paddingRight="56dp">

            <TextView
                android:id="@+id/material_drawer_account_header_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/material_drawer_vertical_padding"
                android:fontFamily="sans-serif-medium"
                android:lines="1"
                android:singleLine="true"
                android:textSize="@dimen/material_drawer_account_header_text" />

            <TextView
                android:id="@+id/material_drawer_account_header_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/material_drawer_vertical_padding"
                android:layout_marginTop="8dp"
                android:fontFamily="sans-serif"
                android:lines="1"
                android:singleLine="true"
                android:textSize="14sp" />

        </LinearLayout>

        <ImageView
            android:id="@+id/material_drawer_account_header_text_switcher"
            android:layout_width="@dimen/material_drawer_account_header_dropdown"
            android:layout_height="@dimen/material_drawer_account_header_dropdown"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="@dimen/material_drawer_account_header_dropdown_margin_bottom"
            android:layout_marginRight="@dimen/material_drawer_vertical_padding" />

    </RelativeLayout>
</FrameLayout>


text:
import errno
import os
import stat
import time
import signal
import threading

from beaver.utils import eglob
from beaver.base_log import BaseLog
from beaver.worker.tail import Tail

class TailManager(BaseLog):

    def __init__(self, beaver_config, queue_consumer_function, callback, logger=None):
        super(TailManager, self).__init__(logger=logger)
        self._active = False
        self._beaver_config = beaver_config
        self._folder = self._beaver_config.get('path')
        self._callback = callback
        self._create_queue_consumer = queue_consumer_function
        self._discover_interval = beaver_config.get('discover_interval', 15)
        self._log_template = "[TailManager] - {0}"
        self._proc = None
        self._tails = {}
        self._update_time = None

        self._active = True

        signal.signal(signal.SIGTERM, self.close)

    def listdir(self):
        """HACK around not having a beaver_config stanza
        TODO: Convert this to a glob"""
        ls = os.listdir(self._folder)
        return [x for x in ls if os.path.splitext(x)[1][1:] == "log"]

    def watch(self, paths=[]):
        for path in paths:
            if not self._active:
                break

            tail = Tail(
                filename=path,
                beaver_config=self._beaver_config,
                callback=self._callback,
                logger=self._logger
            )

            if tail.active:
                self._tails[tail.fid()] = tail

    def create_queue_consumer_if_required(self, interval=5.0):
        if not (self._proc and self._proc.is_alive()):
            self._proc = self._create_queue_consumer()
        timer = threading.Timer(interval, self.create_queue_consumer_if_required)
        timer.start()

    def run(self, interval=0.1,):

        self.create_queue_consumer_if_required()

        while self._active:
            for fid in self._tails.keys():

                self.update_files()

                self._log_debug("Processing {0}".format(fid))
                if not self._active:
                    break

                self._tails[fid].run(once=True)

                if not self._tails[fid].active:
                    self._tails[fid].close()
                    del self._tails[fid]

            self.update_files()
            time.sleep(interval)

    def update_files(self):
        """Ensures all files are properly loaded.
        Detects new files, file removals, file rotation, and truncation.
        On non-linux platforms, it will also manually reload the file for tailing.
        Note that this hack is necessary because EOF is cached on BSD systems.
        """
        if self._update_time and int(time.time()) - self._update_time < self._discover_interval:
            return

        self._update_time = int(time.time())

        possible_files = []
        files = []
        if len(self._beaver_config.get('globs')) > 0:
            extend_files = files.extend
            for name, exclude in self._beaver_config.get('globs').items():
                globbed = [os.path.realpath(filename) for filename in eglob(name, exclude)]
                extend_files(globbed)
                self._beaver_config.addglob(name, globbed)
                self._callback(("addglob", (name, globbed)))
        else:
            append_files = files.append
            for name in self.listdir():
                append_files(os.path.realpath(os.path.join(self._folder, name)))

        for absname in files:
            try:
                st = os.stat(absname)
            except EnvironmentError, err:
                if err.errno != errno.ENOENT:
                    raise
            else:
                if not stat.S_ISREG(st.st_mode):
                    continue
                append_possible_files = possible_files.append
                fid = self.get_file_id(st)
                append_possible_files((fid, absname))

        # add new ones
        new_files = [fname for fid, fname in possible_files if fid not in self._tails]
        self.watch(new_files)

    def close(self, signalnum=None, frame=None):
        self._running = False
        """Closes all currently open Tail objects"""
        self._log_debug("Closing all tail objects")
        self._active = False
        for fid in self._tails:
            self._tails[fid].close()
        if self._proc is not None and self._proc.is_alive():
            self._proc.terminate()
            self._proc.join()

    @staticmethod
    def get_file_id(st):
        return "%xg%x" % (st.st_dev, st.st_ino)


text:
<?php
namespace tests\validation\rules;

require_once  DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . "testinit.php";

use validation\rules\RequiredValidatorCommand;
use validation\core\ValidationItem;

class RequiredValidatorCommandTest extends \PHPUnit_Framework_TestCase
{

    public function testOnCommand() {
        // make an instance of the Validator Command
        $command = new RequiredValidatorCommand();
		$validString1 = 'anything can go in here';
		$validString2 = '<script>@$delete something</script> is still valid for this';
		$invalidString = '';

 		$object = new ValidationItem($invalidString);

 		//first pass in a different command type to check if this is the command we need (false)
 		$result = $command->onCommand('anythinghere', $object);
 		$this->assertFalse($result);

		//now pass in a valid command parameter to begin executing the tests
		$result = $command->onCommand('validateRequired', $object);
 		$this->assertTrue($result);

		//now let's pass in an empty string - we don't care if it NEEDS to be there,
		//we only care that IF there is something, it is valid
		$this->assertFalse(is_null($object));
		$this->assertFalse($object->getIsValid());

		//now let's pass in a valid string
		$object = new ValidationItem($validString1);
		$command->onCommand('validateRequired', $object);
		$this->assertTrue($object->getIsValid());

		$object = new ValidationItem($validString2);
		$command->onCommand('validateRequired', $object);
		$this->assertTrue($object->getIsValid());
    }

}


text:
package gw2trades.repository.lucene;

import gw2trades.repository.api.RecipeRepository;
import gw2trades.repository.api.model.Recipe;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author Stefan Lotties (slotties@gmail.com)
 */
public class LuceneRecipeRepository implements RecipeRepository {
    private String indexDir;
    private IndexReader indexReader;

    public LuceneRecipeRepository(String indexDir, boolean enableReading) throws IOException {
        this.indexDir = indexDir;
        if (enableReading) {
            this.indexReader = openIndexReader();
        }
    }

    private IndexReader openIndexReader() throws IOException {
        return DirectoryReader.open(FSDirectory.open(Paths.get(indexDir)));
    }

    @Override
    public void store(Collection<Recipe> recipes) throws IOException {
        try (IndexWriter indexWriter = openIndexWriter()) {
            for (Recipe recipe : recipes) {
                Document doc = createDoc(recipe);
                indexWriter.addDocument(doc);
            }

            indexWriter.commit();
        }
    }

    private IndexWriter openIndexWriter() throws IOException {
        // TODO: correct analyzers
        Directory directory = FSDirectory.open(Paths.get(indexDir));
        StandardAnalyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        return new IndexWriter(directory, iwc);
    }

    private Document createDoc(Recipe recipe) {
        Document doc = new Document();
        doc.add(new StringField("recipeId", Integer.toString(recipe.getId()), Field.Store.YES));

        doc.add(new StringField("outputItemId", Integer.toString(recipe.getOutputItemId()), Field.Store.YES));
        doc.add(new TextField("type", recipe.getType(), Field.Store.YES));
        doc.add(new SortedDocValuesField("type", new BytesRef(recipe.getType())));

        doc.add(new IntField("minRating", recipe.getMinRating(), IntField.TYPE_STORED));
        if (recipe.getDisciplines() != null) {
            for (String discipline : recipe.getDisciplines()) {
                doc.add(new StringField("discipline", discipline, Field.Store.YES));
            }
        }

        doc.add(new TextField("outputItemName", recipe.getOutputItemName(), Field.Store.YES));
        doc.add(new SortedDocValuesField("outputItemName", new BytesRef(recipe.getOutputItemName())));

        List<Recipe.Ingredient> ingredients = recipe.getIngredients();
        if (ingredients != null) {
            doc.add(new IntField("ingredientsCount", ingredients.size(), IntField.TYPE_STORED));
            for (int i = 0; i < ingredients.size(); i++) {
                Recipe.Ingredient ingredient = ingredients.get(i);
                doc.add(new StringField("ingredients", Integer.toString(ingredient.getItemId()), Field.Store.YES));
                doc.add(new IntField("ingredient" + i + "_id", ingredient.getItemId(), IntField.TYPE_STORED));
                doc.add(new IntField("ingredient" + i + "_count", ingredient.getCount(), IntField.TYPE_STORED));
                doc.add(new TextField("ingredient" + i + "_name", ingredient.getName(), Field.Store.YES));
                doc.add(new SortedDocValuesField("ingredient" + i + "_name", new BytesRef(ingredient.getName())));
            }
        } else {
            doc.add(new IntField("ingredientsCount", 0, IntField.TYPE_STORED));
        }

        return doc;
    }

    @Override
    public Recipe getRecipe(int id) throws IOException {
        IndexSearcher searcher = new IndexSearcher(this.indexReader);
        Query query = new TermQuery(new Term("recipeId", Integer.toString(id)));
        TopDocs topDocs = searcher.search(query, 1);
        if (topDocs.totalHits < 1) {
            return null;
        }

        Document doc = indexReader.document(topDocs.scoreDocs[0].doc);
        return readRecipe(doc);
    }

    @Override
    public Collection<Recipe> getRecipesByIngredient(int itemId) throws IOException {
        IndexSearcher searcher = new IndexSearcher(this.indexReader);
        Query query = new TermQuery(new Term("ingredients", Integer.toString(itemId)));
        TopDocs topDocs = searcher.search(query, Integer.MAX_VALUE);

        List<Recipe> recipes = new ArrayList<>(topDocs.totalHits);
        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            Document doc = indexReader.document(topDocs.scoreDocs[i].doc);
            if (doc != null) {
                recipes.add(readRecipe(doc));
            }
        }

        return recipes;
    }

    @Override
    public Collection<Recipe> getRecipesByOutputItem(int itemId) throws IOException {
        IndexSearcher searcher = new IndexSearcher(this.indexReader);
        Query query = new TermQuery(new Term("outputItemId", Integer.toString(itemId)));
        TopDocs topDocs = searcher.search(query, Integer.MAX_VALUE);

        List<Recipe> recipes = new ArrayList<>(topDocs.totalHits);
        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            Document doc = indexReader.document(topDocs.scoreDocs[i].doc);
            if (doc != null) {
                recipes.add(readRecipe(doc));
            }
        }

        return recipes;
    }

    private Recipe readRecipe(Document document) {
        Recipe recipe = new Recipe();
        recipe.setId(Integer.valueOf(document.get("recipeId")));
        recipe.setOutputItemId(Integer.valueOf(document.get("outputItemId")));
        recipe.setType(document.get("type"));
        recipe.setOutputItemName(document.get("outputItemName"));
        recipe.setMinRating(Integer.valueOf(document.get("minRating")));

        recipe.setDisciplines(Arrays.asList(document.getValues("discipline")));

        int ingredientsCount = Integer.valueOf(document.get("ingredientsCount"));
        List<Recipe.Ingredient> ingredients = new ArrayList<>(ingredientsCount);
        for (int i = 0; i < ingredientsCount; i++) {
            Recipe.Ingredient ingredient = new Recipe.Ingredient();
            ingredient.setItemId(Integer.valueOf(document.get("ingredient" + i + "_id")));
            ingredient.setCount(Integer.valueOf(document.get("ingredient" + i + "_count")));
            ingredient.setName(document.get("ingredient" + i + "_name"));
            ingredients.add(ingredient);
        }
        recipe.setIngredients(ingredients);

        return recipe;
    }

    @Override
    public void close() throws IOException {
        if (indexReader != null) {
            indexReader.close();
        }
    }

    @Override
    public void reopen() throws IOException {
        close();
        this.indexReader = openIndexReader();
    }
}


text:
/* eslint-env node, mocha */
/* global $pg_database */
import request from 'superagent';
import expect from 'unexpected';

import cleanDB from '../dbCleaner';
import { getSingleton } from '../../app/app';
import { DummyPublisher } from '../../app/pubsub';
import { Comment, PubSub } from '../../app/models';

import * as funcTestHelper from './functional_test_helper';
import { getCommentResponse } from './schemaV2-helper';

describe('CommentsController', () => {
  let app;

  before(async () => {
    app = await getSingleton();
    PubSub.setPublisher(new DummyPublisher());
  });

  beforeEach(() => cleanDB($pg_database));

  describe('#create()', () => {
    let context = {};
    beforeEach(async () => {
      context = await funcTestHelper.createUserAsync('Luna', 'password');
      context.post = await funcTestHelper.createAndReturnPost(context, 'Post body');
    });

    describe('in a group', () => {
      const groupName = 'pepyatka-dev';

      beforeEach(async () => {
        const screenName = 'Pepyatka Developers';
        await funcTestHelper.createGroupAsync(context, groupName, screenName);
      });

      it("should not update group's last activity", (done) => {
        const body = 'Post body';

        request
          .post(`${app.context.config.host}/v1/posts`)
          .send({ post: { body }, meta: { feeds: [groupName] }, authToken: context.authToken })
          .end((err, res) => {
            res.status.should.eql(200);
            const postB = res.body.posts;
            funcTestHelper.getTimeline(`/v1/users/${groupName}`, context.authToken, (err, res) => {
              res.status.should.eql(200);
              const lastUpdatedAt = parseInt(res.body.users.updatedAt, 10);

              funcTestHelper.createComment(body, postB.id, context.authToken, (err, res) => {
                res.status.should.eql(200);
                funcTestHelper.getTimeline(
                  `/v1/users/${groupName}`,
                  context.authToken,
                  (err, res) => {
                    res.status.should.eql(200);
                    res.body.should.have.property('users');
                    res.body.users.should.have.property('updatedAt');
                    lastUpdatedAt.should.be.lt(parseInt(res.body.users.updatedAt, 10));

                    done();
                  },
                );
              });
            });
          });
      });
    });

    it('should create a comment with a valid user', (done) => {
      const body = 'Comment';

      funcTestHelper.createCommentCtx(
        context,
        body,
      )((err, res) => {
        res.body.should.not.be.empty;
        res.body.should.have.property('comments');
        res.body.comments.should.have.property('body');
        res.body.comments.body.should.eql(body);

        done();
      });
    });

    it('should not create a comment for an invalid user', (done) => {
      const body = 'Comment';

      context.authToken = 'token';
      funcTestHelper.createCommentCtx(
        context,
        body,
      )((err) => {
        err.should.not.be.empty;
        err.status.should.eql(401);

        done();
      });
    });

    it('should not create a comment for an invalid post', (done) => {
      const body = 'Comment';

      context.post.id = '00000000-0000-4000-8000-000000000046';
      funcTestHelper.createCommentCtx(
        context,
        body,
      )((err) => {
        err.should.not.be.empty;
        err.status.should.eql(404);

        done();
      });
    });

    it('should create a comment to own post even when comments disabled', async () => {
      const postResponse = await funcTestHelper.createPostWithCommentsDisabled(
        context,
        'Post body',
        true,
      );
      const data = await postResponse.json();
      const post = data.posts;

      const response = await funcTestHelper.createCommentAsync(context, post.id, 'Comment');
      response.status.should.eql(200);
    });

    it("should not create a comment to another user's post when comments disabled", async () => {
      const postResponse = await funcTestHelper.createPostWithCommentsDisabled(
        context,
        'Post body',
        true,
      );
      const postData = await postResponse.json();
      const post = postData.posts;

      const marsContext = await funcTestHelper.createUserAsync('mars', 'password2');

      const response = await funcTestHelper.createCommentAsync(marsContext, post.id, 'Comment');
      response.status.should.eql(403);

      const data = await response.json();
      data.should.have.property('err');
      data.err.should.eql('Comments disabled');
    });

    describe('Interaction with banned user', () => {
      let mars;
      let postOfMars;

      beforeEach(async () => {
        mars = await funcTestHelper.createUserAsync('Mars', 'password');
        postOfMars = await funcTestHelper.createAndReturnPost(mars, 'I am mars!');
        await funcTestHelper.banUser(context, mars);
      });

      it(`should not create comment on banned user's post`, async () => {
        const response = await funcTestHelper.createCommentAsync(context, postOfMars.id, 'Comment');
        response.status.should.eql(403);
      });

      it(`should not create comment on post of user who banned us`, async () => {
        const response = await funcTestHelper.createCommentAsync(mars, context.post.id, 'Comment');
        response.status.should.eql(403);
      });
    });
  });

  describe('#update()', () => {
    let lunaContext = {};
    let yoleContext = {};
    let comment;

    beforeEach(async () => {
      [lunaContext, yoleContext] = await Promise.all([
        funcTestHelper.createUserAsync('Luna', 'password'),
        funcTestHelper.createUserAsync('yole', 'pw'),
      ]);

      const post = await funcTestHelper.createAndReturnPost(lunaContext, 'post body');
      const response = await funcTestHelper.createCommentAsync(lunaContext, post.id, 'comment');
      const commentData = await response.json();

      comment = commentData.comments;
    });

    it('should update a comment with a valid user', (done) => {
      const newBody = 'New body';
      request
        .post(`${app.context.config.host}/v1/comments/${comment.id}`)
        .send({
          comment: { body: newBody },
          authToken: lunaContext.authToken,
          _method: 'put',
        })
        .end((err, res) => {
          res.body.should.not.be.empty;
          res.body.should.have.property('comments');
          res.body.comments.should.have.property('body');
          res.body.comments.body.should.eql(newBody);

          done();
        });
    });

    it('should not update a comment with a invalid user', (done) => {
      const newBody = 'New body';
      request
        .post(`${app.context.config.host}/v1/comments/${comment.id}`)
        .send({
          comment: { body: newBody },
          _method: 'put',
        })
        .end((err) => {
          err.should.not.be.empty;
          err.status.should.eql(401);

          done();
        });
    });

    it("should not update another user's comment", (done) => {
      const newBody = 'New body';
      request
        .post(`${app.context.config.host}/v1/comments/${comment.id}`)
        .send({
          comment: { body: newBody },
          authToken: yoleContext.authToken,
          _method: 'put',
        })
        .end((err) => {
          err.status.should.eql(403);
          done();
        });
    });
  });

  describe('#destroy()', () => {
    let lunaContext = {},
      marsContext = {},
      ceresContext = {};

    let lunaPostLunaComment,
      lunaPostMarsComment,
      marsPostMarsComment,
      marsPostLunaComment,
      marsPostCeresComment;

    beforeEach(async () => {
      [lunaContext, marsContext, ceresContext] = await Promise.all([
        funcTestHelper.createUserAsync('luna', 'password'),
        funcTestHelper.createUserAsync('mars', 'password2'),
        funcTestHelper.createUserAsync('ceres', 'password3'),
      ]);

      const [lunaPost, marsPost] = await Promise.all([
        funcTestHelper.createAndReturnPost(lunaContext, 'Post body 1'),
        funcTestHelper.createAndReturnPost(marsContext, 'Post body 2'),
      ]);

      let response = await funcTestHelper.createCommentAsync(
        lunaContext,
        lunaPost.id,
        'Comment 1-1',
      );
      let data = await response.json();
      lunaPostLunaComment = data.comments.id;

      response = await funcTestHelper.createCommentAsync(marsContext, lunaPost.id, 'Comment 1-2');
      data = await response.json();
      lunaPostMarsComment = data.comments.id;

      response = await funcTestHelper.createCommentAsync(marsContext, marsPost.id, 'Comment 2-1');
      data = await response.json();
      marsPostMarsComment = data.comments.id;

      response = await funcTestHelper.createCommentAsync(lunaContext, marsPost.id, 'Comment 2-2');
      data = await response.json();
      marsPostLunaComment = data.comments.id;

      response = await funcTestHelper.createCommentAsync(ceresContext, marsPost.id, 'Comment 2-3');
      data = await response.json();
      marsPostCeresComment = data.comments.id;
    });

    it('should remove comment (your own comment in your own post)', async () => {
      const response = await funcTestHelper.removeCommentAsync(lunaContext, lunaPostLunaComment);
      response.status.should.eql(200);
    });

    it("should remove comment (other's comment in your own post)", async () => {
      const response = await funcTestHelper.removeCommentAsync(lunaContext, lunaPostMarsComment);
      response.status.should.eql(200);
    });

    it("should remove comment (your own comment in other's post)", async () => {
      const response = await funcTestHelper.removeCommentAsync(lunaContext, marsPostLunaComment);
      response.status.should.eql(200);
    });

    it("should not remove comment (other's comment in other's post)", async () => {
      const response = await funcTestHelper.removeCommentAsync(lunaContext, marsPostMarsComment);
      response.status.should.eql(403);

      const data = await response.json();
      data.should.have.property('err');
      data.err.should.eql("You don't have permission to delete this comment");
    });

    it("should not remove comment (other's comment in other's post, again)", async () => {
      const response = await funcTestHelper.removeCommentAsync(lunaContext, marsPostCeresComment);
      response.status.should.eql(403);

      const data = await response.json();
      data.should.have.property('err');
      data.err.should.eql("You don't have permission to delete this comment");
    });

    it('should not remove comment if anonymous', async () => {
      const response = await funcTestHelper.removeCommentAsync({}, lunaPostLunaComment);
      response.status.should.eql(401);
    });
  });

  describe('get by id or number', () => {
    let luna, mars, venus, postId, commentIds;
    beforeEach(async () => {
      [luna, mars, venus] = await funcTestHelper.createTestUsers(['luna', 'mars', 'venus']);
      ({ id: postId } = await funcTestHelper.createAndReturnPost(luna, 'post'));
      commentIds = [];

      for (let i = 0; i < 3; i++) {
        // eslint-disable-next-line no-await-in-loop
        const resp = await funcTestHelper.createCommentAsync(
          [luna, mars, luna][i],
          postId,
          `Comment ${i + 1}`,
        );
        // eslint-disable-next-line no-await-in-loop
        const data = await resp.json();
        commentIds.push(data.comments.id);
      }
    });

    describe('comment by id', () => {
      it('should not return comment by invalid id', async () => {
        const resp = await funcTestHelper.performJSONRequest('GET', `/v1/comments/${postId}`);
        expect(resp.__httpCode, 'to be', 404);
      });

      it('should return public comment by id to anonymous', async () => {
        const resp = await funcTestHelper.performJSONRequest(
          'GET',
          `/v1/comments/${commentIds[0]}`,
        );
        expect(resp, 'to satisfy', getCommentResponse);
        expect(resp, 'to satisfy', {
          __httpCode: 200,
          comments: { id: commentIds[0] },
        });
      });

      describe('Luna became private', () => {
        beforeEach(() => funcTestHelper.goPrivate(luna));

        it('should not return comment by id to anonymous', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[0]}`,
          );
          expect(resp.__httpCode, 'to be', 403);
        });

        it('should not return comment by id to Mars', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[0]}`,
            undefined,
            funcTestHelper.authHeaders(mars),
          );
          expect(resp.__httpCode, 'to be', 403);
        });

        it('should return comment by id to Luna', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[0]}`,
            undefined,
            funcTestHelper.authHeaders(luna),
          );
          expect(resp.__httpCode, 'to be', 200);
        });
      });

      describe('Luna bans Mars', () => {
        beforeEach(() => funcTestHelper.banUser(luna, mars));

        it('should return comment by id to anonymous', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[0]}`,
          );
          expect(resp.__httpCode, 'to be', 200);
        });

        it('should not return comment by id to Mars', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[0]}`,
            undefined,
            funcTestHelper.authHeaders(mars),
          );
          expect(resp.__httpCode, 'to be', 403);
        });

        it('should return comment by id to Luna', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[0]}`,
            undefined,
            funcTestHelper.authHeaders(luna),
          );
          expect(resp.__httpCode, 'to be', 200);
        });
      });

      describe('Venus bans Mars', () => {
        beforeEach(() => funcTestHelper.banUser(venus, mars));

        it('should return hidden Marses comment by id to Venus', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v1/comments/${commentIds[1]}`,
            undefined,
            funcTestHelper.authHeaders(venus),
          );
          expect(resp, 'to satisfy', {
            __httpCode: 200,
            comments: {
              id: commentIds[1],
              body: Comment.hiddenBody(Comment.HIDDEN_BANNED),
              hideType: Comment.HIDDEN_BANNED,
              createdBy: null,
            },
          });
        });
      });
    });

    describe('comment by number', () => {
      it('should not return comment by invalid post id', async () => {
        const resp = await funcTestHelper.performJSONRequest(
          'GET',
          `/v2/posts/${commentIds[0]}/comments/1`,
        );
        expect(resp.__httpCode, 'to be', 404);
      });

      it('should not return comment by invalid comment number', async () => {
        const resp = await funcTestHelper.performJSONRequest(
          'GET',
          `/v2/posts/${postId}/comments/137`,
        );
        expect(resp.__httpCode, 'to be', 404);
      });

      it('should return public comment by id to anonymous', async () => {
        const resp = await funcTestHelper.performJSONRequest(
          'GET',
          `/v2/posts/${postId}/comments/1`,
        );
        expect(resp, 'to satisfy', getCommentResponse);
        expect(resp, 'to satisfy', {
          __httpCode: 200,
          comments: { id: commentIds[0] },
        });
      });

      describe('Luna became private', () => {
        beforeEach(() => funcTestHelper.goPrivate(luna));

        it('should not return comment by id to anonymous', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/1`,
          );
          expect(resp.__httpCode, 'to be', 403);
        });

        it('should not return comment by id to Mars', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/1`,
            undefined,
            funcTestHelper.authHeaders(mars),
          );
          expect(resp.__httpCode, 'to be', 403);
        });

        it('should return comment by id to Luna', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/1`,
            undefined,
            funcTestHelper.authHeaders(luna),
          );
          expect(resp.__httpCode, 'to be', 200);
        });
      });

      describe('Luna bans Mars', () => {
        beforeEach(() => funcTestHelper.banUser(luna, mars));

        it('should return comment by id to anonymous', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/1`,
          );
          expect(resp.__httpCode, 'to be', 200);
        });

        it('should not return comment by id to Mars', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/1`,
            undefined,
            funcTestHelper.authHeaders(mars),
          );
          expect(resp.__httpCode, 'to be', 403);
        });

        it('should return comment by id to Luna', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/1`,
            undefined,
            funcTestHelper.authHeaders(luna),
          );
          expect(resp.__httpCode, 'to be', 200);
        });
      });

      describe('Venus bans Mars', () => {
        beforeEach(() => funcTestHelper.banUser(venus, mars));

        it('should return hidden Marses comment by id to Venus', async () => {
          const resp = await funcTestHelper.performJSONRequest(
            'GET',
            `/v2/posts/${postId}/comments/2`,
            undefined,
            funcTestHelper.authHeaders(venus),
          );
          expect(resp, 'to satisfy', {
            __httpCode: 200,
            comments: {
              id: commentIds[1],
              body: Comment.hiddenBody(Comment.HIDDEN_BANNED),
              hideType: Comment.HIDDEN_BANNED,
              createdBy: null,
            },
          });
        });
      });
    });
  });
});


text:
namespace PhoneSystem.Contracts
{
    using System;

    public interface IAuditInfo
    {
        DateTime CreatedOn { get; set; }

        bool PreserveCreatedOn { get; set; }

        DateTime? ModifiedOn { get; set; }
    }
}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.support.events;

import com.google.common.primitives.Primitives;

import org.openqa.selenium.Alert;
import org.openqa.selenium.Beta;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.decorators.Decorated;
import org.openqa.selenium.support.decorators.WebDriverDecorator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This decorator creates a wrapper around an arbitrary {@link WebDriver} instance that notifies
 * registered listeners about events happening in this WebDriver and derived objects, such as
 * {@link WebElement}s and {@link Alert}.
 *

 * Listeners should implement {@link WebDriverListener}. It supports three types of events:
 *

 *
"before"-event: a method is about to be called;

 *
"after"-event: a method was called successfully and returned some result;

 *
"error"-event: a method was called and thrown an exception.

 *

 * To use this decorator you have to prepare a listener, create a decorator using this listener,
 * decorate the original WebDriver instance with this decorator and use the new WebDriver
 * instance created by the decorator instead of the original one:
 *

 *   WebDriver original = new FirefoxDriver();
 *   WebDriverListener listener = new MyListener();
 *   WebDriver decorated = new EventFiringDecorator(listener).decorate(original);
 *   decorated.get("http://example.com/");
 *   WebElement header = decorated.findElement(By.tagName("h1"));
 *   String headerText = header.getText();
 *

 *

 * The instance of WebDriver created by the decorator implements all the same interfaces as
 * the original driver.
 *

 * A listener can subscribe to "specific" or "generic" events (or both). A "specific" event
 * correspond to a single specific method, a "generic" event correspond to any method called in
 * a class or in any class.
 *

 * To subscribe to a "specific" event a listener should implement a method with a name derived from
 * the target method to be watched. The listener methods for "before"-events receive the parameters
 * passed to the decorated method. The listener methods for "after"-events receive the parameters
 * passed to the decorated method as well as the result returned by this method.
 *

 *   WebDriverListener listener = new WebDriverListener() {
 *     @Override
 *     public void beforeGet(WebDriver driver, String url) {
 *       logger.log("About to open a page %s", url);
 *     }
 *     @Override
 *     public void afterGetText(WebElement element, String result) {
 *       logger.log("Element %s has text '%s'", element, result);
 *     }
 *   };
 *

 *

 * To subscribe to a "generic" event a listener should implement a method with a name derived from
 * the class to be watched:
 *

 *   WebDriverListener listener = new WebDriverListener() {
 *     @Override
 *     public void beforeAnyWebElementCall(WebElement element, Method method, Object[] args) {
 *       logger.log("About to call a method %s in element %s with parameters %s",
 *                  method, element, args);
 *     }
 *     @Override
 *     public void afterAnyWebElementCall(WebElement element, Method method, Object[] args, Object result) {
 *       logger.log("Method %s called in element %s with parameters %s returned %s",
 *                  method, element, args, result);
 *     }
 *   };
 *

 *

 * There are also listener methods for "super-generic" events:
 *

 *   WebDriverListener listener = new WebDriverListener() {
 *     @Override
 *     public void beforeAnyCall(Object target, Method method, Object[] args) {
 *       logger.log("About to call a method %s in %s with parameters %s",
 *                  method, target, args);
 *     }
 *     @Override
 *     public void afterAnyCall(Object target, Method method, Object[] args, Object result) {
 *       logger.log("Method %s called in %s with parameters %s returned %s",
 *                  method, target, args, result);
 *     }
 *   };
 *

 *

 * A listener can subscribe to both "specific" and "generic" events at the same time. In this case
 * "before"-events are fired in order from the most generic to the most specific,
 * and "after"-events are fired in the opposite order, for example:
 *

 *   beforeAnyCall
 *   beforeAnyWebDriverCall
 *   beforeGet
 *   // the actual call to the decorated method here
 *   afterGet
 *   afterAnyWebDriverCall
 *   afterAnyCall
 *

 *

 * One of the most obvious use of this decorator is logging. But it can be used to modify behavior
 * of the original driver to some extent because listener methods are executed in the same thread
 * as the original driver methods.
 *

 * For example, a listener can be used to slow down execution for demonstration purposes, just
 * make a listener that adds a pause before some operations:
 *

 *   WebDriverListener listener = new WebDriverListener() {
 *     @Override
 *     public void beforeClick(WebElement element) {
 *       try {
 *         Thread.sleep(3000);
 *       } catch (InterruptedException e) {
 *         Thread.currentThread().interrupt();
 *       }
 *     }
 *   };
 *

 *

 * Just be careful to not block the current thread in a listener method!
 *

 * Listeners can't affect driver behavior too much. They can't throw any exceptions
 * (they can, but the decorator suppresses these exceptions), can't prevent execution of
 * the decorated methods, can't modify parameters and results of the methods.
 *

 * Decorators that modify the behaviour of the underlying drivers should be implemented by
 * extending {@link WebDriverDecorator}, not by creating sophisticated listeners.
 */
@Beta
public class EventFiringDecorator<T extends WebDriver> extends WebDriverDecorator<T>  {

  private static final Logger logger = Logger.getLogger(EventFiringDecorator.class.getName());

  private final List<WebDriverListener> listeners;

  public EventFiringDecorator(WebDriverListener... listeners) {
    this.listeners = Arrays.asList(listeners);
  }

  @Override
  public void beforeCall(Decorated<?> target, Method method, Object[] args) {
    listeners.forEach(listener -> fireBeforeEvents(listener, target, method, args));
    super.beforeCall(target, method, args);
  }

  @Override
  public void afterCall(Decorated<?> target, Method method, Object[] args, Object result) {
    super.afterCall(target, method, args, result);
    listeners.forEach(listener -> fireAfterEvents(listener, target, method, result, args));
  }

  @Override
  public Object onError(Decorated<?> target, Method method, Object[] args,
                        InvocationTargetException e) throws Throwable {
    listeners.forEach(listener -> {
      try {
        listener.onError(target.getOriginal(), method, args, e);
      } catch (Throwable t) {
        logger.log(Level.WARNING, t.getMessage(), t);
      }
    });
    return super.onError(target, method, args, e);
  }

  private void fireBeforeEvents(WebDriverListener listener, Decorated<?> target, Method method, Object[] args) {
    try {
      listener.beforeAnyCall(target.getOriginal(), method, args);
    } catch (Throwable t) {
      logger.log(Level.WARNING, t.getMessage(), t);
    }

    try {
      if (target.getOriginal() instanceof WebDriver) {
        listener.beforeAnyWebDriverCall((WebDriver) target.getOriginal(), method, args);
      } else if (target.getOriginal() instanceof WebElement) {
        listener.beforeAnyWebElementCall((WebElement) target.getOriginal(), method, args);
      } else if (target.getOriginal() instanceof WebDriver.Navigation) {
        listener.beforeAnyNavigationCall((WebDriver.Navigation) target.getOriginal(), method, args);
      } else if (target.getOriginal() instanceof Alert) {
        listener.beforeAnyAlertCall((Alert) target.getOriginal(), method, args);
      } else if (target.getOriginal() instanceof WebDriver.Options) {
        listener.beforeAnyOptionsCall((WebDriver.Options) target.getOriginal(), method, args);
      } else if (target.getOriginal() instanceof WebDriver.Timeouts) {
        listener.beforeAnyTimeoutsCall((WebDriver.Timeouts) target.getOriginal(), method, args);
      } else if (target.getOriginal() instanceof WebDriver.Window) {
        listener.beforeAnyWindowCall((WebDriver.Window) target.getOriginal(), method, args);
      }
    } catch (Throwable t) {
      logger.log(Level.WARNING, t.getMessage(), t);
    }

    String methodName = createEventMethodName("before", method.getName());

    int argsLength = args != null ? args.length : 0;
    Object[] args2 = new Object[argsLength + 1];
    args2[0] = target.getOriginal();
    for (int i = 0; i < argsLength; i++) {
      args2[i + 1] = args[i];
    }

    Method m = findMatchingMethod(listener, methodName, args2);
    if (m != null) {
      callListenerMethod(m, listener, args2);
    }
  }

  private void fireAfterEvents(WebDriverListener listener, Decorated<?> target, Method method, Object res, Object[] args) {
    String methodName = createEventMethodName("after", method.getName());

    boolean isVoid = method.getReturnType() == Void.TYPE
                     || method.getReturnType() == WebDriver.Timeouts.class;
    int argsLength = args != null ? args.length : 0;
    Object[] args2 = new Object[argsLength + 1 + (isVoid  ? 0 : 1)];
    args2[0] = target.getOriginal();
    for (int i = 0; i < argsLength; i++) {
      args2[i + 1] = args[i];
    }
    if (! isVoid) {
      args2[args2.length - 1] = res;
    }

    Method m = findMatchingMethod(listener, methodName, args2);
    if (m != null) {
      callListenerMethod(m, listener, args2);
    }

    try {
      if (target.getOriginal() instanceof WebDriver) {
        listener.afterAnyWebDriverCall((WebDriver) target.getOriginal(), method, args, res);
      } else if (target.getOriginal() instanceof WebElement) {
        listener.afterAnyWebElementCall((WebElement) target.getOriginal(), method, args, res);
      } else if (target.getOriginal() instanceof WebDriver.Navigation) {
        listener.afterAnyNavigationCall((WebDriver.Navigation) target.getOriginal(), method, args,
                                        res);
      } else if (target.getOriginal() instanceof Alert) {
        listener.afterAnyAlertCall((Alert) target.getOriginal(), method, args, res);
      } else if (target.getOriginal() instanceof WebDriver.Options) {
        listener.afterAnyOptionsCall((WebDriver.Options) target.getOriginal(), method, args, res);
      } else if (target.getOriginal() instanceof WebDriver.Timeouts) {
        listener.afterAnyTimeoutsCall((WebDriver.Timeouts) target.getOriginal(), method, args, res);
      } else if (target.getOriginal() instanceof WebDriver.Window) {
        listener.afterAnyWindowCall((WebDriver.Window) target.getOriginal(), method, args, res);
      }
    } catch (Throwable t) {
      logger.log(Level.WARNING, t.getMessage(), t);
    }

    try {
      listener.afterAnyCall(target.getOriginal(), method, args, res);
    } catch (Throwable t) {
      logger.log(Level.WARNING, t.getMessage(), t);
    }
  }

  private String createEventMethodName(String prefix, String originalMethodName) {
    return prefix + originalMethodName.substring(0, 1).toUpperCase() + originalMethodName.substring(1);
  }

  private Method findMatchingMethod(WebDriverListener listener, String methodName, Object[] args) {
    for (Method m : listener.getClass().getMethods()) {
      if (m.getName().equals(methodName) && parametersMatch(m, args)) {
        return m;
      }
    }
    return null;
  }

  private boolean parametersMatch(Method m, Object[] args) {
    Class<?>[] params = m.getParameterTypes();
    if (params.length != args.length) {
      return false;
    }
    for (int i = 0; i < params.length; i++) {
      if (args[i] != null && ! Primitives.wrap(params[i]).isAssignableFrom(args[i].getClass())) {
        return false;
      }
    }
    return true;
  }

  private void callListenerMethod(Method m, WebDriverListener listener, Object[] args) {
    try {
      m.invoke(listener, args);
    } catch (Throwable t) {
      logger.log(Level.WARNING, t.getMessage(), t);
    }
  }
}


text:
package org.jetbrains.yaml.meta.model;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLBundle;
import org.jetbrains.yaml.psi.YAMLScalar;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@ApiStatus.Experimental
public class YamlEnumType extends YamlScalarType {
  private String[] myLiterals = ArrayUtil.EMPTY_STRING_ARRAY;
  private String[] myHiddenLiterals = ArrayUtil.EMPTY_STRING_ARRAY;
  private String[] myDeprecatedLiterals = ArrayUtil.EMPTY_STRING_ARRAY;

  public YamlEnumType(@NotNull String typeName) {
    super(typeName);
  }

  @NotNull
  public YamlEnumType withLiterals(String... literals) {
    myLiterals = cloneArray(literals);
    return this;
  }

  /**
   * Specifies subset of the valid values which will be accepted by validation but will NOT be offered in
   * completion lists. These values must not overlap with the visible (see {@link #withLiterals(String...)}),
   * but may overlap with the deprecated (see {@link #withDeprecatedLiterals(String...)})
   */
  @NotNull
  public YamlEnumType withHiddenLiterals(String... hiddenLiterals) {
    myHiddenLiterals = hiddenLiterals.clone();
    return this;
  }

  /**
   * Specifies subset of the valid values which will be considered deprecated.
   * They will be available in completion list (struck out) and highlighted after validation.
   * These values must not overlap with the visible (see {@link #withLiterals(String...)}),
   * but may overlap with the hidden (see {@link #withHiddenLiterals(String...)})
   */
  @NotNull
  public YamlEnumType withDeprecatedLiterals(String... deprecatedLiterals) {
    myDeprecatedLiterals = deprecatedLiterals.clone();
    return this;
  }

  @NotNull
  protected final Stream<String> getLiteralsStream() {
    return Stream.concat(Arrays.stream(myLiterals), Arrays.stream(myDeprecatedLiterals));
  }

  @Override
  protected void validateScalarValue(@NotNull YAMLScalar scalarValue, @NotNull ProblemsHolder holder) {
    super.validateScalarValue(scalarValue, holder);

    String text = scalarValue.getTextValue();
    if (text.isEmpty()) {
      // not our business
      return;
    }

    if (Arrays.asList(myDeprecatedLiterals).contains(text)) {
      holder.registerProblem(scalarValue,
                             YAMLBundle.message("YamlEnumType.validation.warning.value.deprecated", text),
                             ProblemHighlightType.LIKE_DEPRECATED);
    }
    else if (Stream.concat(Arrays.stream(myHiddenLiterals), getLiteralsStream()).noneMatch(text::equals)) {
      //TODO quickfix makes sense here if !text.equals(text.toLowerCase)
      holder.registerProblem(scalarValue,
                             YAMLBundle.message("YamlEnumType.validation.error.value.unknown", text),
                             ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    }
  }

  @NotNull
  @Override
  public List<LookupElement> getValueLookups(@NotNull YAMLScalar context) {
    return Stream.concat(
      Arrays.stream(myLiterals).map((String literal) -> createValueLookup(literal, false)),
      Arrays.stream(myDeprecatedLiterals).map((String literal) -> createValueLookup(literal, true))
    )
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
  }

  @Nullable
  protected LookupElement createValueLookup(@NotNull String literal, boolean deprecated) {
    return LookupElementBuilder.create(literal).withStrikeoutness(deprecated);
  }

  @NotNull
  private static String[] cloneArray(@NotNull String[] array) {
    return array.length == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : array.clone();
  }
}


text:
@implementation NSData (TLHash)

- (NSData *)md5Data
{
    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
    CC_MD5(self.bytes, (CC_LONG)self.length, bytes);
    return [NSData dataWithBytes:bytes length:CC_MD5_DIGEST_LENGTH];
}

- (NSData *)sha1Data
{
    unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(self.bytes, (CC_LONG)self.length, bytes);
    return [NSData dataWithBytes:bytes length:CC_SHA1_DIGEST_LENGTH];
}

- (NSData *)sha256Data
{
    unsigned char bytes[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(self.bytes, (CC_LONG)self.length, bytes);
    return [NSData dataWithBytes:bytes length:CC_SHA256_DIGEST_LENGTH];
}

- (NSData *)sha512Data
{
    unsigned char bytes[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(self.bytes, (CC_LONG)self.length, bytes);
    return [NSData dataWithBytes:bytes length:CC_SHA512_DIGEST_LENGTH];
}

- (NSData *)hmacMD5DataWithKey:(NSData *)key
{
    return [self hmacDataUsingAlg:kCCHmacAlgMD5 withKey:key];
}

- (NSData *)hmacSHA1DataWithKey:(NSData *)key
{
    return [self hmacDataUsingAlg:kCCHmacAlgSHA1 withKey:key];
}

- (NSData *)hmacSHA256DataWithKey:(NSData *)key
{
    return [self hmacDataUsingAlg:kCCHmacAlgSHA256 withKey:key];
}

- (NSData *)hmacSHA512DataWithKey:(NSData *)key
{
    return [self hmacDataUsingAlg:kCCHmacAlgSHA512 withKey:key];
}

- (NSData *)hmacDataUsingAlg:(CCHmacAlgorithm)alg withKey:(NSData *)key
{
    size_t size;
    switch (alg) {
        case kCCHmacAlgMD5: size = CC_MD5_DIGEST_LENGTH; break;
        case kCCHmacAlgSHA1: size = CC_SHA1_DIGEST_LENGTH; break;
        case kCCHmacAlgSHA224: size = CC_SHA224_DIGEST_LENGTH; break;
        case kCCHmacAlgSHA256: size = CC_SHA256_DIGEST_LENGTH; break;
        case kCCHmacAlgSHA384: size = CC_SHA384_DIGEST_LENGTH; break;
        case kCCHmacAlgSHA512: size = CC_SHA512_DIGEST_LENGTH; break;
        default: return nil;
    }
    unsigned char result[size];
    CCHmac(alg, [key bytes], key.length, self.bytes, self.length, result);
    return [NSData dataWithBytes:result length:size];
}

@end


text:
#include "tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h"

#include <limits>
#include <string>

#include "tensorflow/compiler/xla/service/gpu/backend_configs.pb.h"
#include "tensorflow/compiler/xla/service/gpu/buffer_comparator.h"
#include "tensorflow/compiler/xla/service/gpu/gemm_thunk.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_asm_opts_util.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logger.h"
#include "tensorflow/core/protobuf/autotuning.pb.h"
#include "tensorflow/core/util/proto/proto_utils.h"
#include "tensorflow/stream_executor/blas.h"
#include "tensorflow/stream_executor/device_memory.h"
#include "tensorflow/stream_executor/device_memory_allocator.h"
#include "tensorflow/stream_executor/gpu/redzone_allocator.h"

namespace xla {
namespace gpu {

using tensorflow::AutotuneResult;

using GemmCacheKey =
    std::tuple<se::StreamExecutor*, Shape, Shape, Shape, std::string>;

static absl::Mutex autotune_cache_mu(absl::kConstInit);
static auto& autotune_cache ABSL_GUARDED_BY(autotune_cache_mu) =
    *new absl::flat_hash_map<GemmCacheKey,
                             absl::optional<se::blas::AlgorithmType>>();
static int64_t cache_hits ABSL_GUARDED_BY(autotune_cache_mu) = 0;
static int64_t cache_misses ABSL_GUARDED_BY(autotune_cache_mu) = 0;

StatusOr<tensorflow::DataType> EncodePrimitiveTypeAsDataType(
    PrimitiveType type) {
  switch (type) {
    case PRED:
      return tensorflow::DT_BOOL;
    case BF16:
      return tensorflow::DT_BFLOAT16;
    case F16:
      return tensorflow::DT_HALF;
    case F32:
      return tensorflow::DT_FLOAT;
    case F64:
      return tensorflow::DT_DOUBLE;
    case C64:
      return tensorflow::DT_COMPLEX64;
    case C128:
      return tensorflow::DT_COMPLEX128;
    case S8:
      return tensorflow::DT_INT8;
    case S16:
      return tensorflow::DT_INT16;
    case S32:
      return tensorflow::DT_INT32;
    case S64:
      return tensorflow::DT_INT64;
    case U8:
      return tensorflow::DT_UINT8;
    case U16:
      return tensorflow::DT_UINT16;
    case U32:
      return tensorflow::DT_UINT32;
    case U64:
      return tensorflow::DT_UINT64;
    default:
      return InternalError("Unsupported type in EncodePrimitiveAsDataType.");
  }
}

Status DoBlasPlansAutotune(se::Stream* stream, const HloInstruction* instr,
                           se::DeviceMemoryAllocator* allocator,
                           const GemmBackendConfig& gemm_config) {
  TF_ASSIGN_OR_RETURN(GemmConfig config, GemmConfig::For(instr));

  const HloModuleConfig& hlo_module_config = instr->GetModule()->config();
  const int32_t cublas_autotune_level =
      hlo_module_config.debug_options().xla_gpu_autotune_level();
  const bool init_cublas_data = cublas_autotune_level >= 2;
  const bool reinit_cublas_data = cublas_autotune_level >= 3;
  const bool check_cublas = cublas_autotune_level >= 4;
  const bool crash_on_checking_failure =
      hlo_module_config.debug_options()
          .xla_gpu_crash_on_verification_failures();

  const int64_t redzone_size =
      check_cublas ? se::RedzoneAllocator::kDefaultRedzoneSize : 0;

  se::RedzoneAllocator input_output_allocator(
      stream, allocator,
      PtxOptsFromDebugOptions(hlo_module_config.debug_options()),
      /*memory_limit=*/std::numeric_limits<int64_t>::max(),
      /*redzone_size=*/redzone_size);
  int64_t rng_state = 0;
  auto get_initialized_buffer =
      [&](const HloInstruction* op) -> StatusOr<se::DeviceMemoryBase> {
    TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase buffer,
                        input_output_allocator.AllocateBytes(
                            ShapeUtil::ByteSizeOf(op->shape())));
    if (init_cublas_data) {
      InitializeBuffer(stream, op->shape().element_type(), &rng_state, buffer);
    }
    return buffer;
  };

  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase lhs_buffer,
                      get_initialized_buffer(instr->operand(0)));
  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase rhs_buffer,
                      get_initialized_buffer(instr->operand(1)));
  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase output_buffer,
                      get_initialized_buffer(instr));

  int64_t m = config.output_layout.num_rows;
  int64_t n = config.output_layout.num_cols;
  int64_t k = config.lhs_layout.num_cols;
  se::blas::MatrixDescriptor lhs = GetMatrixDesc(config.lhs_layout, lhs_buffer);
  se::blas::MatrixDescriptor rhs = GetMatrixDesc(config.rhs_layout, rhs_buffer);
  se::blas::MatrixDescriptor output =
      GetMatrixDesc(config.output_layout, output_buffer);
  int64_t batch_size = config.output_layout.batch_size;

  // TODO(cjfj): Support transposed output when using cuBLASLt.
  MakeBlasGemmCompatible(m, n, lhs, rhs, output);

  TF_ASSIGN_OR_RETURN(
      tensorflow::DataType dtype,
      EncodePrimitiveTypeAsDataType(config.output_layout.dtype));

  int device_id = stream->parent()->device_ordinal();
  bool trans_x = lhs.transpose == se::blas::Transpose::kTranspose;
  bool trans_y = rhs.transpose == se::blas::Transpose::kTranspose;
  bool broadcast = batch_size == 1;

  VLOG(4) << "matmul params: trans_x " << trans_x << " trans_y " << trans_y
          << " adj_x " << false << " adj_y " << false << " m " << m << " n "
          << n << " k " << k << " batch_size " << batch_size << " broadcast "
          << broadcast << " broadcast " << broadcast << " dtype " << dtype
          << " device_id " << device_id;

  se::BatchMatmulParameters matmul_parameters(
      trans_x, trans_y, false, false, m, n, k, batch_size,
      /*broadcast_a*/ broadcast, /*broadcast_b*/ broadcast, dtype, dtype,
      device_id);

  TF_ASSIGN_OR_RETURN(
      const se::blas::PlanAndAlgorithms* plan_and_algorithms,
      se::GetPlanAndAlgorithms(stream, matmul_parameters, batch_size, m, n, k,
                               dtype, lhs, rhs, output));

  const std::vector<std::unique_ptr<se::blas::IBlasLtMatmulAlgorithm>>&
      algorithms = plan_and_algorithms->algorithms;

  // Note that algorithm_config.algorithm() here is used to refer
  // to the index within the algorithms vector, not the algorithm
  // itself.
  se::blas::AlgorithmConfig algorithm_config(se::blas::kNoAlgorithm);
  if (!BlasPlansAutotuneCacheSingleton::GetInstance()->Find(
          matmul_parameters, &algorithm_config)) {
    VLOG(4) << "Autotuning BlasLtMatmul over " << algorithms.size()
            << " algorithms.";
    se::blas::ProfileResult best_result;
    se::blas::ProfileResult profile_result;

    for (size_t i = 0; i != algorithms.size(); ++i) {
      // Create a new scratch allocator with every autotuning run so that
      // scratch space is deallocated between runs.
      se::OwningScratchAllocator<> scratch_allocator(device_id, allocator);

      // Make sure the output buffer always has the same value if we use
      // the bias parameter.
      if (reinit_cublas_data && gemm_config.beta() != 0) {
        int64_t rng_state = 0;
        InitializeBuffer(stream, instr->shape().element_type(), &rng_state,
                         output_buffer);
      }

      TF_RETURN_IF_ERROR(
          RunGemm(config, lhs_buffer, rhs_buffer, output_buffer, stream,
                  /*scratch allocator=*/&scratch_allocator,
                  /*algorithm_being_profiled=*/algorithms[i].get(),
                  /*profile_result=*/&profile_result, absl::nullopt));

      VLOG(4) << "  Autotune algorithm " << i
              << " result: " << profile_result.elapsed_time_in_ms()
              << " ms, valid=" << profile_result.is_valid();

      if (profile_result.is_valid() && profile_result.elapsed_time_in_ms() <
                                           best_result.elapsed_time_in_ms()) {
        best_result = profile_result;
      }

      if (!check_cublas) {
        continue;
      }

      TF_ASSIGN_OR_RETURN(
          se::RedzoneAllocator::RedzoneCheckStatus rz_check_status,
          input_output_allocator.CheckRedzones());
      if (!rz_check_status.ok()) {
        LOG(ERROR) << "Detected cuBLASLT out-of-bounds write in gemm buffer";
        CHECK(!crash_on_checking_failure);
        continue;
      }
    }

    if (best_result.is_valid()) {
      algorithm_config.set_algorithm(best_result.algorithm());
    }
    se::blas::AlgorithmType algorithm_idx = algorithm_config.algorithm();
    CHECK(algorithm_idx >= 0 && algorithm_idx < algorithms.size())
        << "Missing/invalid BatchMatmul algorithm";
    // We make sure that each matmul parameter set only gets one pass of
    // autotune. If no algorithms works, we add kNoAlgorithm to the autotune
    // map.
    VLOG(4) << "Inserting algorithm id " << algorithm_config.algorithm()
            << " for " << trans_x << " " << trans_y << " " << m << " " << n
            << " " << k << " " << batch_size << " " << broadcast << " "
            << broadcast << " " << dtype << " " << device_id;
    BlasPlansAutotuneCacheSingleton::GetInstance()->Insert(matmul_parameters,
                                                           algorithm_config);
  }
  return Status::OK();
}

// Experimentally tries to pick the best algorithm for the given gemm.
//
// This may fail under perfectly normal circumstances.  In particular, it will
// fail if the program was built with < CUDA 8 or if we're using a gpu older
// than sm_50 -- in both cases, cublas doesn't support gemm-with-algorithm at
// all.
static StatusOr<absl::optional<se::blas::AlgorithmType>> DoUncachedGemmAutotune(
    const HloInstruction* gemm, se::Stream* stream,
    se::DeviceMemoryAllocator* allocator) {
  if (!stream->parent()->SynchronizeAllActivity()) {
    return InternalError("Failed to synchronize GPU for autotuning.");
  }

  const HloModuleConfig& hlo_module_config = gemm->GetModule()->config();
  const int32_t cublas_autotune_level =
      hlo_module_config.debug_options().xla_gpu_autotune_level();
  const bool init_cublas_data = cublas_autotune_level >= 2;
  const bool reinit_cublas_data = cublas_autotune_level >= 3;
  const bool check_cublas = cublas_autotune_level >= 4;

  const int64_t redzone_size =
      check_cublas ? se::RedzoneAllocator::kDefaultRedzoneSize : 0;
  se::RedzoneAllocator input_output_allocator(
      stream, allocator,
      PtxOptsFromDebugOptions(hlo_module_config.debug_options()),
      /*memory_limit=*/std::numeric_limits<int64_t>::max(),
      /*redzone_size=*/redzone_size);

  BufferComparator comparator(gemm->shape(), hlo_module_config);

  int64_t rng_state = 0;
  auto get_initialized_buffer =
      [&](const HloInstruction* op) -> StatusOr<se::DeviceMemoryBase> {
    TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase buffer,
                        input_output_allocator.AllocateBytes(
                            ShapeUtil::ByteSizeOf(op->shape())));
    if (init_cublas_data) {
      InitializeBuffer(stream, op->shape().element_type(), &rng_state, buffer);
    }
    return buffer;
  };

  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase lhs_buffer,
                      get_initialized_buffer(gemm->operand(0)));
  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase rhs_buffer,
                      get_initialized_buffer(gemm->operand(1)));
  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase output_buffer,
                      get_initialized_buffer(gemm));
  TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase reference_result_buffer,
                      get_initialized_buffer(gemm));

  const DebugOptions& debug_options =
      gemm->GetModule()->config().debug_options();

  const bool crash_on_checking_failure =
      debug_options.xla_gpu_crash_on_verification_failures();

  GemmBackendConfig backend_config =
      gemm->backend_config<GemmBackendConfig>().ValueOrDie();

  std::vector<se::blas::AlgorithmType> algorithms;
  CHECK(stream->parent()->GetBlasGemmAlgorithms(&algorithms));

  absl::optional<se::blas::AlgorithmType> first_algorithm;
  std::vector<AutotuneResult> profile_results;

  TF_ASSIGN_OR_RETURN(GemmConfig config, GemmConfig::For(gemm));

  for (se::blas::AlgorithmType algorithm : algorithms) {
    // Make sure the output buffer always has the same value if we use
    // the bias parameter.
    if (reinit_cublas_data && backend_config.beta() != 0) {
      int64_t rng_state = 0;
      InitializeBuffer(stream, gemm->shape().element_type(), &rng_state,
                       output_buffer);
    }
    se::blas::ProfileResult profile_result;

    // We expect GemmWithAlgorithm to fail sometimes -- in fact, it will fail
    // for all algorithms if we're targeting < sm_50.  But because we pass a
    // non-null ProfileResult, DoGemmWithAlgorithm should always return true,
    // and the actual success-ness is returned in ProfileResult::is_valid.
    Status st = RunGemm(config, lhs_buffer, rhs_buffer, output_buffer, stream,
                        /*scratch allocator=*/nullptr,
                        /* algorithm_being_profiled=*/nullptr,
                        /*profile_result=*/&profile_result, algorithm);
    CHECK(st.ok()) << st.ToString();

    if (!profile_result.is_valid()) {
      // Unsupported algorithm.
      continue;
    }

    profile_results.emplace_back();
    AutotuneResult& result = profile_results.back();
    result.mutable_gemm()->set_algorithm(algorithm);

    VLOG(2) << "cublas gemm algorithm " << algorithm << " took "
            << profile_result.elapsed_time_in_ms() << "ms" << std::endl;

    *result.mutable_run_time() = tensorflow::proto_utils::ToDurationProto(
        absl::Milliseconds(profile_result.elapsed_time_in_ms()));

    if (!check_cublas) {
      continue;
    }

    TF_ASSIGN_OR_RETURN(
        se::RedzoneAllocator::RedzoneCheckStatus rz_check_status,
        input_output_allocator.CheckRedzones());
    if (!rz_check_status.ok()) {
      result.mutable_failure()->set_kind(AutotuneResult::REDZONE_MODIFIED);
      *result.mutable_failure()->mutable_msg() =
          rz_check_status.RedzoneFailureMsg();
      LOG(ERROR) << "Detected cuBLAS out-of-bounds write in gemm buffer";
      CHECK(!crash_on_checking_failure);
      continue;
    }

    if (!first_algorithm) {
      // First run: set the reference result buffer.
      CHECK(reference_result_buffer.size() == output_buffer.size());
      stream->ThenMemcpy(&reference_result_buffer, output_buffer,
                         output_buffer.size());
      first_algorithm.emplace(algorithm);
    } else {
      // Perform the comparison.
      TF_ASSIGN_OR_RETURN(bool compare_result,
                          comparator.CompareEqual(stream, output_buffer,
                                                  reference_result_buffer));
      if (!compare_result) {
        LOG(ERROR) << "Results mismatch between different GEMM algorithms. "
                   << "This is likely a bug/unexpected loss of precision "
                   << "in cuBLAS.";
        CHECK(!crash_on_checking_failure);

        result.mutable_failure()->set_kind(AutotuneResult::WRONG_RESULT);
        result.mutable_failure()->mutable_reference_gemm()->set_algorithm(
            *first_algorithm);
      }
    }
  }

  tensorflow::AutotuningLog log;
  for (const AutotuneResult& profile : profile_results) {
    *log.add_results() = profile;
  }
  if (!crash_on_checking_failure) {
    tensorflow::Logger::GetSingleton()->LogProto(log);
  }

  StatusOr<AutotuneResult> autotune_result =
      PickBestResult(profile_results, *gemm);
  if (!autotune_result.ok()) {
    LOG(WARNING) << "Failed to find best cuBLAS algorithm, GEMM performance "
                    "might be suboptimal: "
                 << autotune_result.status();
    return {absl::nullopt};
  }
  return {autotune_result->gemm().algorithm()};
}

static StatusOr<absl::optional<se::blas::AlgorithmType>> DoGemmAutotune(
    const HloInstruction* instr, const GemmBackendConfig& gemm_config,
    se::DeviceMemoryAllocator* allocator, se::Stream* stream) {
  VLOG(3) << "Starting autotune of GemmThunk " << instr->ToString();
  const HloInstruction* lhs = instr->operand(0);
  const HloInstruction* rhs = instr->operand(1);

  TF_ASSIGN_OR_RETURN(GemmConfig config, GemmConfig::For(instr));
  // Don't run autotuning concurrently on the same GPU.
  absl::MutexLock gpu_lock(&GetGpuMutex(stream->parent()));

  if (config.use_cublaslt && stream->parent()->SupportsBlasPlans()) {
    TF_RETURN_IF_ERROR(
        DoBlasPlansAutotune(stream, instr, allocator, gemm_config));
    return {se::blas::kNoAlgorithm};
  } else {
    GemmCacheKey key =
        std::make_tuple(stream->parent(), lhs->shape(), rhs->shape(),
                        instr->shape(), gemm_config.SerializeAsString());

    absl::MutexLock cache_lock(&autotune_cache_mu);
    auto it = autotune_cache.find(key);
    int64_t autotuning_requests = cache_hits + cache_misses;
    if (autotuning_requests && autotuning_requests % 10 == 0) {
      VLOG(2) << "Autotuning cache hits/(hits + misses): " << cache_hits << "/"
              << autotuning_requests;
    }

    if (it != autotune_cache.end()) {
      cache_hits++;
      VLOG(4) << "Autotuning cache hit, using algorithm: "
              << (it->second.has_value() ? absl::StrCat(*(it->second))
                                         : "<generic>");
      return it->second;
    }
    cache_misses++;
    VLOG(4) << "Autotuning cache miss";

    // Make sure any previous activity on this executor is done. We don't want
    // other work still running on the GPU to interfere with autotuning.
    if (!stream->parent()->SynchronizeAllActivity()) {
      auto options = HloPrintOptions::Canonical();
      options.set_print_backend_config(true);
      return InternalError(
          "Failed to synchronize GPU for autotuning gemm instruction: %s",
          instr->ToString(options));
    }

    TF_ASSIGN_OR_RETURN(absl::optional<se::blas::AlgorithmType> result,
                        DoUncachedGemmAutotune(instr, stream, allocator));

    CHECK(autotune_cache.emplace(key, result).second);
    return result;
  }
}

static StatusOr<bool> RunOnInstruction(HloInstruction* instr,
                                       se::StreamExecutor* executor,
                                       se::DeviceMemoryAllocator* allocator) {
  if (allocator == nullptr) {
    allocator = executor->GetAllocator();
  }
  TF_ASSIGN_OR_RETURN(se::Stream* const stream,
                      allocator->GetStream(executor->device_ordinal()));

  GemmBackendConfig gemm_config =
      instr->backend_config<GemmBackendConfig>().ValueOrDie();

  TF_ASSIGN_OR_RETURN(absl::optional<se::blas::AlgorithmType> gemm_algorithm,
                      DoGemmAutotune(instr, gemm_config, allocator, stream));

  // We update instruction->backend_config(); if no algorithms are supported,
  // a different API is used, which does not require specifying an algorithm.
  GemmBackendConfig updated_config = gemm_config;
  if (gemm_algorithm) {
    VLOG(4) << "GEMM autotuning picked algorithm " << *gemm_algorithm << " for "
            << instr->name();
    updated_config.set_selected_algorithm(*gemm_algorithm);
  }
  TF_RETURN_IF_ERROR(instr->set_backend_config(updated_config));
  return updated_config.SerializeAsString() != gemm_config.SerializeAsString();
}

static StatusOr<bool> RunOnComputation(HloComputation* computation,
                                       se::StreamExecutor* se,
                                       se::DeviceMemoryAllocator* allocator) {
  bool changed = false;
  for (HloInstruction* instr : computation->instructions()) {
    if (IsCublasGemm(*instr)) {
      TF_ASSIGN_OR_RETURN(bool result, RunOnInstruction(instr, se, allocator));
      changed |= result;
    }
  }
  return changed;
}

StatusOr<bool> GemmAlgorithmPicker::Run(HloModule* module) {
  XLA_SCOPED_LOGGING_TIMER("GemmAlgorithmPicker");

  if (module->config().debug_options().xla_gpu_autotune_level() == 0) {
    VLOG(2) << "GEMM auto-tuning disabled, GemmAlgorithmPicker returning early";
    return false;
  }

  bool changed = false;
  for (HloComputation* computation : module->MakeNonfusionComputations()) {
    TF_ASSIGN_OR_RETURN(
        bool result, RunOnComputation(computation, stream_exec_, allocator_));
    changed |= result;
  }
  return changed;
}

}  // namespace gpu
}  // namespace xla


text:
sudo apt update

banner LaTeX
sudo apt install texlive-latex-extra -y

banner jabref
sudo snap install jabref


text:
package net.ripe.db.whois.update.mail;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.Session;
import java.util.Properties;

@Component
public class MailConfiguration {

    @Value("${mail.smtp.host}")
    private String smtpHost;

    @Value("${whois.update.mail.smtpPort:25}")
    private String smtpPort;

    @Value("${mail.from}")
    private String from;

    @Value("${whois.update.mail.debug:false}")
    private boolean debug;

    private Session session;

    public MailConfiguration() {}

    public MailConfiguration(final String from) {
        this.from = from;
    }

    @PostConstruct
    public void initSession() {
        final Properties props = new Properties();

        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

        session = Session.getInstance(props);
        session.setDebug(debug);
    }

    public Session getSession() {
        return session;
    }

    public String getFrom() {
        return from;
    }
}