text:
package org.jutility.math.geometry;

//@formatter:off

//@formatter:on

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;

/**
 * The {@code IScaleFactor} interface provides a contract for classes
 * implementing scaling in three dimensions.
 *
 * @param <T>
 *            the {@link Number} type of the {@code IScaleFactor}.
 *
 * @author Peter J. Radics
 * @version 0.1.2
 * @since 0.1.0
 */
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY,
        property = "implementingType")
@JsonSubTypes({ @JsonSubTypes.Type(value = ScaleFactor.class,
        name = "ScaleFactor") })
public interface IScaleFactor<T extends Number> {

    /**
     * Returns the type of this scale.
     *
     * @return the type.
     */
    Class<? extends T> getType();

    /**
     * Returns the scale factor for the x-dimension.
     *
     * @return the scale factor.
     */
    T getScaleFactorX();

    /**
     * Returns the scale factor for the y-dimension.
     *
     * @return the scale factor.
     */
    T getScaleFactorY();

    /**
     * Returns the scale factor for the z-dimension.
     *
     * @return the scale factor.
     */
    T getScaleFactorZ();
}


text:
<!--

-->
<input class="admin__control-text" type="text" data-bind="
    hasFocus: focused,
    datepicker: { storage: value, options: options },
    attr: {
        value: value,
        name: inputName,
        placeholder: placeholder,
        'aria-describedby': noticeId,
        disabled: disabled
    }" />

redpajama_set_name: RedPajamaGithub


text:
require 'hocho/utils/finder'

module Hocho
  module Drivers
    def self.find(name)
      Hocho::Utils::Finder.find(self, 'hocho/drivers', name)
    end
  end
end


text:
package main

import (
	"fmt"
	"html/template"
	"net/http"
	"os"
)

func handler(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("templates/page.html")
	if err != nil {
		panic(err)
	}
	t.Execute(w, nil)
}

func main() {
	port := os.Getenv("WEB_SERVER_PORT")
	if port == "" {
		port = ":8080"
	}
	fmt.Printf("Serving on port %s\n", port)
	http.HandleFunc("/", handler)
	err := http.ListenAndServe(port, nil)
	if err != nil {
		fmt.Printf("ListenAndServe exited with error %v\n", err)
	}
}


text:
namespace DataTanker
{

    /// <summary>
    /// Contains properties and methods of keys
    /// which is used to access the values in storage.
    /// </summary>
    public interface IKey
    {
    }
}


text:
export UserBox from './UserBox/UserBox';
export TestsList from './TestsList/TestsList';


text:
class QwtPlotRescaler;
class QLabel;
class Plot;

class MainWindow: public QMainWindow
{
    Q_OBJECT

public:
    enum RescaleMode
    {
        KeepScales,
        Fixed,
        Expanding,
        Fitting
    };

    MainWindow();

private Q_SLOTS:
    void setRescaleMode( int );
    void showRatio( double, double );

private:
    QWidget *createPanel( QWidget * );
    Plot *createPlot( QWidget * );

    QwtPlotRescaler *d_rescaler;
    QLabel *d_rescaleInfo;

    Plot *d_plot;
};

#endif


text:
The demo can be used to show how a serverless architecture can be designed using Azure Functions and storage queues. By decoupling the functions using the queues the functions can be individually developed and deployed without interrupting the flow of the application.

More context is given in [this presentation](https://www.slideshare.net/marcduiker/getting-started-with-serverless-architectures-using-azure-functions-80755768) I gave at TechDays 2017 in Amsterdam.

## Solution files

The ImageAnalysisApp solution contains an Azure Functions App with two functions:

- `ValidateBlobSize`, this function is triggered by messages on the `imagesinput` storage queue and checks the size of the image that is configured as input binding to the `images` blob container. If the blob is too big a message is placed on the `imagestoolarge` queue. The the blob is not too big a message is placed on the `imagestoanalyze` queue.
- `ImageAnalyzer`, this function is triggered by messages on the `imagestoanalyze` queue and uses the Azure Cognitive Services Computer Vision api to analyze the image that is configured as input binding. The results of the computer vision analysis are then placed on the `analysisresultstostore` queue.

The ImageUploader solution contains a console application that can be used to upload images from a local folder to the `imagesinput` queue.

## Creating the Function App & storage queues in Azure

The ImageAnalysisApp solution needs to run in a Azure Function App. You can either create this manually through the Azure portal or use these commands in the Azure CLI. In addition a separate storage account is created for the blob container and the 4 storage queues.

### Azure CLI: Function App commands

You can use these commands to create the Function App and the related storage account and resource group.

Before running the commands I recommend verifying in the Azure portal if the names for the Function App, resource groups and storage accounts are available.

`resourceGroup=functionsdemo-rg`

`location=westeurope`

`appStorage=functionappstorage`

`functionAppName=myfirstfunctionsdemo`

`az group create --name $resourceGroup --location $location`

`az storage account create --name $appStorage --location $location --resource-group $resourceGroup --sku Standard_LRS`

`az functionapp create --name $functionAppName --storage-account $appStorage --resource-group $resourceGroup --consumption-plan-location $location`

### Azure CLI: Blob container & Storage queues commands

Use these commands to create a separate storage account for the blob container and the queues:

`dataStorage=functiondatastorage`

`az storage account create --name $dataStorage --location $location --resource-group $resourceGroup --sku Standard_LRS`

`storageKey="$(az storage account keys list --account-name $dataStorage --resource-group $resourceGroup --query [0].value)"`

`az storage container create --name "images" --account-key $storageKey --account-name $dataStorage`

`az storage queue create --name "imagesinput" --account-key $storageKey --account-name $dataStorage`

`az storage queue create --name "imagestoolarge" --account-key $storageKey --account-name $dataStorage`

`az storage queue create --name "imagestoanalyze" --account-key $storageKey --account-name $dataStorage`

`az storage queue create --name "analysisresultstostore" --account-key $storageKey --account-name $dataStorage`

The following command will show the connection string which needs to be put in the Function App application settings:

`az storage account show-connection-string --resource-group $resourceGroup --name $dataStorage`

## Function App settings

Finally add the following application settings to the Function App:

- Key=`StorageConnectionString`, Value=_<ConnectionString of the $dataStorage account>_
- Key=`ComputerVisionApiKey`, Value=_<Api key of the Cognitive Services Computer Vision API>_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Septoria sorghi Padwick

### Remarks
null


text:
using System;
using System.IO;
using System.Text;
using TMPro;
using UnityEngine;

namespace EA4S.ReadingGame
{
    public class ReadingGameGame : MiniGame // ReadingGameGameGameGameGame!
    {
        public ReadingBarSet barSet;
        public GameObject blurredText;
        public GameObject circleBox;
        public ReadingGameAntura antura;
        public ReadingRadialWidget radialWidget;
        public Camera uiCamera;

        public int CurrentScore { get; private set; }
        public int CurrentQuestionNumber { get; set; }

        [HideInInspector]
        public bool isTimesUp;

        int lives = 3;
        public int Lives { get { return lives; } }

        [HideInInspector]
        public KaraokeSong alphabetSong;
        public AudioClip alphabetSongAudio;
        public TextAsset alphabetSongSrt;

        public int TimeToAnswer
        {
            get
            {
                return Mathf.RoundToInt(30 - 20 * ReadingGameConfiguration.Instance.Difficulty);
            }
        }

        public const int MAX_QUESTIONS = 5;
        static readonly float[] READING_STARS_THRESHOLDS_RATIOS = new float[] { 0.4f, 0.55f, 0.7f };

        public int GetStarsThreshold(int stars)
        {
            if (ReadingGameConfiguration.Instance.Variation == ReadingGameVariation.ReadAndAnswer)
            {
                return Mathf.FloorToInt(MAX_QUESTIONS * TimeToAnswer * READING_STARS_THRESHOLDS_RATIOS[stars - 1]);
            }

            if (alphabetSong == null)
                return int.MaxValue;

            var t = (int)(alphabetSong.GetSegmentsLength() / (4 - stars));
            return t;
        }

        public int CurrentStars
        {
            get
            {
                if (CurrentScore < GetStarsThreshold(1))
                    return 0;
                if (CurrentScore < GetStarsThreshold(2))
                    return 1;
                if (CurrentScore < GetStarsThreshold(3))
                    return 2;
                return 3;
            }
        }

        public ReadingGameInitialState InitialState { get; private set; }
        public ReadingGameQuestionState QuestionState { get; private set; }
        public ReadingGameReadState ReadState { get; private set; }
        public ReadingGameAnswerState AnswerState { get; private set; }
        public IQuestionPack CurrentQuestion { get; set; }

        protected override IGameConfiguration GetConfiguration()
        {
            return ReadingGameConfiguration.Instance;
        }

        protected override IGameState GetInitialState()
        {
            return InitialState;
        }

        protected override void OnInitialize(IGameContext context)
        {
            InitialState = new ReadingGameInitialState(this);
            QuestionState = new ReadingGameQuestionState(this);
            ReadState = new ReadingGameReadState(this);
            AnswerState = new ReadingGameAnswerState(this);

            if (ReadingGameConfiguration.Instance.Variation == ReadingGameVariation.AlphabetSong)
            {
                ISongParser parser = new AkrSongParser();

                using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(alphabetSongSrt.text)))
                {
                    alphabetSong = new KaraokeSong(parser.Parse(stream));
                }
            }

            radialWidget.Hide();
        }

        public void AddScore(int score)
        {
            CurrentScore += score;

            Context.GetOverlayWidget().SetStarsScore(CurrentScore);
        }

        public bool RemoveLife()
        {
            --lives;
            Context.GetOverlayWidget().SetLives(lives);

            if (lives == 0)
            {
                EndGame(CurrentStars, CurrentScore);
                return true;
            }
            return false;
        }
    }
}


