text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Dynamic;
using System.Xml.Linq;

namespace Business.Utilities.Extensions
{
    public static class IEnumerableExtensionBase
    {
        public static void IEnumerableCallAction<T>(this IEnumerable<T> values, Action<T> action)
        {
            foreach (var o in values)
            {
                action(o);
            }
        }

        public static void IEnumerableCallActions<T>(this IEnumerable<T> values, params Action<T>[] actions)
        {
            foreach (var t in values)
            {
                foreach (var t1 in actions)
                {
                    t1(t);
                }
            }
        }

        public static IEnumerable<TDest> IEnumerableTransformEach<TDest, TSource>(this IEnumerable<TSource> values, Func<TSource, TDest> function)
        {
            return values.Select(function);
        }

        public delegate TOut Action<in TIn, out TOut>(TIn element);

        public static IEnumerable<TOut> Transform<TIn, TOut>(IEnumerable<TIn> list, Action<TIn, TOut> method)
        {
            return list.Select(entry => method(entry));
        }

        public static ObservableCollection<T> IEnumerableToObservableCollection<T>(this IEnumerable<T> values)
        {
            return new ObservableCollection<T>(values);
        }

        public static IEnumerable<TSource> IEnumerableTop<TSource, TKey>(this IEnumerable<TSource> source, Int32 count, Func<TSource, TKey> orderBy)
        {
            return source.OrderBy(orderBy).Take(count).AsEnumerable();
        }

        public static XElement IEnumerableToXElement<TSource>(this IEnumerable<TSource> list
            , String filePath
            , String itemName = @"Arg"
            , String valueName = "V"
            ) where TSource : IConvertible
        {
            var x = new XElement(itemName);
            foreach (var e in list)
            {
                x.Add(new XElement(valueName, e));
            }
            return x;
        }

        public static IEnumerable<TSource> IEnumerableFromXElement<TSource>(
            XElement xml
            , String valueName = "V"
            ) where TSource : IConvertible
        {
            return xml.Elements(valueName).Select(el => (TSource)Convert.ChangeType(el.Value, typeof(TSource)));
        }

        public static void IEnumerableToXElementToFile<TSource>(this IEnumerable<TSource> list
            , String filePath
            , String itemName = @"Arg"
            , String valueName = "V"
            ) where TSource : IConvertible
        {
            var x = new XElement(itemName);
            foreach (var e in list)
            {
                x.Add(new XElement(valueName, e));
            }
            x.Save(filePath);
        }

        public static IEnumerable<TSource> IEnumerableFromXElementFromFile<TSource>(
            String filePath
            , String valueName = "V"
            ) where TSource : IConvertible
        {
            var x = XElement.Load(filePath);
            return x.Elements(valueName).Select(el => (TSource)Convert.ChangeType(el.Value, typeof(TSource)));
        }

        public static bool In<T>(this T source, params T[] list)
        {
            return list.ToList().Contains(source);
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
        {
            return source == null || !source.Any();
        }

        public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
        {
            return source != null && source.Any();
        }

        public static bool NotAny<T>(this IEnumerable<T> source, Func<T, bool> predicate)
        {
            return !source.Any(predicate);
        }

        public static bool IsNullOrNotAny<T>(this IEnumerable<T> source, Func<T, bool> predicate)
        {
            return source == null || !source.Any(predicate);
        }

        public static bool NotNullAndAny<T>(this IEnumerable<T> source, Func<T, bool> predicate)
        {
            return source != null && source.Any(predicate);
        }

        public static IEnumerable<T> SkipTake<T>(this IEnumerable<T> source, Int32 skip, Int32 take)
        {
            return source.Skip(skip).Take(take);
        }

        public static IEnumerable<T> Page<T>(this IEnumerable<T> source, Int32 index, Int32 size)
        {
            return source.Skip(index * size).Take(size);
        }

        public static IEnumerable<T> PageWhere<T>(this IEnumerable<T> source, Int32 index, Int32 size, Func<T, bool> predicate)
        {
            return source.Where(predicate).Skip(index * size).Take(size);
        }

        public static IEnumerable<T> PageWhere<T>(this IEnumerable<T> source, Int32 index, Int32 size, string predicate, params object[] values)
        {
            return source.AsQueryable().Where(predicate, values).Skip(index * size).Take(size);
        }

        public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource value)
        {
            yield return value;
            foreach (var element in source)
            {
                yield return element;
            }
        }

        public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource value)
        {
            foreach (var element in source)
            {
                yield return element;
            }
            yield return value;
        }