text:
var csrf = $(document).find('meta[name="csrf-token"]');
$.ajaxSetup({
    headers: {
        'X-CSRF-Token': csrf.attr('content')
    }
});
$(document).ajaxComplete(function(event,xhr,options){
    $options = options;
    if (typeof($options.context) !== 'undefined'){
        $contex = $options.context;
        if (typeof($contex.element) !== 'undefined'){
            $element = $contex.element;
            var form = $element;
        }
    }
    $response = xhr.responseJSON;
    if (typeof($response)!=="undefined" && $response.type && ($response.message || $response.messages || $response.form_errors)) {

        if($response.message)
        {
            UIkit.notify($response.message, {status: $response.type, pos: 'bottom-center'});
        }
        else if($response.messages)
        {
            $.each($response.messages, function(index, value){
                UIkit.notify(value, {status: $response.type, pos: 'bottom-center'});
            });
        }
        else if($response.form_errors && (typeof(form) !== 'undefined') && form.length)
        {
            form.find('.md-input-danger, .md-input-wrapper-danger').removeClass('md-input-danger | md-input-wrapper-danger');
            form.find('span.uk-text-danger').remove();
            var $txtMesg = [];
            $.each($response.form_errors, function(index, value){
                var inputs = form.find('[name="'+index+'"], [id="'+index+'"]');
                var parent = $(inputs).closest('div.uk-form-item, div.uk-form-row');
                var wrapper = parent.find('.md-input-wrapper');
                parent.append(''+value+'');
                inputs.addClass('md-input-danger');
                wrapper.addClass('md-input-wrapper-danger');
                $.each(value, function(i, msg){
                    $txtMesg.push(msg);
                });
            });
            $.unique($txtMesg.sort());
            UIkit.notify($txtMesg.join('
 '), {status:'danger',pos:'bottom-center'})
        }
    };
});

var icheckItems = $('[icheck_toggle]');
$(function() {
    icheckItems.each(function (e) {
        var $this = this;
        if ($attr = $($this).attr('icheck_toggle')) {
            $options = UIkit.Utils.options($attr);
            if ($this.checked === true) {
                $($options.target).removeClass('uk-hidden');
            } else {
                $($options.target).addClass('uk-hidden');
            }
        }
    });
    $(icheckItems).on('ifChanged', function (e) {
        var $this = e.target;
        if ($attr = $($this).attr('icheck_toggle')) {
            $options = UIkit.Utils.options($attr);
            if ($this.checked === true) {
                $($options.target).removeClass('uk-hidden');
            } else {
                $($options.target).addClass('uk-hidden');
            }
        }
    });
    $('[ext_target_click]').on('click',function(e){
        $attr = $(this).attr('ext_target_click');
        $options = UIkit.Utils.options($attr);
        $($options.target).click();
        e.preventDefault();
    });
});

document.addEventListener('DOMContentLoaded', function () {
    if (Notification.permission !== "granted")
        Notification.requestPermission();
});
function browserNotify($data){
    if (!Notification) {
        alert('Desktop notifications not available in your browser. Try Chromium.');
        return;
    }

    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        if($data.head && $data.icon && $data.message){
            var notification = new Notification($data.head,{
                icon: $data.icon,
                body: $data.message
            });
        }
        notification.onclick = function (){
            //window.open("http://www.codesrich.com/display-notifications-from-web-applications");
        };
    }
}

$( document ).ready( function(){
    // Modial dialog for Delete confirmation
    $( document ).on('click', '[data-modal="ajaxConfirmDelete"], .ajaxConfirmDelete', function(e){
        var $delete_btn = $( this );
        e.preventDefault();
        UIkit.modal.confirm("Are you sure to delete this? All data will be lost and not be able to recover.", function() {
            // will be executed on confirm.
            location.href = $delete_btn.data( 'action' );
        });
    });

    // Ajax Toggle Activation/Deactivation
    $( document ).on( 'click', '[data-toggle=ajaxActivate]', function( e ) {
        e.preventDefault();
        $this = $(this);
        url = $this.attr('href') ? $this.attr('href') : $this.data('remote');
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            success:function(msg) {
                if(msg.type){
                    $this.attr( 'title', msg['data']['title'] );
                    $this.find('i').html(msg['data']['icon']);
                    if ( msg['data']['bg-class'] != '' )
                        $this.find('i').attr( 'class', '' ).addClass( msg['data']['bg-class'] );
                }
            }
        })
    } );

    // Modal dialog with remote content
    $(document).on('click', '[data-toggle="ajaxModal"], .ajaxModal', function(e) {
        $('#ajaxModal, .uk-modal').remove();

        e.preventDefault();
        var $this = $(this)
            , url = $this.data('remote') || $this.attr('href');

        window.modalFromURL(url);
    });

    // Logout handler
    $("a[href$='/logout']").on('click', function(e)
    {
        var textMsg = false;
        $.ajax({
            url: '/logout/check-outstanding-tasks',
            type: 'GET',
            cache: false,
            async: false,
            timeout: 30000,
            error: function(){
                return true;
            },
            success: function(msg){
                if(msg.type == 'fail'){
                    if(msg.items)
                        textMsg = 'Are you sure you wish to log out, there are '+msg.items+' outstanding actions on the log?';
                }
            }
        });
        if(textMsg)
            if(!confirm(textMsg))
                return false;
    });

    // Search bar
    var def_text_search = '
Please enter at least 3 characters
';
    var search_form = $('form[role="search"]');
    var search_input = search_form.find('input');
    var search_window = $("#search_results")
    var header_main_search_close = $('.header_main_search_close');
    search_form.on('submit',function(e){
        e.preventDefault();
        searchWord();
    });

    search_input.keyup(function(e)
    {
        e.preventDefault();
        searchWord();
    });

    header_main_search_close.on('click', function() {
        search_window.html('');
    })

    function searchWord(){
        var search_value = search_input.val();
        if(search_value.length > 2)
        {
            $.ajax({
                type: "POST",
                url: "/searching",
                data: {phrase: search_value},
                cache: false,
                success: function(html)
                {
                    search_window.html(html,function(){
                        $(this).show();
                    });
                }
            });
        } else if (search_value.length == 0) {
            search_window.html('');
        } else {
            search_window.html(def_text_search);
        }
    }

    $(document).on('click keydown', function(e) {
        if( $body.hasClass('main_search_active') ) {
            if (
                ( !$(e.target).closest('.header_main_search_form').length && !$(e.target).closest('#main_search_btn').length )
                || ( e.which == 27 )
            ) {
                search_window.html('');
            }
        }
    });

    // Modal with content from a URL
    window.modalFromURL = function(url) {
        var $modal = $('

');
        $('body').append($modal);
        $modal.load(url, function(data){
            var modal = UIkit.modal($modal);
            modal.show();
            try {
                json = $.parseJSON(data);
            } catch (e) {
                json = false;
            }
            if(json && (json.type).length){
                if (json.type == 'error' || json.type == 'fail') {
                    $('#ajaxModal, .modal, .modal-backdrop, .bootstrap-datetimepicker-widget').remove();
                    return notyMsg(json.type, json.msg);
                }
            }
        });
    }

    // Notify Helper
    window.notifyResponse = function( data ) {
        if ( 'success' == data.type ) {
            UIkit.notify({
                message : data.msg.toString(),
                status  : 'success',
                timeout : 5000,
                pos     : 'bottom-right'
            });
        } else if ( 'error' == data.type ) {
            UIkit.notify({
                message : data.msg.toString(),
                status  : 'danger',
                timeout : 5000,
                pos     : 'bottom-right'
            });
            if ( 'undefined' !== data.errors ) {
                for (var property in data.errors) {
                    if (data.errors.hasOwnProperty(property)) {
                        UIkit.notify({
                            message : data.errors[property].toString(),
                            status  : 'danger',
                            timeout : 5000,
                            pos     : 'bottom-right'
                        });
                    }
                }
            }
        }
    }

    $.fn.updateNestable = function() {
        var $list = $( this );
        var url = $list.data( 'url' );
        var nestable = $list.data('nestable');
        if ( JSON ) {
            var output = JSON.stringify( nestable.serialize() );
            $.ajax({
                url: url,
                type: "POST",
                data: output,
                contentType: "application/json",
                success:function(data){
                    if ( ('undefined' !== typeof data.type) && data.type != 'success' )
                        window.notifyResponse( data );
                }
            });
        } else {
            alert( 'JSON browser support required for this application.' );
        }
    }

});

wysiwyg_tinymce =
{
    init: function()
    {
        if(typeof(tinymce) !== 'undefined')
        {
            tinymce.editors = [];
        };
        wysiwyg_tinymce._uploadOnly();
        wysiwyg_tinymce._uploadBasic();
        wysiwyg_tinymce._basic();
        wysiwyg_tinymce._minimal();
        wysiwyg_tinymce._text();
    },
    _elFinderBrowser: function(field_name, url, type, win)
    {
        tinymce.activeEditor.windowManager.open({
            file: '/elfinder/tinymce',
            title: 'Navitas Filemanager',
            width: 900,
            height: 450,
            resizable: 'no'
        }, {
            setUrl: function (url) {
                win.document.getElementById(field_name).value = url;
            }
        });
        return false;
    },
    _uploadOnly: function()
    {
        var $tinymce = "textarea[wyswig='only-upload']";
        if($($tinymce).length)
        {
            tinymce.init({
                selector: $tinymce,
                height: 200,
                force_br_newlines: false,
                force_p_newlines: false,
                forced_root_block: '',
                menubar: false,
                statusbar: false,
                toolbar1: "image media",
                plugins: ["link paste image imagetools  media"],
                relative_urls: false,
                remove_script_host: false,
                file_browser_callback: wysiwyg_tinymce._elFinderBrowser,
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                }
            });
        }
    },
    _uploadBasic: function()
    {
        var $tinymce = "textarea[wyswig='basic-upload']";
        if($($tinymce).length)
        {
            tinymce.init({
                selector: $tinymce,
                height: 200,
                force_br_newlines: false,
                force_p_newlines: false,
                forced_root_block: '',
                menubar: false,
                statusbar: false,
                theme: "modern",
                toolbar: "fontselect fontsizeselect | insertfile bold italic | alignleft aligncenter alignright alignjustify | table | link image  media",
                plugins: ["link paste imagetools image  media table"],
                relative_urls: false,
                remove_script_host: false,
                file_browser_callback: wysiwyg_tinymce._elFinderBrowser,
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                }
            });
        }
    },
    _basic: function()
    {
        var $tinymce = "textarea[wyswig='basic']";
        if($($tinymce).length)
        {
            tinymce.init({
                selector: $tinymce,
                height: 200,
                force_br_newlines: false,
                force_p_newlines: false,
                forced_root_block: '',
                menubar: false,
                statusbar: false,
                toolbar_items_size : 'small',
                toolbar1: "undo redo | styleselect | bold italic | forecolor | bullist numlist | alignleft aligncenter alignright alignjustify",
                plugins: ["paste,textcolor"],
                relative_urls: false,
                remove_script_host: false,
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                }
            });
        }
    },
    _minimal: function()
    {
        var $tinymce = "textarea[wyswig='minimal']";
        if($($tinymce).length)
        {
            tinymce.init({
                selector: $tinymce,
                height: 200,
                force_br_newlines: false,
                force_p_newlines: false,
                forced_root_block: '',
                menubar: false,
                statusbar: false,
                toolbar1: "bold italic",
                plugins: ["paste"],
                relative_urls: false,
                remove_script_host: false,
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                }
            });
        }
    },
    _text: function()
    {
        var $tinymce = "textarea[wyswig='text']";
        if($($tinymce).length)
        {
            tinymce.init({
                selector: $tinymce,
                force_br_newlines: false,
                force_p_newlines: false,
                forced_root_block: '',
                menubar: false,
                statusbar: false,
                toolbar: false,
                plugins: ["paste"],
                relative_urls: false,
                remove_script_host: false,
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                }
            });
        }
    }
};


text:
package org.maproulette.framework.controller

import java.net.URLDecoder

import javax.inject.Inject
import org.maproulette.exception.{NotFoundException, InvalidException}
import org.maproulette.data._
import org.maproulette.framework.model.{Task, Tag}
import org.maproulette.framework.service.{TaskBundleService, ServiceManager, TagService}
import org.maproulette.framework.mixins.TagsControllerMixin
import org.maproulette.session.SessionManager
import play.api.libs.json._
import play.api.mvc._

//// deprecated and to be removed after conversion
import org.maproulette.models.dal.TaskDAL
import org.maproulette.models.dal.mixin.TagDALMixin

class TaskBundleController @Inject() (
    override val sessionManager: SessionManager,
    override val actionManager: ActionManager,
    override val bodyParsers: PlayBodyParsers,
    service: TaskBundleService,
    val tagService: TagService,
    components: ControllerComponents,
    serviceManager: ServiceManager,
    taskDAL: TaskDAL
) extends AbstractController(components)
    with MapRouletteController
    with TagsControllerMixin[Task] {

  // json reads for automatically reading Tasks from a posted json body
  override implicit val tReads: Reads[Task] = Task.TaskFormat
  // json writes for automatically writing Tasks to a json body response
  override implicit val tWrites: Writes[Task] = Task.TaskFormat

  // For Tags
  implicit val tagType                        = Task.TABLE
  implicit val itemType: ItemType             = TaskType()
  override def dalWithTags: TagDALMixin[Task] = this.taskDAL

  /**
    * This performs setTaskStatus on a bundle of tasks.
    *
    * @param bundleId  The id of the task bundle
    * @param primaryId The id of the primary task for this bundle
    * @param status    The status id to set the task's status to
    * @param comment   An optional comment to add to the task
    * @param tags      Optional tags to add to the task
    * @return 400 BadRequest if status id is invalid or task with supplied id not found.
    *         If successful then 200 NoContent
    */
  def setBundleTaskStatus(
      bundleId: Long,
      primaryId: Long,
      status: Int,
      comment: String = "",
      tags: String = ""
  ): Action[AnyContent] = Action.async { implicit request =>
    this.sessionManager.authenticatedRequest { implicit user =>
      val requestReview = request.getQueryString("requestReview") match {
        case Some(v) => Some(v.toBoolean)
        case None    => None
      }

      val tasks = this.serviceManager.taskBundle.getTaskBundle(user, bundleId).tasks match {
        case Some(t) => t
        case None    => throw new InvalidException("No tasks found in this bundle.")
      }

      val completionResponses = request.body.asJson
      this.taskDAL.setTaskStatus(
        tasks,
        status,
        user,
        requestReview,
        completionResponses,
        Some(bundleId),
        Some(primaryId)
      )

      for (task <- tasks) {
        val action = this.actionManager
          .setAction(Some(user), new TaskItem(task.id), TaskStatusSet(status), task.name)
        // add comment to each task if any provided
        if (comment.nonEmpty) {
          val actionId = action match {
            case Some(a) => Some(a.id)
            case None    => None
          }
          this.serviceManager.comment.create(user, task.id, comment, actionId)
        }

        // Add tags to each task
        val tagList = tags.split(",").toList
        if (tagList.nonEmpty) {
          this.addTagstoItem(task.id, tagList.map(new Tag(-1, _, tagType = this.tagType)), user)
        }
      }

      // Refetch to get updated data
      Ok(Json.toJson(this.serviceManager.taskBundle.getTaskBundle(user, bundleId)))
    }
  }

  /**
    * This function sets the task review status.
    * Must be authenticated to perform operation and marked as a reviewer.
    *
    * @param id           The id of the task
    * @param reviewStatus The review status id to set the task's review status to
    * @param comment      An optional comment to add to the task
    * @param tags         Optional tags to add to the task
    * @param newTaskStatus  Optional new taskStatus to change on all tasks in bundle
    * @return 400 BadRequest if task with supplied id not found.
    *         If successful then 200 NoContent
    */
  def setBundleTaskReviewStatus(
      id: Long,
      reviewStatus: Int,
      comment: String = "",
      tags: String = "",
      newTaskStatus: String = ""
  ): Action[AnyContent] = Action.async { implicit request =>
    this.sessionManager.authenticatedRequest { implicit user =>
      val tasks = this.serviceManager.taskBundle.getTaskBundle(user, id).tasks match {
        case Some(t) => {
          // If the mapper wants to change the task status while revising the task after review
          if (!newTaskStatus.isEmpty) {
            val taskStatus = newTaskStatus.toInt

            for (task <- t) {
              // Make sure to remove user's score credit for the prior task status first.
              this.serviceManager.userMetrics.rollbackUserScore(task.status.get, user.id)
            }

            // Change task status. This will also credit user's score for new task status.
            this.taskDAL.setTaskStatus(t, taskStatus, user, Some(false))
            val updatedTasks = this.serviceManager.taskBundle.getTaskBundle(user, id).tasks match {
              case Some(t) => t
              case None    => throw new InvalidException("No tasks found in this bundle.")
            }

            for (task <- t) {
              this.actionManager
                .setAction(Some(user), new TaskItem(task.id), TaskStatusSet(taskStatus), task.name)
            }
            updatedTasks
          } else t
        }
        case None => throw new InvalidException("No tasks found in this bundle.")
      }

      for (task <- tasks) {
        val action = this.actionManager.setAction(
          Some(user),
          new TaskItem(task.id),
          TaskReviewStatusSet(reviewStatus),
          task.name
        )
        val actionId = action match {
          case Some(a) => Some(a.id)
          case None    => None
        }

        this.serviceManager.taskReview
          .setTaskReviewStatus(task, reviewStatus, user, actionId, comment)

        if (tags.nonEmpty) {
          val tagList = tags.split(",").toList
          if (tagList.nonEmpty) {
            this.addTagstoItem(id, tagList.map(new Tag(-1, _, tagType = this.tagType)), user)
          }
        }
      }

      // Refetch to get updated data
      Ok(Json.toJson(this.serviceManager.taskBundle.getTaskBundle(user, id)))
    }
  }

  /**
    * This function sets the meta review status.
    * Must be authenticated to perform operation and marked as a reviewer.
    *
    * @param id           The id of the task
    * @param reviewStatus The review status id to set the task's review status to
    * @param comment      An optional comment to add to the task
    * @param tags         Optional tags to add to the task
    * @return 400 BadRequest if task with supplied id not found.
    *         If successful then 200 NoContent
    */
  def setBundleMetaReviewStatus(
      id: Long,
      reviewStatus: Int,
      comment: String = "",
      tags: String = ""
  ): Action[AnyContent] = Action.async { implicit request =>
    this.sessionManager.authenticatedRequest { implicit user =>
      val tasks = this.serviceManager.taskBundle.getTaskBundle(user, id).tasks match {
        case Some(t) => t
        case None    => throw new InvalidException("No tasks found in this bundle.")
      }

      for (task <- tasks) {
        val action = this.actionManager.setAction(
          Some(user),
          new TaskItem(task.id),
          MetaReviewStatusSet(reviewStatus),
          task.name
        )
        val actionId = action match {
          case Some(a) => Some(a.id)
          case None    => None
        }

        this.serviceManager.taskReview
          .setMetaReviewStatus(task, reviewStatus, user, actionId, comment)

        if (tags.nonEmpty) {
          val tagList = tags.split(",").toList
          if (tagList.nonEmpty) {
            this.addTagstoItem(id, tagList.map(new Tag(-1, _, tagType = this.tagType)), user)
          }
        }
      }

      // Refetch to get updated data
      Ok(Json.toJson(this.serviceManager.taskBundle.getTaskBundle(user, id)))
    }
  }

  /**
    * Creates a new task bundle with the task ids in the json body, assigning
    * ownership of the bundle to the logged-in user
    *
    * @return A TaskBundle representing the new bundle
    */
  def createTaskBundle(): Action[JsValue] = Action.async(bodyParsers.json) { implicit request =>
    this.sessionManager.authenticatedRequest { implicit user =>
      val name = (request.body \ "name").asOpt[String].getOrElse("")
      val taskIds = (request.body \ "taskIds").asOpt[List[Long]] match {
        case Some(tasks) => tasks
        case None        => throw new InvalidException("No task ids provided for task bundle")
      }
      val bundle = this.serviceManager.taskBundle.createTaskBundle(user, name, taskIds)
      Created(Json.toJson(bundle))
    }
  }

  /**
    * Gets the tasks in the given Bundle
    *
    * @param id The id for the bundle
    * @return Task Bundle
    */
  def getTaskBundle(id: Long): Action[AnyContent] = Action.async { implicit request =>
    this.sessionManager.authenticatedRequest { implicit user =>
      Ok(Json.toJson(this.serviceManager.taskBundle.getTaskBundle(user, id)))
    }
  }

  /**
    * Remove tasks from a bundle.
    *
    * @param id      The id for the bundle
    * @param taskIds List of task ids to remove
    * @return Task Bundle
    */
  def unbundleTasks(id: Long, taskIds: List[Long]): Action[AnyContent] = Action.async {
    implicit request =>
      this.sessionManager.authenticatedRequest { implicit user =>
        this.serviceManager.taskBundle.unbundleTasks(user, id, taskIds)
        Ok(Json.toJson(this.serviceManager.taskBundle.getTaskBundle(user, id)))
      }
  }

  /**
    * Delete bundle.
    *
    * @param id        The id for the bundle
    * @param primaryId optional task id to no unlock after deleting this bundle
    */
  def deleteTaskBundle(id: Long, primaryId: Option[Long] = None): Action[AnyContent] =
    Action.async { implicit request =>
      this.sessionManager.authenticatedRequest { implicit user =>
        this.serviceManager.taskBundle.deleteTaskBundle(user, id, primaryId)
        Ok
      }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <meta http-equiv="CONTENT-TYPE" content="text/html; charset=UTF-8">
  <title>glideinWMS - Factory</title>
  <meta name="CREATED" content="0;0">
  <meta name="CHANGED" content="20100521;20081031;14115200">
  <link rel="stylesheet" type="text/css" href="../common/glideinWMS.css" media="screen, projection" />

        GlideinWMS
	The Glidein-based Workflow Management System

 Home

 WMS Factory

 Design

Entry Internals

 Home

 Download

 Glidein Frontend

 Corral Frontend

 WMS Factory

 Components

 Recipes

 FAQ

Loading

Search Results

    <map name="rightimage">
        <area shape="rect" coords="90,3,177,60" href="../frontend/index.html" />
        <area shape="rect" coords="5,88,118,146" href="../components/collector_install.html" />
        <area shape="rect" coords="134,88,275,146" href="../factory/index.html" />
        <area shape="rect" coords="189,3,274,60" target="_blank" href="../corral.html" />
    </map>

WMS Factory Design

 Overview

 Install

 Configuration

 Design

 Monitoring

 Troubleshooting

Entry Internals

Jump to:

Program flow

Find and perform work

Advertise myself

Write statistics

Source code distribution

Configuration files

Factory Design Topics:

 Factory Internals

 Entry Internals

 Glidein Internals

 Data Exchange

Program flow

The Factory Entry Daemon is based on the polling principle; it
runs in an eternal loop as described in the picture below.

The
configuration is read only once, at daemon startup, so a restart is
needed for every configuration change.
However, the daemon does
check the downtime file at every iteration, so a change to the
downtime configuration file does not need any further action on the
daemon.

Most stages are self explanatory, so they will not be described to
further detail. However a few need more detail; in particular:

Find and perform work

Advertise myself

Write statistics

Find and perform work

This stage is composed of three logical parts, as shown in the
picture below:

Find the requests by querying the HTCondor
    Collector

For each request:

Keep the required number of idle jobs in the HTCondor
        Schedd (G) queue

Extract the statistics

This stage requires two input fields, the configuration data and
the downtime flag, and returns the request-specific job statistics.

It also communicates with external HTCondor daemons. To talk to
them, it currently uses the HTCondor command line tools:

condor_status to query the HTCondor Collector

condor_q to query the HTCondor Schedd

condor_submit to submit new jobs to and to release held jobs in the HTCondor Schedd

The requests are inserted into the HTCondor Collector by the VO
frontends. The picture below shows the format of the request as
present in the Collector.

Advertise myself

The advertise stage advertises the existence of the Entry Daemon
and its statistics to the HTCondor
Collector.
Two classes of ClassAds are sent, one for the
Entry Daemon itself, and one for every processed event. The two types
of ClassAds are shown in the pictures below.

The current implementation uses a HTCondor provided command line
tool, namely condor_advertise,
for this task.

Write statistics

The write statistics stage converts the in-memory statistics into
files in the Web exported monitoring area, as shown in the picture
below.

The data is written both in a XML file and
as entries in RRD
archives.

The XML data can be used by other applications, while the
RRD archives can be viewed using the provided HTML pages based
on JavascriptRRD
and Flot.

The current implementation will use the Python RRDTool
library, if available. Else, it will fall back to the command
line tool.

Source code distribution

The Factory Entry Daemons are implemented as python scripts, and
they don't need to be pre-compiled.

The code is spread over several Python modules, some specific to
the factory other shared between different parts of the GlideinWMS. A
shell script is also used.
There are also some external
dependencies, namely the rrdtool
and M2Crypto
python libraries and the HTCondor
command line binaries.

The picture below shows the dependency tree.

glideFactoryEntry.py
is executable.

The GlideinWMS common libraries are in glideinWMS/lib
directory.
The shell script is located in the root directory of
the factory tree, copied there during the creation
of the tree itself.

Configuration files

The Factory Entry Daemons have configuration files both in the
root of the factory configuration tree as well as in the entry
specific subdirectory. The configuration files in the root are common
for all the entry points, while the ones in the entry subdirectory
are specific to that Entry Daemon.

Warning: The configuration files should never be changed by
hand. They are generated and maintained by a
dedicated tool.

Shared configuration files

The configuration files in the root of the factory configuration
tree are shared between all the Factory Entry Daemons.

The following files are used:

<TT>glidein.descript</TT> – This file contains the factory
    description.
Most of the elements are used. Follows the
    description of the most important ones:

FactoryName and GlideinName – The factory name used when
        advertising the Entry Daemon.

WebURL – Where are the
        glidein support files
        located.

PubKeyType – Should I use encrypted IPC and if so, using
        which algorithm.

DowntimeFile – The name of the file containing all the factory
        downtimes. Usually defaults to “glideinWMS.downtimes”.

LoopDelay and AdvertiseDelay – How much should it sleep
        between iterations, and the minimum collector update frequency.

<TT>params.cfg</TT> – This file contains the factory global
    default parameters.  These are for values the frontend will change, also published in the factory classad

Entry-specific configuration files

The configuration files in the entry-specific subdirectory are
used by only one Entry Daemon.

The following files are used:

<TT>job.descript</TT> – This file contains the entry
    description.  It is used by the factory entry daemon in order to
    decide how to do work.

All the elements are used. Follows the description
    of the most important ones:

EntryName – The entry name used when advertising the Entry
        Daemon.

ScheddName – The HTCondor Schedd
        used to submit jobs.

SubmitCluster – How many jobs should I submit in a single
        submission.

MaxIdle, MaxGlideins, MaxHeld – Limits on the number of
        jobs in the HTCondor Schedd
        queue.

MaxSubmitRate, MaxRemoveRate, MaxReleaseRate, SubmitSleep,
        RemoveSleep, ReleaseSleep – Knobs to limit the interaction with
        the HTCondor Schedd.

DowntimeFile – The name of the file containing all the
        factory downtimes. Usually defaults to “glideinWMS.downtimes”.

<TT>job.condor</TT> – A condor description file that is
    used for submitting the jobs using condor_submit.

<TT>params.cfg</TT> – This file contains the entry-specific
    default parameters. These are for values the frontend will change, also published in the factory classad

<tt>attributes.cfg</tt> - This file contains fixed values; these are published in the factory classad

<TT>infosys.descript</TT> – This file contains the
    reference to the information system that contains the information of
    this entry point.

Banner image by
Madhusudan Katti
used under Creative Commons license.

Original Home URL: http://www.uscms.org/SoftwareComputing/Grid/WMS/glideinWMS.
glideinWMS email support: glideinwms-support at fnal.gov


text:
package docker

import (
	"bytes"
	"io"
	"io/ioutil"

	"github.com/containerd/containerd/errdefs"
	"github.com/containerd/containerd/log"
	"github.com/pkg/errors"
)

type httpReadSeeker struct {
	size   int64
	offset int64
	rc     io.ReadCloser
	open   func(offset int64) (io.ReadCloser, error)
	closed bool
}

func newHTTPReadSeeker(size int64, open func(offset int64) (io.ReadCloser, error)) (io.ReadCloser, error) {
	return &httpReadSeeker{
		size: size,
		open: open,
	}, nil
}

func (hrs *httpReadSeeker) Read(p []byte) (n int, err error) {
	if hrs.closed {
		return 0, io.EOF
	}

	rd, err := hrs.reader()
	if err != nil {
		return 0, err
	}

	n, err = rd.Read(p)
	hrs.offset += int64(n)
	return
}

func (hrs *httpReadSeeker) Close() error {
	if hrs.closed {
		return nil
	}
	hrs.closed = true
	if hrs.rc != nil {
		return hrs.rc.Close()
	}

	return nil
}

func (hrs *httpReadSeeker) Seek(offset int64, whence int) (int64, error) {
	if hrs.closed {
		return 0, errors.Wrap(errdefs.ErrUnavailable, "Fetcher.Seek: closed")
	}

	abs := hrs.offset
	switch whence {
	case io.SeekStart:
		abs = offset
	case io.SeekCurrent:
		abs += offset
	case io.SeekEnd:
		if hrs.size == -1 {
			return 0, errors.Wrap(errdefs.ErrUnavailable, "Fetcher.Seek: unknown size, cannot seek from end")
		}
		abs = hrs.size + offset
	default:
		return 0, errors.Wrap(errdefs.ErrInvalidArgument, "Fetcher.Seek: invalid whence")
	}

	if abs < 0 {
		return 0, errors.Wrapf(errdefs.ErrInvalidArgument, "Fetcher.Seek: negative offset")
	}

	if abs != hrs.offset {
		if hrs.rc != nil {
			if err := hrs.rc.Close(); err != nil {
				log.L.WithError(err).Errorf("Fetcher.Seek: failed to close ReadCloser")
			}

			hrs.rc = nil
		}

		hrs.offset = abs
	}

	return hrs.offset, nil
}

func (hrs *httpReadSeeker) reader() (io.Reader, error) {
	if hrs.rc != nil {
		return hrs.rc, nil
	}

	if hrs.size == -1 || hrs.offset < hrs.size {
		// only try to reopen the body request if we are seeking to a value
		// less than the actual size.
		if hrs.open == nil {
			return nil, errors.Wrapf(errdefs.ErrNotImplemented, "cannot open")
		}

		rc, err := hrs.open(hrs.offset)
		if err != nil {
			return nil, errors.Wrapf(err, "httpReadSeeker: failed open")
		}

		if hrs.rc != nil {
			if err := hrs.rc.Close(); err != nil {
				log.L.WithError(err).Errorf("httpReadSeeker: failed to close ReadCloser")
			}
		}
		hrs.rc = rc
	} else {
		// There is an edge case here where offset == size of the content. If
		// we seek, we will probably get an error for content that cannot be
		// sought (?). In that case, we should err on committing the content,
		// as the length is already satisfied but we just return the empty
		// reader instead.

		hrs.rc = ioutil.NopCloser(bytes.NewReader([]byte{}))
	}

	return hrs.rc, nil
}


text:
package org.artifactory.repo.webdav.methods;

import org.artifactory.repo.webdav.WebdavMethod;
import org.artifactory.request.ArtifactoryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;

import static org.artifactory.repo.webdav.WebdavServiceImpl.INFINITY;

/**
 * @author Yoav Luft
 */
public abstract class AbstractWebdavMethod implements WebdavMethod {

    private static final Logger log = LoggerFactory.getLogger(AbstractWebdavMethod.class);

    /**
     * Get the ETag associated with a file.
     */
    static String getEtag(String resourceLength, String lastModified)
            throws IOException {
        return "W/\"" + resourceLength + "-" + lastModified + "\"";
    }

    protected int findDepth(ArtifactoryRequest request) {
        String depthStr = request.getHeader("Depth");
        if (depthStr == null) {
            return INFINITY;
        }
        switch (depthStr) {
            case "0":
                return 0;
            case "1":
                return 1;
            case "infinity":
                return INFINITY;
            default:
                return INFINITY;
        }
    }

    /**
     * resource type Return JAXP document builder instance.
     *
     * @return
     * @throws javax.servlet.ServletException
     */
    protected DocumentBuilder getDocumentBuilder() throws IOException {
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory;
        try {
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new IOException("JAXP document builder creation failed", e);
        }
        return documentBuilder;
    }

    protected void logWebdavRequest(Document document) throws TransformerException {
        if (log.isDebugEnabled()) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(writer));
            log.debug("Webdav request body:\n" + writer.toString());
        }
    }
}