        public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> value)
        {
            foreach (var element in value)
            {
                yield return element;
            }
            foreach (var element in source)
            {
                yield return element;
            }
        }

        public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> value)
        {
            foreach (var element in source)
            {
                yield return element;
            }
            foreach (var element in value)
            {
                yield return element;
            }
        }

        public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<IEnumerable<TSource>> source, IEnumerable<TSource> value)
        {
            foreach (var element in value)
            {
                yield return element;
            }
            foreach (var child in source.SelectMany(element => element))
            {
                yield return child;
            }
        }

        public static IEnumerable<TSource> Append<TSource>(this IEnumerable<IEnumerable<TSource>> source, IEnumerable<TSource> value)
        {
            foreach (var child in source.SelectMany(element => element))
            {
                yield return child;
            }
            foreach (var element in value)
            {
                yield return element;
            }
        }

        public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<IEnumerable<TSource>> source, IEnumerable<IEnumerable<TSource>> value)
        {
            foreach (var child in value.SelectMany(element => element))
            {
                yield return child;
            }
            foreach (var child in source.SelectMany(element => element))
            {
                yield return child;
            }
        }

        public static IEnumerable<TSource> Append<TSource>(this IEnumerable<IEnumerable<TSource>> source, IEnumerable<IEnumerable<TSource>> value)
        {
            foreach (var element in source)
            {
                foreach (var child in element)
                {
                    yield return child;
                }
            }
            foreach (var element in value)
            {
                foreach (var child in element)
                {
                    yield return child;
                }
            }
        }

        public static IEnumerable<IEnumerable<T>> Pages<T>(this IEnumerable<T> source, Int32 size)
        {
            var cnt = 0;
            while (true)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var page = source.SkipTake(cnt++ * size, size);
                // ReSharper disable once PossibleMultipleEnumeration
                if (page.IsNullOrEmpty()) break;
                // ReSharper disable once PossibleMultipleEnumeration
                yield return page;
            }
        }

        public static IEnumerable<IEnumerable<T>> PagesWhere<T>(this IEnumerable<T> source, Int32 size, Func<T, bool> predicate)
        {
            var cnt = 0;
            while (true)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var page = source.Where(predicate).SkipTake(cnt++ * size, size);
                // ReSharper disable once PossibleMultipleEnumeration
                if (page.IsNullOrEmpty()) break;
                // ReSharper disable once PossibleMultipleEnumeration
                yield return page;
            }
        }

        public static IEnumerable<IEnumerable<T>> PagesWhere<T>(this IEnumerable<T> source, Int32 size, string predicate, params object[] values)
        {
            var cnt = 0;
            while (true)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var page = source.AsQueryable().Where(predicate, values).SkipTake(cnt++ * size, size);
                // ReSharper disable once PossibleMultipleEnumeration
                if (page.IsNullOrEmpty()) break;
                // ReSharper disable once PossibleMultipleEnumeration
                yield return page;
            }
        }

        public static IEnumerable<IEnumerable<T>> Transpose<T>(this IEnumerable<IEnumerable<T>> values)
        {
            if (!values.Any())
                return values;
            if (!values.First().Any())
                return Transpose(values.Skip(1));

            var x = values.First().First();
            var xs = values.First().Skip(1);
            var xss = values.Skip(1);
            return
             new[] {new[] {x}
           .Concat(xss.Select(ht => ht.First()))}
               .Concat(new[] { xs }
               .Concat(xss.Select(ht => ht.Skip(1)))
               .Transpose());
        }

        /*
        //Input: transpose [[1,2,3],[4,5,6],[7,8,9]]
//Output: [[1,4,7],[2,5,8],[3,6,9]]
var result = new[] {new[] {1, 2, 3}, new[] {4, 5, 6}, new[] {7, 8, 9}}.Transpose();
        */

        public static Dictionary<TKey1, Dictionary<TKey2, TValue>> Pivot<TSource, TKey1, TKey2, TValue>(
            this IEnumerable<TSource> source, Func<TSource, TKey1> key1Selector
            , Func<TSource, TKey2> key2Selector
            , Func<IEnumerable<TSource>, TValue> aggregate
            )
        {
            return source.GroupBy(key1Selector).Select(
            x => new
            {
                X = x.Key,
                Y = x.GroupBy(key2Selector).Select(
                z => new
                {
                    Z = z.Key,
                    V = aggregate(z)
                }
                ).ToDictionary(e => e.Z, o => o.V)
            }
            ).ToDictionary(e => e.X, o => o.Y);
        }

        /*
         class Program {
    internal class Employee {
        public string Name { get; set; }
        public string Department { get; set; }
        public string Function { get; set; }
        public decimal Salary { get; set; }
    }

    static void Main(string[] args) {
        var l = new List<Employee>() {
            new Employee() { Name = "Fons", Department = "R&D", Function = "Trainer", Salary = 2000 },
            new Employee() { Name = "Jim", Department = "R&D", Function = "Trainer", Salary = 3000 },
            new Employee() { Name = "Ellen", Department = "Dev", Function = "Developer", Salary = 4000 },
            new Employee() { Name = "Mike", Department = "Dev", Function = "Consultant", Salary = 5000 },
            new Employee() { Name = "Jack", Department = "R&D", Function = "Developer", Salary = 6000 },
            new Employee() { Name = "Demy", Department = "Dev", Function = "Consultant", Salary = 2000 }};

        var result1 = l.Pivot(emp => emp.Department, emp2 => emp2.Function, lst => lst.Sum(emp => emp.Salary));

        foreach (var row in result1) {
            Console.WriteLine(row.Key);
            foreach (var column in row.Value) {
                Console.WriteLine("  " + column.Key + "\t" + column.Value);
            }
        }

*/

        public static IEnumerable<TSource> SelectRecursive<TSource>(
            this IEnumerable<TSource> source,
            Func<TSource, IEnumerable<TSource>> recursiveSelector
            )
        {
            var stack = new Stack<IEnumerator<TSource>>();
            stack.Push(source.GetEnumerator());
            try
            {
                while (stack.Count > 0)
                {
                    if (stack.Peek().MoveNext())
                    {
                        var current = stack.Peek().Current;
                        yield return current;
                        stack.Push(recursiveSelector(current).GetEnumerator());
                    }
                    else
                    {
                        stack.Pop().Dispose();
                    }
                }
            }
            finally
            {
                while (stack.Count > 0)
                {
                    stack.Pop().Dispose();
                }
            }
        }

        #region to xml string or xelements

        //public static XElement ToXElement<T>(this T input)
        //{
        //    return XElement.Parse(input.ToXmlString());
        //}

        //public static IEnumerable<XElement> ToXElements<T>(this IEnumerable<T> input)
        //{
        //    foreach (var item in input)
        //        yield return input.ToXElement();
        //}

        //public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> input)
        //{
        //    foreach (var item in input)
        //        yield return item.ToXmlString();
        //}

        //public static string ToXmlString<T>(this T input)
        //{
        //    using (var writer = new StringWriter())
        //    {
        //        input.ToXml(writer);
        //        return writer.ToString();
        //    }
        //}

        //public static void ToXml<T>(this T objectToSerialize, Stream stream)
        //{
        //    new XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize);
        //}

        //public static void ToXml<T>(this T objectToSerialize, StringWriter writer)
        //{
        //    new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
        //}

        #endregion to xml string or xelements

        public static IDictionary<TKey, IEnumerable<T>> PartitionToDictionary<TKey, T>(this IEnumerable<T> source, IEnumerable<TKey> partitionKeys, Func<TKey, IEnumerable<T>, IEnumerable<T>> partitioner)
        {
            return partitionKeys.ToDictionary(k => k, k => partitioner(k, source));
        }
    }
}


text:
exports.awesome = function() {
  return 'ação é isso aí';
};

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { dismiss } from '../actions/ErrorActionCreators';
import { firstErrorSelector } from '../selectors/errorSelectors';
import ErrorArea from '../components/ErrorArea';

const {
  useCallback,
} = React;

function ErrorAreaContainer() {
  const error = useSelector(firstErrorSelector);
  const dispatch = useDispatch();
  const onDismiss = useCallback(() => dispatch(dismiss()), [dispatch]);

  return <ErrorArea error={error} onDismiss={onDismiss} />;
}

export default ErrorAreaContainer;


text:
<?php
/**
 * Created by PhpStorm.
 * User: jcuna
 * Date: 5/30/16
 * Time: 9:41 AM
 */

namespace App\Core\Api;

use App\Core\Db\Statement;

interface DatabaseAccessInterface
{

    /**
     * @return Statement
     */
    public function getStatement();

    /**
     * @return \PDO
     */
    public function getConnection();

}


text:
package pipoint

import (
	"math"
)

const (
	m1 = 111132.92 // latitude calculation term 1
	m2 = -559.82   // latitude calculation term 2
	m3 = 1.175     // latitude calculation term 3
	m4 = -0.0023   // latitude calculation term 4
	p1 = 111412.84 // longitude calculation term 1
	p2 = -93.5     // longitude calculation term 2
	p3 = 0.118     // longitude calculation term 3
)

// LatLength returns the length of a line of latitude at the given
// latitude.  Input is in rad, output in m.
func LatLength(lat float64) float64 {
	return m1 + m2*math.Cos(2*lat) + m3*math.Cos(4*lat)
}

// LonLength returns the length of a line of longitude at the given
// latitude.  Input is in rad, output in m.
func LonLength(lat float64) float64 {
	return p1*math.Cos(lat) + p2*math.Cos(3*lat) + p3*math.Cos(5*lat)
}

// AsRad converts degrees to radians.
func AsRad(deg float64) float64 {
	return deg * (math.Pi / 180)
}

// AsDeg converts radians to degrees.
func AsDeg(rad float64) float64 {
	return rad * (180 / math.Pi)
}


text:
package com.example.android.supportv7.app;

import com.example.android.supportv7.Cheeses;
import com.example.android.supportv7.R;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;

/**
 * This demonstrates the styled text input widgets in AppCompat, such as
 * {@link android.widget.EditText}, {@link AutoCompleteTextView} and
 * {@link MultiAutoCompleteTextView}.
 */
public class AppCompatWidgetsTextInput extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.appcompat_widgets_text_input);

        // Fetch the AutoCompleteTextView and set an adapter
        AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(
                R.id.widgets_autocompletetextview);
        actv.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, Cheeses.sCheeseStrings));

        // Fetch the MultiAutoCompleteTextView and set an adapter and Tokenizer
        MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) findViewById(
                R.id.widgets_multiautocompletetextview);
        mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        mactv.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, Cheeses.sCheeseStrings));
    }

}


text:
<?php

class Sewa_model extends MY_Model
{

	function __construct()
	{
		parent::__construct();
		$this->table = 'sewa';
	}
}


text:
//b2.1
import jdsl.core.api.*;
import jdsl.core.ref.*;
import jdsl.core.algo.sorts.*;
//e2.1
import java.awt.*;
import java.awt.event.*;
import java.util.*;