text:
module CUDNN

using ..CUJulia

if is_windows()
    const libcudnn = Libdl.find_library(["cudnn64_6","cudnn64_5"])
else
    const libcudnn = Libdl.find_library(["libcudnn"])
end
isempty(libcudnn) && throw("CUDNN library cannot be found.")

const version = ccall((:cudnnGetVersion,libcudnn),Cint,())
const major = div(version, 1000)
const minor = div(version - major*1000, 100)

info("CUDNN version: $(version)")
include("../lib/$(CUJulia.major)$(CUJulia.minor)/libcudnn$(major)$(minor).jl")
include("../lib/$(CUJulia.major)$(CUJulia.minor)/libcudnn$(major)$(minor)_types.jl")

function checkstatus(status)
    status == CUDNN_STATUS_SUCCESS && return
    throw(unsafe_string(cudnnGetErrorString(status)))
end

datatype(::Type{Float32}) = CUDNN_DATA_FLOAT
datatype(::Type{Float64}) = CUDNN_DATA_DOUBLE
datatype(::Type{Float16}) = CUDNN_DATA_HALF

const handles = Ptr{Void}[]
function handle(x)
    dev = device(x) + 1
    while dev > length(handles)
        p = Ptr{Void}[0]
        cudnnCreate(p)
        push!(handles, p[1])
    end
    handles[dev]
end
atexit(() -> foreach(cudnnDestroy, handles))

include("cudnn/activation.jl")
#include("batchnorm.jl")
include("cudnn/convolution.jl")
include("cudnn/dropout.jl")
include("cudnn/filter.jl")
include("cudnn/math.jl")
include("cudnn/pooling.jl")
include("cudnn/rnn.jl")
include("cudnn/softmax.jl")
include("cudnn/tensor.jl")

end


text:
import * as React from 'react';
import { connect } from 'react-redux';
import { getPhotoById } from './actions/getPhotoById.action';
import { editPhoto } from './actions/editPhoto.action';
import { createPhoto } from './actions/createPhoto.action';
import { FormControl, Form, FormGroup, ControlLabel, Col, Button } from 'react-bootstrap';
import { extend, map } from 'lodash';
import { Link } from 'react-router-dom';
import { POINTERS } from '../../_shared/constants/constants';
import { PHOTO_FIELDS_VALIDATION } from '../../_shared/validations/validation-rules';
import { forIn } from 'lodash';

import { createFormValidation } from 'lc-form-validation';

const photoFormValidation = createFormValidation(PHOTO_FIELDS_VALIDATION);

class PhotoView extends React.Component<any, any> {
    private photoId: number;
    private statePreloader: boolean = false;

    constructor(props: any) {
        super(props);
        this.state = {
            photo: {},
            photoIsCreating: {isCreating: false},
            photoIsEditing: {isEditing: false},
            formErrors: {}
        };
    }

    public componentDidMount() {
        this.photoId = this.props.match.params.id;
        if (this.photoId) {
            this.props.onGetPhotoById(this.props.match.params.id);
        }
    }

    public componentWillReceiveProps(nextProps: any) {
        if (nextProps.photoIsCreating) {
            this.statePreloader = nextProps.photoIsCreating.isCreating;
        }
        if (nextProps.match.params.id) {
            this.setState({
                photo: nextProps.photo,
            });
        } else {
            this.setState({
                photo: {}
            });
        }
        if (nextProps.photoIsEditing) {
            this.statePreloader = nextProps.photoIsEditing.isEditing;
        }
    }

    public setErrorsToState(errors: any) {
        errors.forEach((item: any, i: number) => {
            switch (item.key) {
                case 'name':
                    this.setState({
                        formErrors: extend(this.state.formErrors, {name: item.errorMessage})
                    });
                    break;
                case 'tooltip':
                    this.setState({
                        formErrors: extend(this.state.formErrors, {tooltip: item.errorMessage})
                    });
                    break;
                case 'pointer':
                    this.setState({
                        formErrors: extend(this.state.formErrors, {pointer: item.errorMessage})
                    });
                    break;
                case 'image':
                    this.setState({
                        formErrors: extend(this.state.formErrors, {image: item.errorMessage})
                    });
                    break;
                default:
                    this.setState({
                        formErrors: {}
                    });
            }
        });
    }

    public render() {
        return (

                {this.preloader()}

                    {this.createEditTitle()}

                        <Button bsStyle='primary'>
                            <Link to={'/photos-list'}>Back to photos list</Link>
                        </Button>

                    <Form horizontal onSubmit={this.handleSubmit}>
                        <Col sm={6}>
                            <FormGroup controlId='formHorizontalName'>
                                <Col componentClass={ControlLabel} sm={3}>
                                    Name
                                </Col>
                                <Col sm={9}>
                                    <FormControl
                                        type='text'
                                        value={this.state.photo.name || ''}
                                        onChange={this.handleFullNameChange}
                                        placeholder='Name' />

{this.state.formErrors.name}

                                </Col>
                            </FormGroup>

                            <FormGroup controlId='formHorizontalTooltip'>
                                <Col componentClass={ControlLabel} sm={3}>
                                    Tooltip
                                </Col>
                                <Col sm={9}>
                                    <FormControl
                                        type='textarea'
                                        value={this.state.photo.tooltip || ''}
                                        content={this.state.photo.name}
                                        onChange={this.handleFullTooltipChange}
                                        placeholder='Tooltip' />

{this.state.formErrors.tooltip}

                                </Col>
                            </FormGroup>

                            <FormGroup controlId='formHorizontalPointer'>
                                <Col sm={3}>
                                    Check pointer
                                </Col>
                                <Col sm={9}>

                                        {map(POINTERS, (item, index) => {
                                            return

                                                <input id={`pointer_${item}`}
                                                       type={'radio'}
                                                       value={item}
                                                       onChange={this.handlePointerSelection}
                                                       checked = {this.state.photo.pointer === item}
                                                       name='pointer'/>
                                                <label className='custom-radio' htmlFor={`pointer_${item}`}>{item}

;
                                        })}

{this.state.formErrors.pointer}

                                </Col>
                            </FormGroup>

                            <FormGroup className='clearfix text-right'>
                                <Col smOffset={2} sm={10}>
                                    {this.createEditBtn()}
                                </Col>
                            </FormGroup>
                        </Col>
                        <Col sm={6}>

                                    Upload Photo
                                    <input type='file' name='preview' onChange={(e) => this._handleImageChange(e)}/>

                            {this.setImgPreview()}
                            {/**/}
                            {/*
{this.state.formErrors.preview}
*/}
                        </Col>
                    </Form>

        );
    }

    private handleFullNameChange = (e: any) => this.setState({photo: extend(this.state.photo, {name: e.target.value})});
    private handleFullTooltipChange = (e: any) => this.setState({photo: extend(this.state.photo, {tooltip: e.target.value})});
    private handlePointerSelection = (e: any) => this.setState({photo: extend(this.state.photo, {pointer: e.target.value})});

    private preloader() {
        if (this.statePreloader) {
            return

;
        }
    }

    private setImgPreview() {
        if (this.props.match.params.id && !this.state.photo.preview) {
            return <img src={`/uploads/${this.state.photo.file_image}`} alt=''/>;
        } else if (this.state.photo.preview) {
            return ;
        } else {
            return ;
        }
    }

    private _handleImageChange(e: any) {
        e.preventDefault();
        const reader = new FileReader();
        const file = e.target.files[0];
        reader.onloadend = () => this.setState({photo: extend(this.state.photo, {preview: reader.result})});
        reader.readAsDataURL(file);
        if (file) {
            this.setState({photo: extend(this.state.photo, {file_image: file})});
        }
    }

    private createEditBtn() {
        if (this.props.match.params.id) {
            return <Button bsStyle='success' type='submit'>Edit photo</Button>;
        }
        return <Button bsStyle='success' type='submit'>Create photo</Button>;
    }

    private createEditTitle() {
        if (this.props.match.params.id) {
            return
Edit photo
;
        }
        return
Create photo
;
    }

    private handleSubmit = (e: any) => {
        const data =  {
            name: this.state.photo.name || '',
            tooltip: this.state.photo.tooltip || '',
            pointer: this.state.photo.pointer || '',
            file_image: this.state.photo.file_image || ''
        };
        const formData = new FormData();
        forIn(data, (value, key) => formData.append(key, value));
        photoFormValidation
            .validateForm(data)
            .then((validationResult) => {
                if (validationResult.succeeded) {
                    this.props.onCreateEditPhoto(formData, this.photoId);
                    //
                } else {
                    this.setErrorsToState(validationResult.fieldErrors);
                }
            })
            .catch((error) => {
                console.log(error);
                // handle unexpected errors
            });

        e.preventDefault();
    }
}

function mapStateToProps(state: any) {
    return {
        photo: state.getPhotoById,
        photoIsCreating: state.createPhoto,
        photoIsEditing: state.editPhoto
    };
}

export default connect(
    mapStateToProps,
    dispatch => ({
        onGetPhotoById: (id: number) => {
            dispatch(getPhotoById(id));
        },
        onCreateEditPhoto: (data: any, photoId: number) => {
            if (photoId) {
                dispatch(editPhoto(data, photoId));
            } else {
                dispatch(createPhoto(data));
            }
        }
    })
)(PhotoView);


text:
.class Lcom/android/server/pm/ShutdownThread$CloseDialogReceiver;
.super Landroid/content/BroadcastReceiver;
.source "ShutdownThread.java"

# interfaces
.implements Landroid/content/DialogInterface$OnDismissListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/pm/ShutdownThread;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "CloseDialogReceiver"
.end annotation

# instance fields
.field public dialog:Landroid/app/Dialog;

.field private mContext:Landroid/content/Context;