/*
 * This Class demonstrates manipulating Sequences.
 *
 * @author Robert Cohen (rfc)
 * @version JDSL 2
*/
public class SequenceFun extends Frame implements ActionListener,  WindowListener {

    /* ************************************ */
    /* The members described in the lesson. */
    /* ************************************ */

    /*
     Sort a sequence in alphabetical order.
    */
    //b2.2
    private void sort(Sequence seq) {
        // This object will do the sorting.
        SortObject sorter = new ArrayQuickSort();
        // Sort in alphabetical order.
        sorter.sort(seq, new ComparableComparator());
    }
    //e2.2

    /*
     Sort a sequence in reverse alphabetical order.
    */
    //b2.4
    private void reverseSort(Sequence seq) {
        // This object will do the sorting.
        SortObject sorter = new ArrayQuickSort();
        // Sort in alphabetical order.
        sorter.sort(seq, new ComparatorReverser(new ComparableComparator()));
    }
    //e2.4

    /*
     Randomly permute the elements of a Sequence.
    */
    //b2.5
    protected void permute(Sequence s) {
        Random rnd = new java.util.Random();
        for(int i=s.size()-1;i>0;i--) {
            int j=rnd.nextInt(i+1);
            if (j<i)
                s.swapElements(s.atRank(i),s.atRank(j));
        }
    }
    //e2.5

    /* ************************************ */
    /* Members not described in the lesson. */
    /* ************************************ */

    // The sequence to store the words.
    Sequence seq;

    // The GUI widgets
    Label title = new Label( "Test Sequences" );
    TextField inField = new TextField( "", 50 );
    TextField outField = new TextField( "", 50 );
    Button echoBtn = new Button("Echo");
    Button sortBtn = new Button("Sort");
    Button reverseBtn = new Button("Reverse Sort");
    Button permuteBtn = new Button("Permute");
    Button quitBtn = new Button("Quit");

    /*
     The Constructor simple sets up the GUI.
    */
    public SequenceFun() {
        setUpWindow();
    }

    public void actionPerformed(ActionEvent e) {
        String in = inField.getText();
        seq = getWords(in);
        if (e.getSource()==sortBtn)
            sort(seq);
        else if (e.getSource()==reverseBtn)
            reverseSort(seq);
        else if (e.getSource()==permuteBtn)
            permute(seq);
        else if (e.getSource()==quitBtn)
            quit();
        outField.setText(conc(seq));
    }

    /*
     Takes a string and converts it to a sequence of words.  This is
     the same method from Lesson 1.
    */
    private Sequence getWords(String s) {
        Sequence ret = new ArraySequence();
        StringTokenizer st = new StringTokenizer(s);
        while (st.hasMoreTokens()) {
            ret.insertLast(st.nextToken());
        }
        return ret;
    }

    /*
     Takes a Sequence of words and returns a string consisting of all
     the words, each separated by a space.  This is
     the same method from Lesson 1.
    */
    private String conc(Sequence s) {
        String ret = "";
        for(ObjectIterator i=seq.elements();i.hasNext();)
            ret += (i.nextObject() + " ");
        return ret;
    }

    /*
     Run the frame.
    */
    public static void main(String args[]) {
        SequenceFun s = new SequenceFun();
        s.show();
    }

    /*
     Set up the GUI.
    */
    private void setUpWindow() {
        setTitle("Sort");
        title.setFont( new Font( "Helvetica", Font.BOLD , 24 ) );
        Panel titlePanel = new Panel();
        titlePanel.add(title);

        Panel inPanel = new Panel();
        inPanel.add(new Label("Enter a sentence"));
        inPanel.add(inField);

        outField.setEditable(false);
        Panel outPanel = new Panel();
        outPanel.add(new Label("Result"));
        outPanel.add(outField);

        Panel centerPanel = new Panel();
        centerPanel.add(inPanel);
        centerPanel.add(outPanel);

        Panel btnPanel = new Panel();
        btnPanel.add(echoBtn);
        btnPanel.add(sortBtn);
        btnPanel.add(reverseBtn);
        btnPanel.add(permuteBtn);
        btnPanel.add(quitBtn);

        setLayout(new BorderLayout());
        add(titlePanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.SOUTH);

        addWindowListener(this);
        echoBtn.addActionListener(this);
        sortBtn.addActionListener(this);
        reverseBtn.addActionListener(this);
        permuteBtn.addActionListener(this);
        quitBtn.addActionListener(this);
        inField.addActionListener(this);
        inField.requestFocus();

	setSize(500,250);
	setLocation(50,50);
    }

    private void quit() {
        System.exit(0);
    }