# direct methods
.method constructor <init>(Landroid/content/Context;)V
    .locals 2
    .parameter "context"

    .prologue
    .line 267
    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    .line 268
    iput-object p1, p0, Lcom/android/server/pm/ShutdownThread$CloseDialogReceiver;->mContext:Landroid/content/Context;

    .line 269
    new-instance v0, Landroid/content/IntentFilter;

    const-string v1, "android.intent.action.CLOSE_SYSTEM_DIALOGS"

    invoke-direct {v0, v1}, Landroid/content/IntentFilter;-><init>(Ljava/lang/String;)V

    .line 270
    .local v0, filter:Landroid/content/IntentFilter;
    invoke-virtual {p1, p0, v0}, Landroid/content/Context;->registerReceiver(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;

    .line 271
    return-void
.end method

# virtual methods
.method public onDismiss(Landroid/content/DialogInterface;)V
    .locals 2
    .parameter "unused"

    .prologue
    .line 279
    iget-object v0, p0, Lcom/android/server/pm/ShutdownThread$CloseDialogReceiver;->mContext:Landroid/content/Context;

    invoke-virtual {v0, p0}, Landroid/content/Context;->unregisterReceiver(Landroid/content/BroadcastReceiver;)V

    .line 280
    invoke-static {}, Lcom/android/server/pm/ShutdownThread;->access$100()Ljava/lang/Object;

    move-result-object v1

    monitor-enter v1

    .line 281
    const/4 v0, 0x0

    :try_start_0
    invoke-static {v0}, Lcom/android/server/pm/ShutdownThread;->access$202(Z)Z

    .line 282
    monitor-exit v1

    .line 283
    return-void

    .line 282
    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 1
    .parameter "context"
    .parameter "intent"

    .prologue
    .line 275
    iget-object v0, p0, Lcom/android/server/pm/ShutdownThread$CloseDialogReceiver;->dialog:Landroid/app/Dialog;

    invoke-virtual {v0}, Landroid/app/Dialog;->cancel()V

    .line 276
    return-void
.end method


text:
module RuboCop
  module Cop
    module Style
      # This cop checks for use of the lambda.(args) syntax.
      #
      # @example
      #
      #  # bad
      #  lambda.(x, y)
      #
      #  # good
      #  lambda.call(x, y)
      class LambdaCall < Cop
        include ConfigurableEnforcedStyle

        def on_send(node)
          return unless node.receiver && node.method?(:call)

          if offense?(node)
            add_offense(node, :expression) { opposite_style_detected }
          else
            correct_style_detected
          end
        end

        private

        def offense?(node)
          explicit_style? && node.implicit_call? ||
            implicit_style? && !node.implicit_call?
        end

        def autocorrect(node)
          lambda do |corrector|
            if explicit_style?
              receiver = node.receiver.source
              replacement = node.source.sub("#{receiver}.", "#{receiver}.call")

              corrector.replace(node.source_range, replacement)
            else
              corrector.remove(node.loc.selector)
            end
          end
        end

        def message(_node)
          if explicit_style?
            'Prefer the use of `lambda.call(...)` over `lambda.(...)`.'
          else
            'Prefer the use of `lambda.(...)` over `lambda.call(...)`.'
          end
        end

        def implicit_style?
          style == :braces
        end

        def explicit_style?
          style == :call
        end
      end
    end
  end
end


text:
// Copyright (c) Aspose 2002-2021. All Rights Reserved.

using System.IO;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Packaging;
using NUnit.Framework;

namespace AsposeWordsVSOpenXML.OpenXML_features
{
    [TestFixture]
    public class SearchAndReplaceText : TestUtil
    {
        [Test]
        public static void SearchAndReplaceTextFeature()
        {
            using (WordprocessingDocument wordDoc =
                WordprocessingDocument.Open(MyDir + "Search and replace text.docx", true))
            {
                string docText;

                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                Regex regexText = new Regex("Hello world!");
                docText = regexText.Replace(docText, "Hi Everyone!");

                using (StreamWriter sw =
                    new StreamWriter(File.Create(ArtifactsDir + "Search and replace text - OpenXML.docx")))
                {
                    sw.Write(docText);
                }
            }
        }
    }
}


text:
import { DataSet } from './data-set';

export class Column {

  title: string = '';
  type: string = '';
  class: string = '';
  width: string = '';
  hide: boolean = false;
  isSortable: boolean = false;
  isEditable: boolean = true;
  isAddable: boolean = true;
  isFilterable: boolean = false;
  sortDirection: string = '';
  defaultSortDirection: string = '';
  editor: { type: string, config: any, component: any } = { type: '', config: {}, component: null };
  filter: { type: string, config: any, component: any } = { type: '', config: {}, component: null };
  renderComponent: any = null;
  compareFunction: Function;
  valuePrepareFunction: Function;
  filterFunction: Function;
  onComponentInitFunction: Function;

  constructor(public id: string, protected settings: any, protected dataSet: DataSet) {
    this.process();
  }

  getOnComponentInitFunction(): Function {
    return this.onComponentInitFunction;
  }

  getCompareFunction(): Function {
    return this.compareFunction;
  }

  getValuePrepareFunction(): Function {
    return this.valuePrepareFunction;
  }

  getFilterFunction(): Function {
    return this.filterFunction;
  }

  getConfig(): any {
    return this.editor && this.editor.config;
  }

  getFilterType(): any {
    return this.filter && this.filter.type;
  }

  getFilterConfig(): any {
    return this.filter && this.filter.config;
  }

  protected process() {
    this.title = this.settings['title'];
    this.class = this.settings['class'];
    this.width = this.settings['width'];
    this.hide = !!this.settings['hide'];
    this.type = this.prepareType();
    this.editor = this.settings['editor'];
    this.filter = this.settings['filter'];
    this.renderComponent = this.settings['renderComponent'];

    this.isFilterable = typeof this.settings['filter'] === 'undefined' ? true : !!this.settings['filter'];
    this.defaultSortDirection = ['asc', 'desc']
      .indexOf(this.settings['sortDirection']) !== -1 ? this.settings['sortDirection'] : '';
    this.isSortable = typeof this.settings['sort'] === 'undefined' ? true : !!this.settings['sort'];
    this.isEditable = typeof this.settings['editable'] === 'undefined' ? true : !!this.settings['editable'];
    this.isAddable=typeof this.settings['addable'] === 'undefined' ? true : !!this.settings['addable'];
    this.sortDirection = this.prepareSortDirection();

    this.compareFunction = this.settings['compareFunction'];
    this.valuePrepareFunction = this.settings['valuePrepareFunction'];
    this.filterFunction = this.settings['filterFunction'];
    this.onComponentInitFunction = this.settings['onComponentInitFunction'];
  }

  prepareType(): string {
    return this.settings['type'] || this.determineType();
  }

  prepareSortDirection(): string {
    return this.settings['sort'] === 'desc' ? 'desc' : 'asc';
  }

  determineType(): string {
    // TODO: determine type by data
    return 'text';
  }
}


text:
var async = require('async');
var fs = require('fs');
var _ = require('lodash');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');

var CON = {
    paths: {
        base: __dirname + '/',
        packedVideos: __dirname + '/videos-packed/',
        videoRefined: __dirname + '/videos-refined/',
        tempPath: __dirname + '/tmp-processing/'
    }
}

// body parser
var bodyParser = require('body-parser');

var backend = require(__dirname + '/backend/sql.js').backend;

backend.ensureDir(CON.paths.tempPath, true);
backend.ensureDir(CON.paths.packedVideos);

var parseVideo = function(videos) {
    var v = videos.pop();

    var runNext = function() {
        if (!videos.length) return;
        setImmediate(function() {
            parseVideo(videos);
        });
    }
    var p = CON.paths.videoRefined + v;
    if (!fs.existsSync(p)) runNext();

    var stat = fs.statSync(p);
    if (v.substr(0, 1) != '.') {
        if (stat.isDirectory()) {
            var clipV2Path = p + '/clip_v2/';

            if (!fs.existsSync(clipV2Path)) {
                runNext();
                return;
            }

            var jobs = [];
            var runningJob = 0, maxRunningJob = 1;
            var runJob = function() {
                if (jobs.length) {
                    var job = jobs.shift();
                    console.log('debug: job, ', job);
                    if (job.type == 'pack') {
                        backend.packVideo(job, function() {
                            runJob();
                        });
                    } else if (job.type == 'image') {
                        backend.image(job, function() {
                            runJob();
                        });
                    }
                } else {
                    runningJob --;
                    if (runningJob <= 0) {
                        runNext();
                    }
                }
            }

            var queueJob = function() {
                if (maxRunningJob <= runningJob) return;
                runningJob ++;
                setTimeout(function() {
                    runJob();
                }, 0);
            }

            var targetPath = CON.paths.packedVideos + v + '/';
            backend.ensureDir(targetPath);

            var clips = fs.readdirSync(clipV2Path);
            for (var clipIdx = 0; clipIdx < clips.length; clipIdx++) {
                var clip = clips[clipIdx];
                var nextClip = clips[clipIdx + 1];

                if (path.extname(clip) == '.mp4' && (!nextClip ||
                            path.extname(nextClip) == '.mp4'
                    )) {
                    if (!fs.existsSync(targetPath + nextClip)) {
                        jobs.push({
                            type: 'pack',
                            source: clipV2Path + clip,
                            target: targetPath + clip,
                            clipType: 'video',
                            vbitrate: '450k',
                            outputOptions: [
                                '-vf scale=-2:320'
                            ]
                        });
                    }

                    if (!fs.existsSync(targetPath + nextClip + '.jpg')) {
                        jobs.push({
                            type: 'image',
                            source: targetPath + clip,
                            path: targetPath,
                            filename: path.basename(clip, '.mp4') + '.jpg'
                        });
                    }
                }

            }

            var audioV2Path = p + '/audio_v2/';
            var sounds = fs.readdirSync(audioV2Path);
            console.log(sounds);
            sounds.forEach(function(clip, idx) {
                var nextClip = sounds[idx + 1];
                if (path.extname(clip) == '.mp4' &&
                    (!nextClip ||
                        (path.extname(nextClip) == '.mp4'
                            && !fs.existsSync(targetPath + nextClip)))
                    ) {
                    jobs.push({
                        type: 'pack',
                        source: audioV2Path + clip,
                        target: targetPath + clip,
                        clipType: 'audio',
                        abitrate: '72k'
                    })
                }
            })
            queueJob();
        } else {
            runNext();
        }
    } else {
        runNext();
    }
}

var allVideos = fs.readdirSync(CON.paths.videoRefined);
parseVideo(allVideos);


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DoseReferenceUID extends AbstractTag
{

    protected $Id = '300A,0013';

    protected $Name = 'DoseReferenceUID';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Dose Reference UID';

}


text:
/* global QUnit, sinon */
sap.ui.define([
	"sap/ui/core/ContextMenuSupport",
	"sap/ui/core/Control",
	"sap/ui/core/Element",
	"sap/ui/qunit/QUnitUtils",
	"sap/ui/thirdparty/jquery"
], function(ContextMenuSupport, Control, Element, QUnitUtils, jQuery) {
	"use strict";

	var MyControl = Control.extend("my.lib.MyControl", {
		metadata : {
			aggregations: { content: {type: "sap.ui.core.Control", multiple: false} }
		},

		renderer : {
			apiVersion: 2,
			render: function(oRenderManager, oControl) {
				oRenderManager.openStart("span", oControl).openEnd();
				oRenderManager.renderControl(oControl.getContent());
				oRenderManager.close("span");
			}
		}
	});

	var MyMenuControl = Control.extend("my.lib.MyMenuControl", {
		metadata : {
			interfaces: [
				"sap.ui.core.IContextMenu"
			],
			aggregations: { content: {type: "sap.ui.core.Control", multiple: false} }
		},

		renderer : {
			apiVersion: 2,
			render: function(oRenderManager, oControl) {
				oRenderManager.openStart("span").openEnd().close("span");
			}
		}
	});
	MyMenuControl.prototype.openAsContextMenu = function(){};

	ContextMenuSupport.apply(MyControl.prototype);

	QUnit.module("ContextMenuSupport", {
		beforeEach: function() {
			this.myControl = new MyControl("myControl");
			this.myMenuControl = new MyMenuControl("myMenu");

			this.myControl.placeAt("qunit-fixture");
			sap.ui.getCore().applyChanges();
		},
		afterEach: function() {
			this.myControl.destroy();
			this.myMenuControl.destroy();
		}
	});

	QUnit.test('Control has the new methods', function(assert) {
		assert.ok(this.myControl.setContextMenu, "Should have a setter for ContextMenu");
		assert.ok(this.myControl.getContextMenu, "Should have a getter for ContextMenu");
	});

	QUnit.test('setContextMenu twice should open the second menu', function(assert) {
		var oOpenStub = sinon.stub(MyMenuControl.prototype, "openAsContextMenu"),
			oSecondMenuControl = this.myMenuControl.clone();

		this.myControl.setContextMenu(this.myMenuControl);
		this.myControl.setContextMenu(oSecondMenuControl);
		QUnitUtils.triggerMouseEvent(this.myControl.getDomRef(), "contextmenu");

		assert.notOk(oOpenStub.calledOn(this.myMenuControl), "first menu should not be opened");
		assert.ok(oOpenStub.calledOn(oSecondMenuControl), "second menu should be opened");

		oOpenStub.restore();
		oSecondMenuControl.destroy();
	});

	QUnit.test("setContextMenu with null should remove the Context Menu", function(assert) {
		var oOpenStub = sinon.stub(MyMenuControl.prototype, "openAsContextMenu");

		this.myControl.setContextMenu(this.myMenuControl);
		this.myControl.setContextMenu(null);

		QUnitUtils.triggerMouseEvent(this.myControl.getDomRef(), "contextmenu");

		assert.notOk(oOpenStub.calledOn(this.myMenuControl), "first menu should not be opened");

		oOpenStub.restore();
	});

	QUnit.test("addEventDelegate should be called", function(assert) {
		var oAddEventDelegateStub = sinon.stub(MyControl.prototype, "addEventDelegate");

		this.myControl.setContextMenu(this.myMenuControl);

		assert.ok(oAddEventDelegateStub.called, "Delegate should be added");

		oAddEventDelegateStub.restore();
	});

	QUnit.test("addEventDelegate should not be called", function(assert) {
		var oFakeMenu = { "fake": "object" },
			oAddEventDelegateStub = sinon.stub(MyControl.prototype, "addEventDelegate");

		this.myControl.setContextMenu(oFakeMenu);

		assert.notOk(oAddEventDelegateStub.called, "Delegate should not be added");

		oAddEventDelegateStub.restore();
		oFakeMenu = null;
	});

	QUnit.test("addEventDelegate should not be called on elements that do not implement IContextMenu", function(assert) {
		var MyElement = Element.extend("my.lib.MyElement", {
			metadata : {}
		});

		ContextMenuSupport.apply(MyElement.prototype);

		var oElement = new MyElement("oElement");

		assert.notOk(oElement.setContextMenu, "Should not have a setter for ContextMenu");
		assert.notOk(oElement.getContextMenu, "Should not have a getter for ContextMenu");

		oElement.destroy();
	});

	QUnit.test("oncontextmenu should open ContextMenu", function(assert) {
		var oFakeEvent = jQuery.Event("oncontextmenu", { srcControl:  this.myControl }),
			oOpenStub = sinon.stub(MyMenuControl.prototype, "openAsContextMenu");

		this.myControl.setContextMenu(this.myMenuControl);
		QUnitUtils.triggerMouseEvent(this.myControl.getDomRef(), "contextmenu");

		assert.ok(oOpenStub.called, "open should be called");

		delete oFakeEvent.srcControl;
		oFakeEvent = null;
		oOpenStub.restore();
	});

	QUnit.test("getContextMenu should return the ContextMenu", function(assert) {
		this.myControl.setContextMenu(this.myMenuControl);

		assert.strictEqual(this.myControl.getContextMenu(), this.myMenuControl, "ContextMenu should be returned");
	});
});


text:
namespace irr
{
	namespace gui
	{

		//! constructor
		CGUIConsoleOverlay::CGUIConsoleOverlay(IGUIEnvironment* environment, IGUIElement* parent,
			s32 id, core::rect<s32> rectangle,
			irr::video::ITexture* topLeft, irr::video::ITexture* topRight,
			irr::video::ITexture* bottomLeft, irr::video::ITexture* bottomRight)
			: IGUIConsoleOverlay(environment, parent, id, rectangle), OverrideFont(0)
		{
#ifdef _DEBUG
			setDebugName("CGUIConsoleOverlay");
#endif
			ConsoleTopLeft = topLeft;
			ConsoleTopRight = topRight;
			ConsoleBottomLeft = bottomLeft;
			ConsoleBottomRight = bottomRight;

			// This element can be tabbed.
			setTabStop(false);
			setTabOrder(-1);
			IsEnabled = true;
			setAlignment(EGUI_ALIGNMENT::EGUIA_UPPERLEFT, EGUI_ALIGNMENT::EGUIA_UPPERLEFT,
					     EGUI_ALIGNMENT::EGUIA_LOWERRIGHT, EGUI_ALIGNMENT::EGUIA_LOWERRIGHT);
		}

		//! destructor
		CGUIConsoleOverlay::~CGUIConsoleOverlay()
		{
			if (OverrideFont)
				OverrideFont->drop();
		}

		//! called if an event happened.
		bool CGUIConsoleOverlay::OnEvent(const SEvent& event)
		{
			if (!isEnabled())
				return IGUIElement::OnEvent(event);

			switch (event.EventType)
			{
			case EET_KEY_INPUT_EVENT:
				break;
			case EET_GUI_EVENT:
				break;
			case EET_MOUSE_INPUT_EVENT:
				break;
			case EET_USER_EVENT:
				if (event.GUIEvent.EventType == EGET_ELEMENT_CLOSED)
				{
					disposedLock.lock();

					IGUIElement* elem = event.GUIEvent.Element;
					disposedChildren.push_back(elem);

					disposedLock.unlock();
				}
				break;
			default:
				break;
			}

			return Parent ? Parent->OnEvent(event) : false;
		}

		//! draws the element and its children
		void CGUIConsoleOverlay::draw()
		{
			if (!IsVisible)
				return;

			disposedLock.lock();

			for (list<IGUIElement*>::ConstIterator i = disposedChildren.begin(); i != disposedChildren.end(); ++i)
				removeChild(*i);

			disposedChildren.clear();

			disposedLock.unlock();

			if (Children.size() == 0)
				return;

			IGUISkin* skin = Environment->getSkin();
			video::IVideoDriver* driver = Environment->getVideoDriver();

			core::rect<s32> backingRect = getBackingRect();

			video::SColor col[4];
			col[0] = video::SColor(128, 0, 0, 0);
			col[1] = video::SColor(128, 0, 0, 0);
			col[2] = video::SColor(128, 0, 0, 0);
			col[3] = video::SColor(128, 0, 0, 0);

			core::dimension2d<u32> leftTopSize(0, 0);
			if (ConsoleTopLeft)
			{
				leftTopSize = ConsoleTopLeft->getSize();
				core::rect<s32> leftRect = backingRect;
				leftRect.LowerRightCorner.X = leftRect.UpperLeftCorner.X + leftTopSize.Width;
				leftRect.LowerRightCorner.Y = leftRect.UpperLeftCorner.Y + leftTopSize.Height;

				driver->draw2DImage(ConsoleTopLeft,
					leftRect,
					core::rect<s32>(0, 0, leftTopSize.Width, leftTopSize.Height), &leftRect,
					col, true);
			}

			core::dimension2d<u32> leftBottomSize(0, 0);
			if (ConsoleBottomLeft)
			{
				leftBottomSize = ConsoleBottomLeft->getSize();
				core::rect<s32> leftRect = backingRect;
				leftRect.LowerRightCorner.X = leftRect.UpperLeftCorner.X + leftBottomSize.Width;
				leftRect.UpperLeftCorner.Y = leftRect.LowerRightCorner.Y - leftBottomSize.Height;

				driver->draw2DImage(ConsoleBottomLeft,
					leftRect,
					core::rect<s32>(0, 0, leftBottomSize.Width, leftBottomSize.Height), &leftRect,
					col, true);
			}

			core::dimension2d<u32> rightTopSize(0, 0);
			if (ConsoleTopRight)
			{
				rightTopSize = ConsoleTopRight->getSize();
				core::rect<s32> leftRect = backingRect;
				leftRect.UpperLeftCorner.X = leftRect.LowerRightCorner.X - rightTopSize.Width;
				leftRect.LowerRightCorner.Y = leftRect.UpperLeftCorner.Y + rightTopSize.Height;

				driver->draw2DImage(ConsoleTopRight,
					leftRect,
					core::rect<s32>(0, 0, rightTopSize.Width, rightTopSize.Height), &leftRect,
					col, true);
			}

			core::dimension2d<u32> rightBottomSize(0, 0);
			if (ConsoleBottomRight)
			{
				rightBottomSize = ConsoleBottomRight->getSize();
				core::rect<s32> leftRect = backingRect;
				leftRect.UpperLeftCorner.X = leftRect.LowerRightCorner.X - rightBottomSize.Width;
				leftRect.UpperLeftCorner.Y = leftRect.LowerRightCorner.Y - rightBottomSize.Height;

				driver->draw2DImage(ConsoleBottomRight,
					leftRect,
					core::rect<s32>(0, 0, rightBottomSize.Width, rightBottomSize.Height), &leftRect,
					col, true);
			}

			core::rect<s32> leftSideRect = backingRect;
			leftSideRect.UpperLeftCorner.Y += leftTopSize.Height;
			leftSideRect.LowerRightCorner.Y -= leftBottomSize.Height;
			leftSideRect.LowerRightCorner.X = leftSideRect.UpperLeftCorner.X + leftTopSize.Width;

			driver->draw2DRectangle(col[0], leftSideRect);

			leftSideRect = backingRect;
			leftSideRect.UpperLeftCorner.X = leftTopSize.Width + 10;
			leftSideRect.LowerRightCorner.X -= rightTopSize.Width;

			driver->draw2DRectangle(col[0], leftSideRect);

			leftSideRect = backingRect;
			leftSideRect.UpperLeftCorner.Y += rightTopSize.Height;
			leftSideRect.LowerRightCorner.Y -= rightBottomSize.Height;
			leftSideRect.UpperLeftCorner.X = leftSideRect.LowerRightCorner.X - rightTopSize.Width;

			driver->draw2DRectangle(col[0], leftSideRect);

			IGUIElement::draw();
		}

		//! sets another skin independent font. if this is set to zero, the button uses the font of the skin.
		void CGUIConsoleOverlay::setOverrideFont(IGUIFont* font)
		{
			if (OverrideFont == font)
				return;

			if (OverrideFont)
				OverrideFont->drop();

			OverrideFont = font;

			if (OverrideFont)
				OverrideFont->grab();
		}

		//! Gets the override font (if any)
		IGUIFont * CGUIConsoleOverlay::getOverrideFont() const
		{
			return OverrideFont;
		}

		//! Get the font which is used right now for drawing
		IGUIFont* CGUIConsoleOverlay::getActiveFont() const
		{
			if (OverrideFont)
				return OverrideFont;
			IGUISkin* skin = Environment->getSkin();
			if (skin)
				return skin->getFont(EGDF_BUTTON);
			return 0;
		}

		void CGUIConsoleOverlay::addLine(video::SColor color, core::stringw text)
		{
			m.lock();

			IGUIFont* font = getActiveFont();

			core::rect<s32> bottomLineRect(AbsoluteRect);
			s32 width = AbsoluteRect.LowerRightCorner.X - AbsoluteRect.UpperLeftCorner.X;

			core::dimension2d<u32> textSize = font->getDimension(text.c_str());
			bottomLineRect.UpperLeftCorner.X = 0;
			bottomLineRect.UpperLeftCorner.Y = bottomLineRect.LowerRightCorner.Y - textSize.Height - 7; // 5 padding
			if (textSize.Width < (u32)width)
				bottomLineRect.LowerRightCorner.X = textSize.Width + 20;
			else
				bottomLineRect.LowerRightCorner.X = width - 10;

			core::list<IGUIElement*>::Iterator it = Children.begin();
			for (; it != Children.end(); ++it)
			{
				core::rect<s32> absoluteRect = (*it)->getAbsoluteClippingRect();
				(*it)->setRelativePosition(core::position2di(0, absoluteRect.UpperLeftCorner.Y - textSize.Height - 7));
			}

			IGUIConsoleRow* elem = new CGUIConsoleRow(text.c_str(), color, font, this->Environment, this, -1, bottomLineRect, 900, 10000, 1500);
			addChild(elem);
			elem->drop();

			m.unlock();
		}

		//! Writes attributes of the element.
		void CGUIConsoleOverlay::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options = 0) const
		{
			IGUIConsoleOverlay::serializeAttributes(out, options);

			//out->addTexture("Image", Image);
			//out->addRect("ImageRect", ImageRect);
			//out->addTexture("PressedImage", PressedImage);
			//out->addRect("PressedImageRect", PressedImageRect);

			//out->addBool("UseAlphaChannel", isAlphaChannelUsed());
			//out->addBool("Border", isDrawingBorder());
			//out->addBool("ScaleImage", isScalingImage());

			//   out->addString  ("OverrideFont",	OverrideFont);
		}

		//! Reads attributes of the element
		void CGUIConsoleOverlay::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options = 0)
		{
			IGUIConsoleOverlay::deserializeAttributes(in, options);

			//IsPushButton = in->getAttributeAsBool("PushButton");
			//Pressed = IsPushButton ? in->getAttributeAsBool("Pressed") : false;

			//core::rect<s32> rec = in->getAttributeAsRect("ImageRect");
			//if (rec.isValid())
			//	setImage(in->getAttributeAsTexture("Image"), rec);
			//else
			//	setImage(in->getAttributeAsTexture("Image"));

			//rec = in->getAttributeAsRect("PressedImageRect");
			//if (rec.isValid())
			//	setPressedImage(in->getAttributeAsTexture("PressedImage"), rec);
			//else
			//	setPressedImage(in->getAttributeAsTexture("PressedImage"));

			//setDrawBorder(in->getAttributeAsBool("Border"));
			//setUseAlphaChannel(in->getAttributeAsBool("UseAlphaChannel"));
			//setScaleImage(in->getAttributeAsBool("ScaleImage"));

			////   setOverrideFont(in->getAttributeAsString("OverrideFont"));

			updateAbsolutePosition();
		}

		core::rect<s32> CGUIConsoleOverlay::getBackingRect()
		{
			IGUIFont* font = getActiveFont();

			s32 maxWidth = 0;
			s32 totalHeight = 0;

			core::list<IGUIElement*>::Iterator it = Children.begin();
			for (; it != Children.end(); ++it)
			{
				core::rect<s32> absoluteRect = (*it)->getAbsoluteClippingRect();

				s32 width = absoluteRect.LowerRightCorner.X - absoluteRect.UpperLeftCorner.X;
				s32 height = absoluteRect.LowerRightCorner.Y - absoluteRect.UpperLeftCorner.Y;
				if (width > maxWidth)
					maxWidth = width;

				totalHeight += height;
			}

			core::rect<s32> backingRect = AbsoluteRect;
			backingRect.UpperLeftCorner.X = 10;
			backingRect.UpperLeftCorner.Y = backingRect.LowerRightCorner.Y - (totalHeight + 10);
			backingRect.LowerRightCorner.X = maxWidth + 10;

			return backingRect;
		}

	} // end namespace gui
} // end namespace irr