    public void windowActivated(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {quit();}
    public void windowClosing(WindowEvent e) {quit();}
    public void windowDeactivated(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowOpened(WindowEvent e) {}
}


text:
<!DOCTYPE html>

    <title>SceneJS Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    <link href="css/styles.css" rel="stylesheet"/>

    SceneJS - render teapot to color and depth textures, apply textures to boxes


text:
package com.intellij.application.options.colors;

import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import com.intellij.openapi.options.colors.ColorSettingsPages;
import com.intellij.openapi.options.newEditor.SettingsDialog;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.components.JBList;
import com.intellij.util.ObjectUtils;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.intellij.application.options.colors.ColorAndFontOptions.getColorSelector;
import static com.intellij.ui.SimpleTextAttributes.*;

/**
 * @author gregsh
 */
public class JumpToColorsAndFontsAction extends DumbAwareAction {

  public JumpToColorsAndFontsAction() {
    setInjectedContext(true);
  }

  @Override
  public void update(AnActionEvent e) {
    Project project = e.getData(CommonDataKeys.PROJECT);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    e.getPresentation().setEnabledAndVisible(project != null && editor != null);
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    // todo handle ColorKey's as well
    Project project = e.getData(CommonDataKeys.PROJECT);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (project == null || editor == null) return;
    Map<TextAttributesKey, Pair<ColorSettingsPage, AttributesDescriptor>> keyMap = ContainerUtil.newHashMap();
    Processor<RangeHighlighterEx> processor = r -> {
      Object tt = r.getErrorStripeTooltip();
      TextAttributesKey key = tt instanceof HighlightInfo ? ObjectUtils.chooseNotNull(
        ((HighlightInfo)tt).forcedTextAttributesKey, ((HighlightInfo)tt).type.getAttributesKey()) : null;
      Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
      if (p != null) keyMap.put(key, p);
      return true;
    };
    JBIterable<Editor> editors = editor instanceof EditorWindow ? JBIterable.of(editor, ((EditorWindow)editor).getDelegate()) : JBIterable.of(editor);
    for (Editor ed : editors) {
      TextRange selection = EditorUtil.getSelectionInAnyMode(ed);
      MarkupModel forDocument = DocumentMarkupModel.forDocument(ed.getDocument(), project, false);
      if (forDocument != null) {
        ((MarkupModelEx)forDocument).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
      }
      ((MarkupModelEx)ed.getMarkupModel()).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
      EditorHighlighter highlighter = ed instanceof EditorEx ? ((EditorEx)ed).getHighlighter() : null;
      SyntaxHighlighter syntaxHighlighter = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter)highlighter).getSyntaxHighlighter() : null;
      if (syntaxHighlighter != null) {
        HighlighterIterator iterator = highlighter.createIterator(selection.getStartOffset());
        while (!iterator.atEnd()) {
          for (TextAttributesKey key : syntaxHighlighter.getTokenHighlights(iterator.getTokenType())) {
            Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
            if (p != null) keyMap.put(key, p);
          }
          if (iterator.getEnd() >= selection.getEndOffset()) break;
          iterator.advance();
        }
      }
    }

    if (keyMap.isEmpty()) {
      HintManager.getInstance().showErrorHint(editor, "No text attributes found");
    }
    else if (keyMap.size() == 1) {
      Pair<ColorSettingsPage, AttributesDescriptor> p = keyMap.values().iterator().next();
      if (!openSettingsAndSelectKey(project, p.first, p.second)) {
        HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
      }
    }
    else {
      ArrayList<Pair<ColorSettingsPage, AttributesDescriptor>> attrs = ContainerUtil.newArrayList(keyMap.values());
      Collections.sort(attrs, (o1, o2) -> StringUtil.naturalCompare(
        o1.first.getDisplayName() + o1.second.getDisplayName(), o2.first.getDisplayName() + o2.second.getDisplayName()));

      EditorColorsScheme colorsScheme = editor.getColorsScheme();
      JBList<Pair<ColorSettingsPage, AttributesDescriptor>> list = new JBList<>(attrs);
      list.setCellRenderer(new ColoredListCellRenderer<Pair<ColorSettingsPage, AttributesDescriptor>>() {
        @Override
        protected void customizeCellRenderer(@NotNull JList<? extends Pair<ColorSettingsPage, AttributesDescriptor>> list,
                                             Pair<ColorSettingsPage, AttributesDescriptor> value,
                                             int index,
                                             boolean selected,
                                             boolean hasFocus) {
          TextAttributes ta = colorsScheme.getAttributes(value.second.getKey());
          Color fg = ObjectUtils.chooseNotNull(ta.getForegroundColor(), colorsScheme.getDefaultForeground());
          Color bg = ObjectUtils.chooseNotNull(ta.getBackgroundColor(), colorsScheme.getDefaultBackground());
          SimpleTextAttributes sa = fromTextAttributes(ta);
          SimpleTextAttributes saOpaque = sa.derive(STYLE_OPAQUE | sa.getStyle(), fg, bg, null);
          SimpleTextAttributes saSelected = REGULAR_ATTRIBUTES.derive(sa.getStyle(), null, null, null);
          SimpleTextAttributes saCur = REGULAR_ATTRIBUTES;
          List<String> split = StringUtil.split(value.first.getDisplayName() + "//" + value.second.getDisplayName(), "//");
          for (int i = 0, len = split.size(); i < len; i++) {
            boolean last = i == len - 1;
            saCur = !last ? REGULAR_ATTRIBUTES : selected ? saSelected : saOpaque;
            if (last) append(" ", saCur);
            append(split.get(i), saCur);
            if (last) append(" ", saCur);
            else append(" > ", GRAYED_ATTRIBUTES);
          }
          Color stripeColor = ta.getErrorStripeColor();
          boolean addStripe = stripeColor != null && stripeColor != saCur.getBgColor();
          boolean addBoxed = ta.getEffectType() == EffectType.BOXED && ta.getEffectColor() != null;
          if (addBoxed) {
            append("\u25A2" + (addStripe ? "" : " "), saCur.derive(-1, ta.getEffectColor(), null, null));
          }
          if (addStripe) {
            append(" ", saCur.derive(STYLE_OPAQUE, null, stripeColor, null));
          }
        }
      });
      JBPopupFactory.getInstance().createListPopupBuilder(list)
        .setTitle(StringUtil.notNullize(e.getPresentation().getText()))
        .setMovable(false)
        .setResizable(false)
        .setRequestFocus(true)
        .setItemChoosenCallback(() -> {
          Pair<ColorSettingsPage, AttributesDescriptor> p = list.getSelectedValue();
          if (p != null && !openSettingsAndSelectKey(project, p.first, p.second)) {
            HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
          }
        })
        .createPopup().showInBestPositionFor(editor);
    }
  }

  private static boolean openSettingsAndSelectKey(@NotNull Project project, @NotNull ColorSettingsPage page, @NotNull AttributesDescriptor descriptor) {
    SettingsDialog dialog = (SettingsDialog)ShowSettingsUtilImpl.getDialog(
      project, ShowSettingsUtilImpl.getConfigurableGroups(project, true), null);
    Runnable selector = getColorSelector(dialog, descriptor.getDisplayName(), page.getDisplayName());
    if (selector == null) return false;
    selector.run();
    dialog.show();
    return true;
  }
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="JP" />
</component>


text:
#import "common_RemoteNotification_send_iOS.h"

@interface common_RemoteNotification_send_iOS()
FREObject ANE4MBG_social_common_RemoteNotification_send_iOS(FREContext cxt,
                                                            void* functionData,
                                                            uint32_t argc,
                                                            FREObject argv[]);
@end

@implementation common_RemoteNotification_send_iOS
+ (void)ContextInitializer:(FunctionSets *)funcSets {
    LOG_METHOD;
    [funcSets addFuncSet:@"ANE4MBG_social_common_RemoteNotification_send_iOS"
                 pointer:&ANE4MBG_social_common_RemoteNotification_send_iOS];

}

FREObject ANE4MBG_social_common_RemoteNotification_send_iOS(FREContext cxt,
                                                            void* functionData,
                                                            uint32_t argc,
                                                            FREObject argv[]) {
    LOG_METHOD;
    ArgsParser *parser = [ArgsParser sharedParser];
    [parser setArgc:argc argv:argv];
    NSString *recipientId = [parser nextString];
    MBGRemoteNotificationPayload *payload = [parser nextPayload];
    NSString *onSuccess  = [parser nextString];
    NSString *onError = [parser nextString];

    FREContext context = [ContextOwner sharedContext];

    [MBGSocialRemoteNotification
     send:recipientId
     data:payload
     onSuccess:^(MBGRemoteNotificationResponse *resp) {
         FREResult result = TCDispatch(context,
                                     onSuccess,
                                     [ArgsParser responseToJSON:resp]);
         if(result != FRE_OK) [ArgsParser reportResult:result];
     }
     onError:^(MBGError *error) {
         FREResult result = TCDispatch(context,
                                     onError,
                                     error);
         if(result != FRE_OK) [ArgsParser reportResult:result];
     }];

    return NULL;
}
@end


text:
using System;

namespace Academy.Models.Abstractions
{
    public abstract class User : IUser
    {
        private string username;

        public User(string username)
        {
            this.Username = username;
        }

        public string Username
        {
            get
            {
                return this.username;
            }

            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new ArgumentException("The provided first name is not valid!");
                }

                if (value.Length < 3 || value.Length > 16)
                {
                    throw new ArgumentException("User's username should be between 3 and 16 symbols long!");
                }

                this.username = value;
            }
        }
    }
}


text:
package org.tp23.antinstaller.input;

import java.io.File;

import org.tp23.antinstaller.InstallerContext;
import org.tp23.antinstaller.ValidationException;

/**
 *
 *
Input type to select a directory

 *

 *
Copyright: Copyright (c) 2004

 *
Company: tp23

 * @author Paul Hinds
 * @version $Id: FileInput.java,v 1.2 2007/01/28 10:25:48 teknopaul Exp $
 */
public class FileInput
	extends OSSpecific{

	private boolean abort = false;
    private String checkExists;

	public FileInput() {
	}

	/**
	 * Called to validate the user input
	 */
	public boolean validate(InstallerContext ctx) throws ValidationException{
		if (getInputResult() == null) { // this does not happen
            return false;
        }
		if(InputField.isTrue(checkExists)){
            File file = new File(getInputResult());
			if(!file.exists()){
				return false;
			}
		}
		return true;
	}

	public boolean isAbort() {
		return abort;
	}

	public void setAbort(boolean abort) {
		this.abort = abort;
	}

	public String getCheckExists() {
		return checkExists;
	}
	public void setCheckExists(String checkExists) {
		this.checkExists = checkExists;
	}
	public void setValue(String dir){
		setInputResult(dir);
	}

	/**
	 * Used by checkConfig to validate the configuration file.
	 * Not used at runtime.
	 * @return boolean
	 */
	public boolean validateObject() {
		if(getDisplayText()==null){
			System.out.println("File:displayText must be set");
			return false;
		}
		if(getProperty()==null){
			System.out.println("File:property must be set");
			return false;
		}
		if(getDefaultValue()==null){
			System.out.println("File:defaultValue must be set");
			return false;
		}
		if(!InputField.optionalBoolean(getCheckExists())){
			System.out.println("File:checkExists must be true or false or null");
			return false;
		}
		return true;
	}
}


text:
from django.core.validators import MaxLengthValidator

from openslides.core.config import ConfigVariable

def get_config_variables():
    """
    Generator which yields all config variables of this app.

    There are two main groups: 'General' and 'Projector'. The group 'General'
    has subgroups. The generator has to be evaluated during app loading
    (see apps.py).
    """
    yield ConfigVariable(
        name="general_event_name",
        default_value="OpenSlides",
        label="Event name",
        weight=110,
        group="General",
        subgroup="Event",
        validators=(MaxLengthValidator(100),),
    )

    yield ConfigVariable(
        name="general_event_description",
        default_value="Presentation and assembly system",
        label="Short description of event",
        weight=115,
        group="General",
        subgroup="Event",
        validators=(MaxLengthValidator(100),),
    )

    yield ConfigVariable(
        name="general_event_date",
        default_value="",
        label="Event date",
        weight=120,
        group="General",
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_location",
        default_value="",
        label="Event location",
        weight=125,
        group="General",
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_legal_notice",
        default_value='OpenSlides is a '
        "free web based presentation and assembly system for "
        "visualizing and controlling agenda, motions and "
        "elections of an assembly.",
        input_type="markupText",
        label="Legal notice",
        weight=132,
        group="General",
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_privacy_policy",
        default_value="",
        input_type="markupText",
        label="Privacy policy",
        weight=132,
        group="General",
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_welcome_title",
        default_value="Welcome to OpenSlides",
        label="Front page title",
        weight=134,
        group="General",
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_welcome_text",
        default_value="[Space for your welcome text.]",
        input_type="markupText",
        label="Front page text",
        weight=136,
        group="General",
        subgroup="Event",
    )

    # General System

    yield ConfigVariable(
        name="general_system_enable_anonymous",
        default_value=False,
        input_type="boolean",
        label="Allow access for anonymous guest users",
        weight=138,
        group="General",
        subgroup="System",
    )

    yield ConfigVariable(
        name="general_login_info_text",
        default_value="",
        label="Show this text on the login page",
        weight=140,
        group="General",
        subgroup="System",
    )

    # General export settings

    yield ConfigVariable(
        name="general_csv_separator",
        default_value=",",
        label="Separator used for all csv exports and examples",
        weight=142,
        group="General",
        subgroup="Export",
    )

    yield ConfigVariable(
        name="general_export_pdf_pagenumber_alignment",
        default_value="center",
        input_type="choice",
        label="Page number alignment in PDF",
        choices=(
            {"value": "left", "display_name": "Left"},
            {"value": "center", "display_name": "Center"},
            {"value": "right", "display_name": "Right"},
        ),
        weight=144,
        group="General",
        subgroup="Export",
    )

    yield ConfigVariable(
        name="general_export_pdf_fontsize",
        default_value="10",
        input_type="choice",
        label="Standard font size in PDF",
        choices=(
            {"value": "10", "display_name": "10"},
            {"value": "11", "display_name": "11"},
            {"value": "12", "display_name": "12"},
        ),
        weight=146,
        group="General",
        subgroup="Export",
    )

    # Projector

    yield ConfigVariable(
        name="projector_language",
        default_value="browser",
        input_type="choice",
        label="Projector language",
        choices=(
            {"value": "browser", "display_name": "Current browser language"},
            {"value": "en", "display_name": "English"},
            {"value": "de", "display_name": "Deutsch"},
            {"value": "fr", "display_name": "Français"},
            {"value": "es", "display_name": "Español"},
            {"value": "pt", "display_name": "Português"},
            {"value": "cs", "display_name": "Čeština"},
            {"value": "ru", "display_name": "русский"},
        ),
        weight=150,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_enable_logo",
        default_value=True,
        input_type="boolean",
        label="Show logo on projector",
        help_text="You can replace the logo by uploading an image and set it as "
        'the "Projector logo" in "files".',
        weight=152,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_enable_title",
        default_value=True,
        input_type="boolean",
        label="Show title and description of event on projector",
        weight=155,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_enable_header_footer",
        default_value=True,
        input_type="boolean",
        label="Display header and footer",
        weight=157,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_header_backgroundcolor",
        default_value="#317796",
        input_type="colorpicker",
        label="Background color of projector header and footer",
        weight=160,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_header_fontcolor",
        default_value="#F5F5F5",
        input_type="colorpicker",
        label="Font color of projector header and footer",
        weight=165,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_h1_fontcolor",
        default_value="#317796",
        input_type="colorpicker",
        label="Font color of projector headline",
        weight=170,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_default_countdown",
        default_value=60,
        input_type="integer",
        label="Predefined seconds of new countdowns",
        weight=185,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_background_color",
        default_value="#FFFFFF",
        input_type="colorpicker",
        label="Color for blanked projector",
        weight=190,
        group="Projector",
    )

    yield ConfigVariable(
        name="projector_currentListOfSpeakers_reference",
        default_value=1,
        input_type="integer",
        label="Projector reference for list of speakers",
        weight=201,
        group="Projector",
        hidden=True,
    )

    # Logos.
    yield ConfigVariable(
        name="logos_available",
        default_value=[
            "logo_projector_main",
            "logo_projector_header",
            "logo_web_header",
            "logo_pdf_header_L",
            "logo_pdf_header_R",
            "logo_pdf_footer_L",
            "logo_pdf_footer_R",
            "logo_pdf_ballot_paper",
        ],
        weight=300,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_projector_main",
        default_value={"display_name": "Projector logo", "path": ""},
        input_type="static",
        weight=301,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_projector_header",
        default_value={"display_name": "Projector header image", "path": ""},
        input_type="static",
        weight=302,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_web_header",
        default_value={"display_name": "Web interface header logo", "path": ""},
        input_type="static",
        weight=303,
        group="Logo",
        hidden=True,
    )

    # PDF logos
    yield ConfigVariable(
        name="logo_pdf_header_L",
        default_value={"display_name": "PDF header logo (left)", "path": ""},
        input_type="static",
        weight=310,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_header_R",
        default_value={"display_name": "PDF header logo (right)", "path": ""},
        input_type="static",
        weight=311,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_footer_L",
        default_value={"display_name": "PDF footer logo (left)", "path": ""},
        input_type="static",
        weight=312,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_footer_R",
        default_value={"display_name": "PDF footer logo (right)", "path": ""},
        input_type="static",
        weight=313,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_ballot_paper",
        default_value={"display_name": "PDF ballot paper logo", "path": ""},
        input_type="static",
        weight=314,
        group="Logo",
        hidden=True,
    )

    # Fonts
    yield ConfigVariable(
        name="fonts_available",
        default_value=["font_regular", "font_italic", "font_bold", "font_bold_italic"],
        weight=320,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_regular",
        default_value={
            "display_name": "Font regular",
            "default": "static/fonts/Roboto-Regular.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_italic",
        default_value={
            "display_name": "Font italic",
            "default": "static/fonts/Roboto-Medium.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_bold",
        default_value={
            "display_name": "Font bold",
            "default": "static/fonts/Roboto-Condensed-Regular.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_bold_italic",
        default_value={
            "display_name": "Font bold italic",
            "default": "static/fonts/Roboto-Condensed-Light.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    # Custom translations
    yield ConfigVariable(
        name="translations",
        label="Custom translations",
        default_value=[],
        input_type="translations",
        weight=1000,
        group="Custom translations",
    )


text:
@interface COBranch (Graphviz)
- (void) show;
- (void) showHistory;
@end


text:
package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.actuate.autoconfigure.cloudfoundry.AccessLevel;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.util.Assert;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

/**
 * Cloud Foundry security service to handle REST calls to the cloud controller and UAA.
 *
 * @author Madhura Bhave
 */
class CloudFoundrySecurityService {

	private final RestTemplate restTemplate;

	private final String cloudControllerUrl;

	private String uaaUrl;

	CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, String cloudControllerUrl,
			boolean skipSslValidation) {
		Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null");
		Assert.notNull(cloudControllerUrl, "CloudControllerUrl must not be null");
		if (skipSslValidation) {
			restTemplateBuilder = restTemplateBuilder.requestFactory(SkipSslVerificationHttpRequestFactory.class);
		}
		this.restTemplate = restTemplateBuilder.build();
		this.cloudControllerUrl = cloudControllerUrl;
	}

	/**
	 * Return the access level that should be granted to the given token.
	 * @param token the token
	 * @param applicationId the cloud foundry application ID
	 * @return the access level that should be granted
	 * @throws CloudFoundryAuthorizationException if the token is not authorized
	 */
	AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException {
		try {
			URI uri = getPermissionsUri(applicationId);
			RequestEntity<?> request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build();
			Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody();
			if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) {
				return AccessLevel.FULL;
			}
			return AccessLevel.RESTRICTED;
		}
		catch (HttpClientErrorException ex) {
			if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
				throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
			}
			throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex);
		}
		catch (HttpServerErrorException ex) {
			throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable");
		}
	}

	private URI getPermissionsUri(String applicationId) {
		try {
			return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId + "/permissions");
		}
		catch (URISyntaxException ex) {
			throw new IllegalStateException(ex);
		}
	}

	/**
	 * Return all token keys known by the UAA.
	 * @return a list of token keys
	 */
	Map<String, String> fetchTokenKeys() {
		try {
			return extractTokenKeys(this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class));
		}
		catch (HttpStatusCodeException ex) {
			throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable");
		}
	}

	private Map<String, String> extractTokenKeys(Map<?, ?> response) {
		Map<String, String> tokenKeys = new HashMap<>();
		for (Object key : (List<?>) response.get("keys")) {
			Map<?, ?> tokenKey = (Map<?, ?>) key;
			tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value"));
		}
		return tokenKeys;
	}

	/**
	 * Return the URL of the UAA.
	 * @return the UAA url
	 */
	String getUaaUrl() {
		if (this.uaaUrl == null) {
			try {
				Map<?, ?> response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class);
				this.uaaUrl = (String) response.get("token_endpoint");
			}
			catch (HttpStatusCodeException ex) {
				throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
						"Unable to fetch token keys from UAA");
			}
		}
		return this.uaaUrl;
	}

}