#endif // _IRR_COMPILE_WITH_GUI_


text:
package com.dojo.silhouette.silhouette

object JustASimpleCheck {

  def main(args: Array[String]): Unit = {
    val nums = (3 until 100).toList
    val somenums = nums filter (x => x % 3 == 0 || x % 5 == 0)
    val somenums2 = nums filter (x => x % 2 == 0 || x % 7 == 0)
    //(somenums reverse_::: somenums2).foreach(x => println(x))
    val v = new MergeSort[Int]
    v.mergeSort(somenums, somenums2, List()).foreach(x => println(x))
  }
}


text:
/**
 * 项目构建模块
 *
 *
 * @desc    A generator for building front-end project.
 * @author  [@soulteary](soulteary@qq.com)
 * @website http://soulteary.com
 * @date    2015.06.28
 */
/* global module */

'use strict';

var conf = require('../common/conf');
var path = require('path');
/* istanbul ignore next: untestable */
module.exports = function(yeoman, options) {

    yeoman.data = yeoman.data || {};
    options = options || {};

    // 构建方式以及构建之后是否进行安装
    yeoman.data.mode = yeoman.data.mode || 'static';
    yeoman.data.install = yeoman.data.install || true;

    if (options.build) {
        if (options.build.mode) {
            yeoman.data.mode = options.build.mode;
        }
        if (options.build.install) {
            yeoman.data.install = options.build.install;
        }
    }

    // 处理当前项目名称
    yeoman.data.name = yeoman.data.name || path.basename(process.cwd());
    if (options.name) {
        yeoman.data.name = options.name;
    }

    // 处理项目描述
    yeoman.data.desc = yeoman.data.desc || '这里是项目的默认描述信息。';
    if (options.desc) {
        yeoman.data.desc = options.desc;
    }

    // 处理项目作者
    yeoman.data.author = yeoman.data.author || 'yournickname <yournickname@email.com> (http://website.com)';
    if (options.author) {
        yeoman.data.author = options.author;
    }

    // 协议相关
    yeoman.data.license = yeoman.data.license || {};
    yeoman.data.license.author = yeoman.data.license.author || yeoman.data.author;
    yeoman.data.license.name = yeoman.data.license.name || yeoman.data.name;
    yeoman.data.license.desc = yeoman.data.license.desc || yeoman.data.desc;
    yeoman.data.license.type = yeoman.data.license.type || 'MIT';
    yeoman.data.license.year = yeoman.data.license.year || (new Date()).getFullYear();
    if (options.license) {
        if (options.license.name) {
            yeoman.data.license.name = options.license.name;
        }
        if (options.license.author) {
            yeoman.data.license.author = options.license.author;
        }
        if (options.license.desc) {
            yeoman.data.license.desc = options.license.desc;
        }
        if (options.license.year) {
            yeoman.data.license.year = options.license.year;
        }
        if (options.license.type) {
            yeoman.data.license.type = options.license.type;
        }
        // 仅为脚本使用
        yeoman.data.license.fullName = conf.projectLicensesOptions
            .filter(function(item) {return (item.value === options.license.type);})[0].name;
    }

    // CSS
    yeoman.data.css = yeoman.data.css || {};
    yeoman.data.css.type = yeoman.data.css.type || 'css';
    if (options.css) {
        if (options.css.type) {
            yeoman.data.css.type = options.css.type;
        }
    }

    // Tasker
    yeoman.data.tasker = yeoman.data.tasker || {};
    yeoman.data.tasker.type = yeoman.data.tasker.type || 'gulp';
    if (options.tasker) {
        if (options.tasker.type) {
            yeoman.data.tasker.type = options.tasker.type;
        }
    }

    // Template
    yeoman.data.template = yeoman.data.template || {};
    yeoman.data.template.type = yeoman.data.template.type || 'doT';
    if (options.template) {
        if (options.template.type) {
            yeoman.data.template.type = options.template.type;
        }
    }

    // Test Framework
    yeoman.data.testFramework = yeoman.data.testFramework || {};
    yeoman.data.testFramework.type = yeoman.data.testFramework.type || 'mocha';
    if (options.testFramework) {
        if (options.testFramework.type) {
            yeoman.data.testFramework.type = options.testFramework.type;
        }
    }

    // JS Module
    yeoman.data.js = yeoman.data.js || {};
    yeoman.data.js.module = yeoman.data.js.module || 'commonjs';
    yeoman.data.js.ver = yeoman.data.js.ver || 'es5';
    if (options.js) {
        if (options.js.module) {
            yeoman.data.js.module = options.js.module;
        }
        if (options.js.ver) {
            yeoman.data.js.ver = options.js.ver;
        }
        if (options.js.jquery && [1, 2].indexOf(options.js.jquery) > -1) {
            yeoman.data.js.jquery = options.js.jquery;
        }
    }

};