text:
const nodeExternals = require('webpack-node-externals')
const merge = require("webpack-merge")
const commonConfig = require("./scommons.webpack.config.js")

module.exports = merge(commonConfig, {

  output: {
    libraryTarget: 'commonjs'
  },
  mode: 'development',
  target: 'node', // important in order not to bundle built-in modules like path, fs, etc.
  externals: [nodeExternals()] // in order to ignore all modules in node_modules folder
})


text:
package org.toobs.framework.servlet.filters.compression;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FilterResponseWrapper extends HttpServletResponseWrapper {
  private ByteArrayOutputStream output;
  private FilterPrintWriter writer;
  private HttpServletResponse origResponse;
  private int contentLength;
  private boolean encodingSpecified = false;

  public FilterResponseWrapper(HttpServletResponse httpservletresponse) {
    super(httpservletresponse);
    output = null;
    writer = null;
    output = new ByteArrayOutputStream();
    origResponse = httpservletresponse;
  }

  public byte[] getData() {
    try {
      finishResponse();
    }
    catch(Exception exception) { }
    return output.toByteArray();
  }

  public ServletOutputStream getOutputStream() {
    return new FilterOutputStream(output);
  }

  public ServletOutputStream createOutputStream() throws IOException {
    return new FilterOutputStream(output);
  }

  public PrintWriter getWriter() throws IOException {
    if(writer != null) {
      return writer;
    } else {
      ServletOutputStream servletoutputstream = getOutputStream();
      writer = new FilterPrintWriter(new OutputStreamWriter(servletoutputstream, origResponse.getCharacterEncoding()), true);
      return writer;
    }
  }

  public void finishResponse() {
    try {
      if (writer != null) {
        writer.reallyClose();
      } else if (output != null) {
        output.flush();
        output.close();
      }
    }
    catch (IOException ioexception) {}
  }

  public void flushBuffer() throws IOException {
    output.flush();
  }

  public void setContentLength(int i) {
    contentLength = i;
    super.setContentLength(i);
  }

  public int getContentLength() {
    return contentLength;
  }

  public void setContentType( String type )
  {
     String explicitType = type;

     // If a specific encoding has not already been set by the app,
     // let's see if this is a call to specify it.  If the content
     // type doesn't explicitly set an encoding, make it UTF-8.
     if (!encodingSpecified)
     {
        String lowerType = type.toLowerCase();

        // See if this is a call to explicitly set the character encoding.
        if (lowerType.indexOf( "charset" ) < 0)
        {
           // If no character encoding is specified, we still need to
           // ensure the app is specifying text content.
           if (lowerType.startsWith( "text/" ))
           {
              // App is sending a text response, but no encoding
              // is specified, so we'll force it to UTF-8.
              explicitType = type + "; charset=UTF-8";
           }
        }
        else
        {
           // App picked a specific encoding, so let's make
           // sure we don't override it.
           encodingSpecified = true;
        }
     }

     // Delegate to supertype to record encoding.
     super.setContentType( explicitType );
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.amazonaws.jmx.spi (AWS SDK for Java - 1.11.60)</title>
<meta name="date" content="2016-11-23">
<link rel="stylesheet" type="text/css" href="../../../../JavaDoc.css" title="Style">

com.amazonaws.jmx.spi

Interfaces

JmxInfoProvider

SdkMBeanRegistry

Classes

JmxInfoProvider.Factory

SdkMBeanRegistry.Factory


text:
namespace CloudFoundry.Loggregator.Client
{
    /// <summary>
    /// Enumeration of Application log message types
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Loggregator only returns 1 or 2")]
    public enum ApplicationLogMessageType
    {
        /// <summary>
        /// Application log message is output
        /// </summary>
        Output = 1,

        /// <summary>
        /// Application log message is error
        /// </summary>
        Error = 2
    }
}


text:
using DvachBrowser3.Posts;
using Template10.Mvvm;

namespace DvachBrowser3.ViewModels
{
    /// <summary>
    /// Модель представления поста.
    /// </summary>
    public sealed class PostViewModel : PostViewModelBase
    {
        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="postData">Данные поста.</param>
        /// <param name="parent">Родительская модель.</param>
        public PostViewModel(PostTree postData, IPostCollectionViewModel parent) : base(postData, parent)
        {
        }

        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="postData">Данные поста.</param>
        /// <param name="parent">Родительская модель.</param>
        /// <param name="omitPosts">Пропущено постов.</param>
        public PostViewModel(PostTree postData, IPostCollectionViewModel parent, int omitPosts) : base(postData, parent)
        {
            this.omitPosts = omitPosts;
        }

        /// <summary>
        /// Создать модель текста.
        /// </summary>
        /// <returns>Модель текста.</returns>
        protected override IPostTextViewModel CreateText()
        {
            return new PostTextViewModel(this, PostData);
        }

        /// <summary>
        /// Создать модель медиафайлов.
        /// </summary>
        /// <returns>Модель.</returns>
        protected override IPostMediaViewModel CreateMedia()
        {
            return new PostMediaViewModel(this, PostData);
        }

        /// <summary>
        /// Создать модель флагов.
        /// </summary>
        /// <returns>Модель флагов.</returns>
        protected override IPostFlagsViewModel CreateFlags()
        {
            return new PostFlagsViewModel(PostData, this);
        }

        /// <summary>
        /// Создать модель постера.
        /// </summary>
        /// <returns>Модель постера.</returns>
        protected override IPostNameViewModel CreateName()
        {
            return new PostNameViewModel(PostData, this);
        }

        /// <summary>
        /// Создать тэги.
        /// </summary>
        /// <returns></returns>
        protected override IPostTags CreateTags()
        {
            return new PostTags(this, PostData);
        }

        /// <summary>
        /// Пропущено постов.
        /// </summary>
        private int? omitPosts;

        /// <summary>
        /// Количество пропущенных постов.
        /// </summary>
        public override string OmitPostCountStr => omitPosts?.ToString();
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>jQuery custom scrollbar demo</title>

	<link href="jquery.mCustomScrollbar.css" rel="stylesheet" />

		malihu
		Plugin home
		Plugin demo

jQuery custom scrollbar callbacks demo

		 onScrollStart
		 onScroll
		 onTotalScroll
		 onTotalScrollBack
		 whileScrolling

		Content position:  Dragger position:  Scroll percentage:

		mcs.top returns content top position (mcs.left for left position). mcs.draggerTop returns dragger top position (mcs.draggerLeft for left position). mcs.topPct returns vertical scroll percentage (mcs.leftPct for horizontal).

		onTotalScrollOffset is set to  (callback will fire  pixels from bottom). onTotalScrollBackOffset is set to  (callback will fire  pixels from top).

Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.

Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.

Consectetur adipiscing elit. Nulla consectetur libero consectetur quam consequat nec tincidunt massa feugiat. Donec egestas mi turpis. Fusce adipiscing dui eu metus gravida vel facilisis ligula iaculis. Cras a rhoncus massa. Donec sed purus eget nunc placerat consequat.

Cras venenatis condimentum nibh a mollis. Duis id sapien nibh. Vivamus porttitor, felis quis blandit tincidunt, erat magna scelerisque urna, a faucibus erat nisl eget nisl. Aliquam consequat turpis id velit egestas a posuere orci semper. Mauris suscipit erat quis urna adipiscing ultricies. In hac habitasse platea dictumst. Nulla scelerisque lorem quis dui sagittis egestas.

Etiam sed massa felis, aliquam pellentesque est.

Nam eu arcu at purus tincidunt pharetra ultrices at ipsum. Mauris urna nunc, vulputate quis gravida in, pharetra id mauris. Ut sit amet mi dictum nulla lobortis adipiscing quis a nulla. Etiam diam ante, imperdiet vel scelerisque eget, venenatis non eros. Praesent ipsum sem, eleifend ut gravida eget, tristique id orci. Nam adipiscing, sem in mattis vulputate, risus libero adipiscing risus, eu molestie mi justo eget nulla.

Cras venenatis metus et urna egestas non laoreet orci rutrum. Pellentesque ullamcorper dictum nisl a tincidunt. Quisque et lacus quam, sed hendrerit mi. Mauris pretium, sapien et malesuada pulvinar, lorem leo viverra leo, et egestas mi nisl quis odio.

Aliquam erat volutpat. Sed urna arcu, tempus eu vulputate adipiscing, consectetur et orci. Vivamus congue, nunc vitae fringilla convallis, libero massa lacinia lorem, id convallis mauris elit ut leo. Nulla vel odio sem. Duis lorem urna, congue vitae rutrum sed, tincidunt vel tortor. In hac habitasse platea dictumst. Nunc vitae enim ante, vitae facilisis massa. Etiam sagittis sapien at nibh fermentum consectetur convallis lacus blandit.

Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.

Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.

Consectetur adipiscing elit. Nulla consectetur libero consectetur quam consequat nec tincidunt massa feugiat. Donec egestas mi turpis. Fusce adipiscing dui eu metus gravida vel facilisis ligula iaculis. Cras a rhoncus massa. Donec sed purus eget nunc placerat consequat.

Cras venenatis condimentum nibh a mollis. Duis id sapien nibh. Vivamus porttitor, felis quis blandit tincidunt, erat magna scelerisque urna, a faucibus erat nisl eget nisl. Aliquam consequat turpis id velit egestas a posuere orci semper. Mauris suscipit erat quis urna adipiscing ultricies. In hac habitasse platea dictumst. Nulla scelerisque lorem quis dui sagittis egestas.

Etiam sed massa felis, aliquam pellentesque est.

the end.


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Set of functions related to designer
 *
 * @package PhpMyAdmin
 */
use PMA\libraries\Message;
use PMA\libraries\plugins\SchemaPlugin;

if (! defined('PHPMYADMIN')) {
    exit;
}

require_once 'libraries/relation.lib.php';

/**
 * Function to get html to display a page selector
 *
 * @param array  $cfgRelation information about the configuration storage
 * @param string $db          database name
 *
 * @return string html content
 */
function PMA_getHtmlForPageSelector($cfgRelation, $db)
{
    return PMA\libraries\Template::get('database/designer/page_selector')
        ->render(
            array(
                'db' => $db,
                'cfgRelation' => $cfgRelation
            )
        );
}

/**
 * Function to get html for displaying the page edit/delete form
 *
 * @param string $db        database name
 * @param string $operation 'edit' or 'delete' depending on the operation
 *
 * @return string html content
 */
function PMA_getHtmlForEditOrDeletePages($db, $operation)
{
    return PMA\libraries\Template::get('database/designer/edit_delete_pages')
        ->render(
            array(
                'db' => $db,
                'operation' => $operation
            )
        );
}

/**
 * Function to get html for displaying the page save as form
 *
 * @param string $db database name
 *
 * @return string html content
 */
function PMA_getHtmlForPageSaveAs($db)
{
    return PMA\libraries\Template::get('database/designer/page_save_as')
        ->render(
            array(
                'db' => $db
            )
        );
}

/**
 * Retrieve IDs and names of schema pages
 *
 * @param string $db database name
 *
 * @return array array of schema page id and names
 */
function PMA_getPageIdsAndNames($db)
{
    $cfgRelation = PMA_getRelationsParam();
    $page_query = "SELECT `page_nr`, `page_descr` FROM "
        . PMA\libraries\Util::backquote($cfgRelation['db']) . "."
        . PMA\libraries\Util::backquote($cfgRelation['pdf_pages'])
        . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($db) . "'"
        . " ORDER BY `page_descr`";
    $page_rs = PMA_queryAsControlUser(
        $page_query, false, PMA\libraries\DatabaseInterface::QUERY_STORE
    );

    $result = array();
    while ($curr_page = $GLOBALS['dbi']->fetchAssoc($page_rs)) {
        $result[intval($curr_page['page_nr'])] = $curr_page['page_descr'];
    }
    return $result;
}

/**
 * Function to get html for displaying the schema export
 *
 * @param string $db   database name
 * @param int    $page the page to be exported
 *
 * @return string
 */
function PMA_getHtmlForSchemaExport($db, $page)
{
    /* Scan for schema plugins */
    /* @var $export_list SchemaPlugin[] */
    $export_list = PMA_getPlugins(
        "schema",
        'libraries/plugins/schema/',
        null
    );

    /* Fail if we didn't find any schema plugin */
    if (empty($export_list)) {
        return Message::error(
            __('Could not load schema plugins, please check your installation!')
        )->getDisplay();
    }

    return PMA\libraries\Template::get('database/designer/schema_export')
        ->render(
            array(
                'db' => $db,
                'page' => $page,
                'export_list' => $export_list
            )
        );
}

/**
 * Returns HTML for including some variable to be accessed by JavaScript
 *
 * @param array $script_tables        array on foreign key support for each table
 * @param array $script_contr         initialization data array
 * @param array $script_display_field display fields of each table
 * @param int   $display_page         page number of the selected page
 *
 * @return string html
 */
function PMA_getHtmlForJSFields(
    $script_tables, $script_contr, $script_display_field, $display_page
) {
    return PMA\libraries\Template::get('database/designer/js_fields')
        ->render(
            array(
                'script_tables' => $script_tables,
                'script_contr' => $script_contr,
                'script_display_field' => $script_display_field,
                'display_page' => $display_page
            )
        );
}

/**
 * Returns HTML for the menu bar of the designer page
 *
 * @param boolean $visualBuilder whether this is visual query builder
 * @param string  $selected_page name of the selected page
 * @param array   $params_array  array with class name for various buttons on side
 *                               menu
 *
 * @return string html
 */
function PMA_getDesignerPageMenu($visualBuilder, $selected_page, $params_array)
{
    return PMA\libraries\Template::get('database/designer/side_menu')
        ->render(
            array(
                'visualBuilder' => $visualBuilder,
                'selected_page' => $selected_page,
                'params_array' => $params_array
            )
        );
}

/**
 * Returns array of stored values of Designer Settings
 *
 * @return array stored values
 */
function PMA_getSideMenuParamsArray()
{
    $params = array();

    $cfgRelation = PMA_getRelationsParam();

    if ($GLOBALS['cfgRelation']['designersettingswork']) {

        $query = 'SELECT `settings_data` FROM '
            . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
            . PMA\libraries\Util::backquote($cfgRelation['designer_settings'])
            . ' WHERE ' . PMA\libraries\Util::backquote('username') . ' = "'
            . $GLOBALS['cfg']['Server']['user'] . '";';

        $result = $GLOBALS['dbi']->fetchSingleRow($query);

        $params = json_decode($result['settings_data'], true);
    }

    return $params;
}

/**
 * Returns class names for various buttons on Designer Side Menu
 *
 * @return array class names of various buttons
 */
function PMA_returnClassNamesFromMenuButtons()
{
    $classes_array = array();
    $params_array = PMA_getSideMenuParamsArray();

    if (isset($params_array['angular_direct'])
        && $params_array['angular_direct'] == 'angular'
    ) {
        $classes_array['angular_direct'] = 'M_butt_Selected_down';
    } else {
        $classes_array['angular_direct'] = 'M_butt';
    }

    if (isset($params_array['snap_to_grid'])
        && $params_array['snap_to_grid'] == 'on'
    ) {
        $classes_array['snap_to_grid'] = 'M_butt_Selected_down';
    } else {
        $classes_array['snap_to_grid'] = 'M_butt';
    }

    if (isset($params_array['pin_text'])
        && $params_array['pin_text'] == 'true'
    ) {
        $classes_array['pin_text'] = 'M_butt_Selected_down';
    } else {
        $classes_array['pin_text'] = 'M_butt';
    }

    if (isset($params_array['relation_lines'])
        && $params_array['relation_lines'] == 'false'
    ) {
        $classes_array['relation_lines'] = 'M_butt_Selected_down';
    } else {
        $classes_array['relation_lines'] = 'M_butt';
    }

    if (isset($params_array['small_big_all'])
        && $params_array['small_big_all'] == 'v'
    ) {
        $classes_array['small_big_all'] = 'M_butt_Selected_down';
    } else {
        $classes_array['small_big_all'] = 'M_butt';
    }

    if (isset($params_array['side_menu'])
        && $params_array['side_menu'] == 'true'
    ) {
        $classes_array['side_menu'] = 'M_butt_Selected_down';
    } else {
        $classes_array['side_menu'] = 'M_butt';
    }

    return $classes_array;
}

/**
 * Returns HTML for the canvas element
 *
 * @return string html
 */
function PMA_getHTMLCanvas()
{
    return PMA\libraries\Template::get('database/designer/canvas')->render();
}

/**
 * Return HTML for the table list
 *
 * @param array $tab_pos      table positions
 * @param int   $display_page page number of the selected page
 *
 * @return string html
 */
function PMA_getHTMLTableList($tab_pos, $display_page)
{
    return PMA\libraries\Template::get('database/designer/table_list')
        ->render(
            array(
                'tab_pos' => $tab_pos,
                'display_page' => $display_page
            )
        );
}

/**
 * Get HTML to display tables on designer page
 *
 * @param array $tab_pos                  tables positions
 * @param int   $display_page             page number of the selected page
 * @param array $tab_column               table column info
 * @param array $tables_all_keys          all indices
 * @param array $tables_pk_or_unique_keys unique or primary indices
 *
 * @return string html
 */
function PMA_getDatabaseTables(
    $tab_pos, $display_page, $tab_column, $tables_all_keys, $tables_pk_or_unique_keys
) {
    return PMA\libraries\Template::get('database/designer/database_tables')
        ->render(
            array(
                'tab_pos' => $tab_pos,
                'display_page' => $display_page,
                'tab_column' => $tab_column,
                'tables_all_keys' => $tables_all_keys,
                'tables_pk_or_unique_keys' => $tables_pk_or_unique_keys
            )
        );
}

/**
 * Returns HTML for the new relations panel.
 *
 * @return string html
 */
function PMA_getNewRelationPanel()
{
    return PMA\libraries\Template::get('database/designer/new_relation_panel')
        ->render();
}

/**
 * Returns HTML for the relations delete panel
 *
 * @return string html
 */
function PMA_getDeleteRelationPanel()
{
    return PMA\libraries\Template::get('database/designer/delete_relation_panel')
        ->render();
}

/**
 * Returns HTML for the options panel
 *
 * @return string html
 */
function PMA_getOptionsPanel()
{
    return PMA\libraries\Template::get('database/designer/options_panel')->render();
}

/**
 * Get HTML for the 'rename to' panel
 *
 * @return string html
 */
function PMA_getRenameToPanel()
{
    return PMA\libraries\Template::get('database/designer/rename_to_panel')
        ->render();
}

/**
 * Returns HTML for the 'having' panel
 *
 * @return string html
 */
function PMA_getHavingQueryPanel()
{
    return PMA\libraries\Template::get('database/designer/having_query_panel')
        ->render();
}

/**
 * Returns HTML for the 'aggregate' panel
 *
 * @return string html
 */
function PMA_getAggregateQueryPanel()
{
    return PMA\libraries\Template::get('database/designer/aggregate_query_panel')
        ->render();
}

/**
 * Returns HTML for the 'where' panel
 *
 * @return string html
 */
function PMA_getWhereQueryPanel()
{
    return PMA\libraries\Template::get('database/designer/where_query_panel')
        ->render();
}

/**
 * Returns HTML for the query details panel
 *
 * @return string html
 */
function PMA_getQueryDetails()
{
    return PMA\libraries\Template::get('database/designer/query_details')->render();
}


text:
SET SERVEROUTPUT ON

PROMPT ================================
PROMPT |        Running Part 7        |
PROMPT |         Extra Credit         |
PROMPT ================================

--Reset tables to default
SET TERMOUT OFF
@table.sql
@values.sql
SET TERMOUT ON

DECLARE

    CURSOR iv_cursor IS
        SELECT mi.common_name AS common_name, aos.stock_id AS stock_id, aos.number_in_stock AS number_in_stock
        FROM aquatic_organism_stock aos, marine_invertebrates mi
        WHERE mi.scientific_name = aos.scientific_name;

    cursor_num iv_cursor%ROWTYPE;

BEGIN

	DBMS_OUTPUT.PUT_LINE('#Running cursor');
    OPEN iv_cursor;
    LOOP
        FETCH iv_cursor INTO cursor_num;
        EXIT WHEN iv_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(cursor_num.common_name || ', ' || cursor_num.stock_id  || ', ' || cursor_num.number_in_stock);
    END LOOP;

	DBMS_OUTPUT.PUT_LINE('#Cursor complete');

    CLOSE iv_cursor;
END;
/