text:
package publichealthcomplaint.exceptionhandling.impl;

public class CommunicationException extends Exception implements java.io.Serializable {

    public CommunicationException(String s) {
        super(s);
    }
}

/*--- Formatted in Sun Java Convention Style on Mon, Oct 30, '00 ---*/

/*------ Formatted by Jindent 3.23 Gold 1.02 Trial --- http://www.jindent.de ------*/


text:
package com.blazebit.persistence.spi;

/**
 * Strategies for generating a VALUES table reference.
 *
 * @author Christian Beikov
 * @since 1.2.0
 */
public enum ValuesStrategy {
    VALUES,
    SELECT_VALUES,
    SELECT_UNION;

    // NOTE: another possible strategy would be to use a temporary table
    // CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)
}


text:
namespace TooManyOrbits.Filter
{
	internal class VesselFilter : IFilter<Vessel>
	{
		public bool Accept(Vessel obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (obj == FlightGlobals.ActiveVessel)
			{
				return false;
			}
			if (obj == FlightGlobals.ActiveVessel.targetObject?.GetVessel())
			{
				return false;
			}
			return true;
		}
	}
}


text:
require 'uri'
class Card < ActiveRecord::Base
  ORIGINS = [:local, :twitter, :instagram, :google_plus, :pintrest]

  belongs_to :user

  validates :title,
            length: { minimum: 1, maximum: 255 }
  validates :origin,
            inclusion: { in: 0..(ORIGINS.size - 1) }
  validates :posted_at,
            presence: true

  def originated_network
    ORIGINS[read_attribute(:origin)]
  end

  def originated_network=(value)
    write_attribute(:origin, ORIGINS.index(value))
  end
end


text:
@class IndoorDeviceView;

typedef void(^IndoorDeviceViewOnDelete)(IndoorDeviceView *);

typedef void (^ChTimeBlock)(BOOL needReload);

@protocol IndoorDeviceDelegate <NSObject>

-(void)clickDevice:(id)sender withDeviceModel:(DeviceModel *)device;

@end

@interface IndoorDeviceView : BaseView<UIAlertViewDelegate>

@property (assign, nonatomic) id<IndoorDeviceDelegate> delegate;
@property (strong, nonatomic) IndoorDeviceViewOnDelete onDelete;

@property (strong, nonatomic) IBOutlet UIImageView *fanImage;
@property (strong, nonatomic) IBOutlet UILabel *modeLabel;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;

@property (strong, nonatomic) IBOutlet UIImageView *deviceImage;

@property (nonatomic, strong) DeviceModel *deviceModel;

-(void)refreshDeviceView;
-(void)stopFanRunning;

#pragma mark kenny add device being controlled status
-(void)startFlashingAnimationWithDevice;
-(void)stopFlashingAnimation;

-(void)showTargetTransitionDisplayMode;

@end


text:
package com.google.android.stardroid.renderer.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;

public class IndexBuffer {
  public IndexBuffer(int numVertices) {
    this(numVertices, false);
  }

  public IndexBuffer() {
    mNumIndices = 0;
  }

  public IndexBuffer(boolean useVBO) {
    mNumIndices = 0;
    mUseVbo = useVBO;
  }

  public IndexBuffer(int numVertices, boolean useVbo) {
    mUseVbo = useVbo;
    reset(numVertices);
  }

  public int size() {
    return mNumIndices;
  }

  public void reset(int numVertices) {
    mNumIndices = numVertices;
    regenerateBuffer();
  }

  // Call this when we have to re-create the surface and reloading all OpenGL resources.
  public void reload() {
    mGLBuffer.reload();
  }

  private void regenerateBuffer() {
    if (mNumIndices == 0) {
      return;
    }

    ByteBuffer bb = ByteBuffer.allocateDirect(2 * mNumIndices);
    bb.order(ByteOrder.nativeOrder());
    ShortBuffer ib = bb.asShortBuffer();
    ib.position(0);
    mIndexBuffer = ib;
  }

  public void addIndex(short index) {
    mIndexBuffer.put(index);
  }

  public void draw(GL10 gl, int primitiveType) {
    if (mNumIndices == 0) {
      return;
    }
    mIndexBuffer.position(0);
    if (mUseVbo && GLBuffer.canUseVBO()) {
      GL11 gl11 = (GL11)gl;
      mGLBuffer.bind(gl11, mIndexBuffer, 2 * mIndexBuffer.capacity());
      gl11.glDrawElements(primitiveType, size(), GL10.GL_UNSIGNED_SHORT, 0);
      GLBuffer.unbind(gl11);
    } else {
      gl.glDrawElements(primitiveType, size(), GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
    }
  }

  private ShortBuffer mIndexBuffer = null;
  private int mNumIndices = 0;
  private GLBuffer mGLBuffer = new GLBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER);
  private boolean mUseVbo = false;
}