text:
package chyle

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/antham/envh"
)

func TestBuildChangelog(t *testing.T) {
	restoreEnvs()
	p, err := os.Getwd()

	if err != nil {
		log.Fatal(err)
	}

	setenv("CHYLE_GIT_REPOSITORY_PATH", p+"/testing-repository")
	setenv("CHYLE_GIT_REFERENCE_FROM", "test2")
	setenv("CHYLE_GIT_REFERENCE_TO", "head")
	setenv("CHYLE_MATCHERS_TYPE", "regular")
	setenv("CHYLE_EXTRACTORS_MESSAGE_ORIGKEY", "message")
	setenv("CHYLE_EXTRACTORS_MESSAGE_DESTKEY", "subject")
	setenv("CHYLE_EXTRACTORS_MESSAGE_REG", "(.{1,50})")
	setenv("CHYLE_SENDERS_STDOUT_FORMAT", "json")

	f, err := ioutil.TempFile(p+"/testing-repository", "test")

	if err != nil {
		log.Fatal(err)
	}

	defer func() {
		if err = f.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	config, err := envh.NewEnvTree("CHYLE", "_")

	if err != nil {
		log.Fatal(err)
	}

	oldStdout := os.Stdout
	os.Stdout = f

	err = BuildChangelog(&config)

	os.Stdout = oldStdout

	assert.NoError(t, err)

	b, err := ioutil.ReadFile(f.Name())

	assert.NoError(t, err)

	type Data struct {
		ID             string `json:"id"`
		AuthorDate     string `json:"authorDate"`
		AuthorEmail    string `json:"authorEmail"`
		AuthorName     string `json:"authorName"`
		Type           string `json:"type"`
		CommitterEmail string `json:"committerEmail"`
		CommitterName  string `json:"committerName"`
		Message        string `json:"message"`
		Subject        string `json:"subject"`
	}

	results := struct {
		Datas     []Data            `json:"datas"`
		Metadatas map[string]string `json:"metadatas"`
	}{}

	j := json.NewDecoder(bytes.NewBuffer(b))
	err = j.Decode(&results)

	assert.NoError(t, err)
	assert.Len(t, results.Datas, 2)
	assert.Len(t, results.Metadatas, 0)

	expected := []map[string]string{
		{
			"authorEmail":    "whatever@example.com",
			"authorName":     "whatever",
			"committerEmail": "whatever@example.com",
			"committerName":  "whatever",
			"type":           "regular",
			"message":        "feat(file8) : new file 8\n\ncreate a new file 8\n",
			"subject":        "feat(file8) : new file 8",
		},
		{
			"authorEmail":    "whatever@example.com",
			"authorName":     "whatever",
			"committerEmail": "whatever@example.com",
			"committerName":  "whatever",
			"type":           "regular",
			"message":        "feat(file7) : new file 7\n\ncreate a new file 7\n",
			"subject":        "feat(file7) : new file 7",
		},
	}

	for i, r := range results.Datas {
		assert.Equal(t, expected[i]["authorEmail"], r.AuthorEmail)
		assert.Equal(t, expected[i]["authorName"], r.AuthorName)
		assert.Equal(t, expected[i]["type"], r.Type)
		assert.Equal(t, expected[i]["committerEmail"], r.CommitterEmail)
		assert.Equal(t, expected[i]["committerName"], r.CommitterName)
		assert.Equal(t, expected[i]["message"], r.Message)
		assert.Equal(t, expected[i]["subject"], r.Subject)
	}
}

func TestBuildChangelogWithAnErrorFromGitPackage(t *testing.T) {
	restoreEnvs()
	p, err := os.Getwd()

	if err != nil {
		log.Fatal(err)
	}

	setenv("CHYLE_GIT_REPOSITORY_PATH", p+"/whatever")
	setenv("CHYLE_GIT_REFERENCE_FROM", "test2")
	setenv("CHYLE_GIT_REFERENCE_TO", "head")
	setenv("CHYLE_MATCHERS_TYPE", "regular")
	setenv("CHYLE_EXTRACTORS_MESSAGE_ORIGKEY", "message")
	setenv("CHYLE_EXTRACTORS_MESSAGE_DESTKEY", "subject")
	setenv("CHYLE_EXTRACTORS_MESSAGE_REG", "(.{1,50})")
	setenv("CHYLE_SENDERS_STDOUT_FORMAT", "json")

	config, err := envh.NewEnvTree("CHYLE", "_")

	if err != nil {
		log.Fatal(err)
	}

	err = BuildChangelog(&config)

	assert.Error(t, err)
	assert.Regexp(t, `check ".*?" is an existing git repository path`, err.Error())
}

func TestBuildChangelogWithAnErrorFromConfigPackage(t *testing.T) {
	restoreEnvs()
	p, err := os.Getwd()

	if err != nil {
		log.Fatal(err)
	}

	setenv("CHYLE_GIT_REPOSITORY_PATH", p+"/testing-repository")
	setenv("CHYLE_GIT_REFERENCE_FROM", "test2")
	setenv("CHYLE_GIT_REFERENCE_TO", "head")
	setenv("CHYLE_SENDERS_STDOUT_FORMAT", "whatever")

	config, err := envh.NewEnvTree("CHYLE", "_")

	if err != nil {
		log.Fatal(err)
	}

	err = BuildChangelog(&config)

	assert.Error(t, err)
	assert.EqualError(t, err, `"CHYLE_SENDERS_STDOUT_FORMAT" "whatever" doesn't exist`)
}

func TestBuildChangelogWithDebuggingEnabled(t *testing.T) {
	restoreEnvs()
	p, err := os.Getwd()

	if err != nil {
		log.Fatal(err)
	}

	EnableDebugging = true

	setenv("CHYLE_GIT_REPOSITORY_PATH", p+"/testing-repository")
	setenv("CHYLE_GIT_REFERENCE_FROM", "test2")
	setenv("CHYLE_GIT_REFERENCE_TO", "head")
	setenv("CHYLE_MATCHERS_TYPE", "regular")
	setenv("CHYLE_EXTRACTORS_MESSAGE_ORIGKEY", "message")
	setenv("CHYLE_EXTRACTORS_MESSAGE_DESTKEY", "subject")
	setenv("CHYLE_EXTRACTORS_MESSAGE_REG", "(.{1,50})")

	config, err := envh.NewEnvTree("CHYLE", "_")

	if err != nil {
		log.Fatal(err)
	}

	assert.NoError(t, err)

	tmpLogger := logger

	b := []byte{}
	buffer := bytes.NewBuffer(b)

	logger = log.New(buffer, "CHYLE - ", log.Ldate|log.Ltime)

	err = BuildChangelog(&config)
	assert.NoError(t, err)

	logger = tmpLogger

	EnableDebugging = false

	assert.Regexp(t, `CHYLE - \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} {\n\s+"GIT": {\n\s+"REPOSITORY": {\n`, buffer.String())
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;

namespace tpscabinet
{
    public partial class frm_notify : Form
    {
        private delegate void delegate_Hide();
        private System.Timers.Timer FadeOutTimer;
        private System.Timers.Timer DelayTimer;
        public int HideDelay = 4000;
        private GraphicsPath BorderPath;
        private GraphicsPath RegionPath;
        private Pen BorderPen;
        private string strTip_package1;
        private string strTip_package2;
        private bool strTip_package1_shown;
        private bool strTip_package2_shown;
        private string saved_lbl_Info;
        private Image saved_pic_Graph;
        private CabinetScraper tps_cabinet;

        public frm_notify()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
            this.UpdateStyles();

            strTip_package1_shown = false;
            strTip_package2_shown = false;
            saved_pic_Graph = null;
            saved_lbl_Info = "";
            lbl_package1.Text = "";
            lbl_package2.Text = "";
            strTip_package1 = "";
            strTip_package2 = "";

            BorderPen = new Pen(Color.FromArgb(118, 118, 118));
            this.SetStyle(ControlStyles.Opaque, true);

            FadeOutTimer = new System.Timers.Timer(120);
            DelayTimer = new System.Timers.Timer(this.HideDelay);
            FadeOutTimer.Elapsed += (o, e) => {
                try {
                    this.Invoke(new delegate_FadeOutAnimation(FadeOutAnimation));
                }
                catch {}
            };
            DelayTimer.Elapsed += (o, e) => {
                try {
                    this.Invoke(new delegate_StartFadeOutAnimation(StartFadeOutAnimation));
                }
                catch {}
            };

            /// set for all controls transparent BG, and click handler
            foreach (Control ctrl in this.Controls)
            {
                ctrl.BackColor = Color.Transparent;
                ctrl.Click += ctrl_Click;
            }
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            this.BorderPath = helper.CreateRoundRect(new Rectangle(0, 0, this.Width - 1, this.Height - 1), 4, helper.RectangleCorners.All);
            this.RegionPath = helper.CreateRoundRect(new Rectangle(0, 0, this.Width, this.Height), 4, helper.RectangleCorners.All);
            this.Region = new System.Drawing.Region(RegionPath);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (BorderPath != null && RegionPath != null)
            {
                e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
                e.Graphics.CompositingQuality = CompositingQuality.AssumeLinear;
                e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                e.Graphics.FillPath(new LinearGradientBrush(new Rectangle(0, 0, this.Width, this.Height), Color.FromArgb(254, 254, 254), Color.FromArgb(228, 229, 240), LinearGradientMode.Vertical), BorderPath);
                e.Graphics.DrawPath(BorderPen, BorderPath);
            }
        }

        /// <summary>
        /// Hide window on control click
        /// </summary>
        void ctrl_Click(object sender, EventArgs e)
        {
            this.DelayTimer.Stop();
            this.FadeOutTimer.Stop();
            this.Hide();
        }

        public void Show(int Delay)
        {
            this.HideDelay = Delay;
            this.DelayedFadeOut();
            base.Show();
        }

        public new void Show()
        {
            this.Show(this.HideDelay);
        }

        /// <summary>
        /// show some info
        /// </summary>
        /// <param name="Info">info string</param>
        public void FillData(string Info)
        {
            this.SuspendLayout();
            lbl_Info.Text = Info;
            lbl_Info.Left = 7;
            pic_Graph.Visible = false;
            tbl_Packages.Visible = false;
            this.ResumeLayout();
        }

        /// <summary>
        /// Fill form data
        /// </summary>
        /// <param name="tps_cabinet">scraped cabinet data</param>
        public void FillData(CabinetScraper tps_cabinet)
        {
            this.tps_cabinet = tps_cabinet;
            if (tps_cabinet.Login.Trim() == "" || tps_cabinet.Password.Trim() == "")
                this.FillData("\r\nВы не ввели свои логин\\пароль\r\n\r\n");
            else if (tps_cabinet.LastError != null && tps_cabinet.LastError.isCritical)
                this.FillData("\r\n" + tps_cabinet.LastError.Message + "\r\n\r\n");
            else if (tps_cabinet.LastUpdate == DateTime.MinValue)
                this.FillData("\r\nОбновление...\r\n\r\n");
            else
            {
                this.SuspendLayout();
                tbl_Packages.Visible = true;

                lbl_Info.Left = 91;
                ///// draw traf use piechart ////
                if ((tps_cabinet.TraffUsed + tps_cabinet.TraffLeft) != 0)
                {
                    Bitmap bmp = new Bitmap(pic_Graph.Width, pic_Graph.Height);
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.SmoothingMode = SmoothingMode.AntiAlias;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode = InterpolationMode.Bicubic;
                        g.Clear(Color.Transparent);
                        g.FillEllipse(Brushes.LightBlue, 0, 0, bmp.Width - 1, bmp.Height - 1);
                        float Prepaid_SweepAngle = tps_cabinet.TraffUsed * 360 / tps_cabinet.TraffAll;
                        g.FillPie(Brushes.Red, 0, 0, bmp.Width - 1, bmp.Height - 1, 0, Prepaid_SweepAngle);
                        if (tps_cabinet.HasPackage) {
#if DEBUG
                            tps_cabinet.Packages[0].TraffLeft = 600;
                            tps_cabinet.Packages[1].TraffLeft = 600;
#endif
                            /// if have show first package
                            float Package1_SweepAngle = tps_cabinet.Packages[0].TraffLeft * 360 / tps_cabinet.TraffAll;
                            if (Package1_SweepAngle > Prepaid_SweepAngle) Package1_SweepAngle = Prepaid_SweepAngle; // if package traff more prepaid show only part
                            if (tps_cabinet.TraffLeft == 0)
                            {
                                Package1_SweepAngle = tps_cabinet.Packages[0].TraffLeft * 360 / tps_cabinet.Packages[0].TraffAll;
                                g.FillPie(Brushes.DarkSeaGreen, 0, 0, bmp.Width - 1, bmp.Height - 1, 0, -Package1_SweepAngle);
                            }
                            else if (!Properties.Settings.Default.DisablePackageDiagramm)
                                g.FillPie(Brushes.DarkSeaGreen, 7, 7, bmp.Width - 15, bmp.Height - 15, Prepaid_SweepAngle, -Package1_SweepAngle);

                            //// if have second package and have space show it
                            if (tps_cabinet.Packages.Count > 1 && Package1_SweepAngle != Prepaid_SweepAngle)
                            {
                                float Package2_SweepAngle = tps_cabinet.Packages[1].TraffLeft * 360 / tps_cabinet.TraffAll;
                                if (Package2_SweepAngle > (Prepaid_SweepAngle - Package1_SweepAngle)) Package2_SweepAngle = Prepaid_SweepAngle - Package1_SweepAngle; // if package traff more prepaid+package1 show only part
                                if (tps_cabinet.TraffLeft == 0 && !Properties.Settings.Default.DisablePackageDiagramm)
                                {
                                    Package2_SweepAngle = tps_cabinet.Packages[1].TraffLeft * 360 / tps_cabinet.Packages[0].TraffAll;
                                    if (Package2_SweepAngle > (360 - Package1_SweepAngle)) Package2_SweepAngle = 360 - Package1_SweepAngle; // if package traff more package1 show only part
                                    g.FillPie(Brushes.MediumTurquoise, 7, 7, bmp.Width - 15, bmp.Height - 15, -Package1_SweepAngle, -Package2_SweepAngle);
                                }
                                else if (!Properties.Settings.Default.DisablePackageDiagramm)
                                    g.FillPie(Brushes.MediumTurquoise, 19, 19, bmp.Width - 39, bmp.Height - 39, Prepaid_SweepAngle - Package1_SweepAngle, -Package2_SweepAngle);
                            }
                        }
                    }
                    if (pic_Graph.Image != null)
                    {
                        pic_Graph.Image.Dispose();
                        pic_Graph.Image = null;
                    }
                    pic_Graph.Image = bmp;
                    pic_Graph.Visible = true;
                }
                else
                    pic_Graph.Visible = false;
                ////////////////////////////////

                int MinFromLastUpdate = (int)(DateTime.Now - tps_cabinet.LastUpdate).TotalMinutes;
                lbl_Info.Text = "Обновлено: " + tps_cabinet.LastUpdate.ToString("d MMM HH:mm") + " (" + ((MinFromLastUpdate == 0) ? "только что" : MinFromLastUpdate + " мин. назад") + ")\r\n";

                string DayUsed = "";
                if (tps_cabinet.TraffUsed > 0 && tps_cabinet.TraffLeft != 0)
                    DayUsed = " (" + (tps_cabinet.TraffUsed / DateTime.Now.Day).ToString("f2") + " Мб/день)";

                if (tps_cabinet.HasPackage && tps_cabinet.TraffLeft == 0)
                    lbl_Info.Text += "Использовано (П): " + tps_cabinet.Packages[0].TraffUsed + " Мб\r\n";
                else
                    lbl_Info.Text += "Использовано: " + tps_cabinet.TraffUsed + " Мб" + DayUsed + "\r\n";

                string PlaningDayUse = "";
                if (tps_cabinet.TraffLeft > 0 && (DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) - DateTime.Now.Day) > 0)
                    PlaningDayUse = " (" + (tps_cabinet.TraffLeft / (DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) - DateTime.Now.Day)).ToString("f2") + " Мб/день)";

                if (tps_cabinet.HasPackage && tps_cabinet.TraffLeft == 0)
                {
                    if (tps_cabinet.Packages[0].TraffLeft > 0)
                    {
                        if (tps_cabinet.Packages[0].DaysLeft > 0)
                            PlaningDayUse = " (" + (tps_cabinet.Packages[0].TraffLeft / (tps_cabinet.Packages[0].DaysLeft)).ToString("f2") + " Мб/день)";
                        else if (tps_cabinet.Packages[0].TotalHoursLeft > 0)
                            PlaningDayUse = " (" + (tps_cabinet.Packages[0].TraffLeft / (tps_cabinet.Packages[0].TotalHoursLeft)).ToString("f2") + " Мб/час)";
                    }
                    lbl_Info.Text += "Остаток (П): " + tps_cabinet.Packages[0].TraffLeft + " Мб" + PlaningDayUse + "\r\n";
                }
                else
                    lbl_Info.Text += "Остаток: " + tps_cabinet.TraffLeft + " Мб" + PlaningDayUse + "\r\n";

                lbl_Info.Text += "Баланс: $ " + tps_cabinet.Balance + " / Курс: " + tps_cabinet.Kurs.ToString("f2") + "\r\n";
                lbl_Info.Text += "К оплате (1-го): " + ((tps_cabinet.AbonentPlata - tps_cabinet.Balance) * tps_cabinet.Kurs).ToString("f2") + "\r\n";

                if (tps_cabinet.Packages.Count > 0)
                {
                    lbl_package1.ForeColor = Color.DarkGreen;
                    //lbl_package1.Text = tps_cabinet.Packages[0].DaysLeft + " " + tps_cabinet.Packages[0].DaysLeftPlural + " - " + tps_cabinet.Packages[0].TraffLeft.ToString("f0") + " Мб";
                    lbl_package1.Text = tps_cabinet.Packages[0].TimeLeftStr + " " + tps_cabinet.Packages[0].TraffLeft.ToString("f0") + " Мб";
                    strTip_package1 = "Пакет: " + tps_cabinet.Packages[0].Name+"\r\n";
                    strTip_package1 += "Активирован: " + tps_cabinet.Packages[0].StartDT.ToString("dd.MM.yy в H:mm") + "\r\n";
                    strTip_package1 += "Кончается: " + tps_cabinet.Packages[0].EndDT.ToString("dd.MM.yy в H:mm")+ "\r\n";
                    strTip_package1 += "Всего:" + tps_cabinet.Packages[0].TraffAll.ToString("f0") + " Мб\r\n";
                    strTip_package1 += "Остаток:" + tps_cabinet.Packages[0].TraffLeft.ToString("f0") + " Мб\r\n";
                }
                else
                {
                    lbl_package1.ForeColor = SystemColors.ControlText;
                    lbl_package1.Text = "Нет пакетов";
                    strTip_package1 = "";

                }
                if (tps_cabinet.Packages.Count > 1)
                {
                    //lbl_package2.Text = tps_cabinet.Packages[1].DaysLeft + " " + tps_cabinet.Packages[1].DaysLeftPlural + " - " + tps_cabinet.Packages[1].TraffLeft.ToString("f0") + " Мб";
                    lbl_package2.Text = tps_cabinet.Packages[1].TimeLeftStr + " " + tps_cabinet.Packages[1].TraffLeft.ToString("f0") + " Мб";
                    strTip_package2 = "Пакет: " + tps_cabinet.Packages[1].Name + "\r\n";
                    strTip_package2 += "Активирован: " + tps_cabinet.Packages[1].StartDT.ToString("dd.MM.yy в H:mm") + "\r\n";
                    strTip_package2 += "Кончается: " + tps_cabinet.Packages[1].EndDT.ToString("dd.MM.yy в H:mm")+ "\r\n";
                    strTip_package2 += "Всего:" + tps_cabinet.Packages[1].TraffAll.ToString("f0") + " Мб\r\n";
                    strTip_package2 += "Остаток:" + tps_cabinet.Packages[1].TraffLeft.ToString("f0") + " Мб\r\n";
                }
                else
                {
                    strTip_package2 = "";
                    lbl_package2.Text = "";
                }
                this.ResumeLayout();

                //AppIcon.Text += "CabinetID = " + tps_cabinet.CabinetID + "\r\n";
                ///AppIcon.Text += "AbonentPlata = " + tps_cabinet.AbonentPlata + "\r\n";
            }
        }

        /// <summary>
        /// Start fadeout animation
        /// </summary>
        delegate void delegate_StartFadeOutAnimation();
        void StartFadeOutAnimation()
        {
            if (this.ClientRectangle.Contains(this.PointToClient(MousePosition))) return;
            DelayTimer.Stop();
            FadeOutTimer.Start();
        }

        /// <summary>
        /// Process fadeout animation
        /// </summary>
        delegate void delegate_FadeOutAnimation();
        void FadeOutAnimation()
        {
            if (this.ClientRectangle.Contains(this.PointToClient(MousePosition)))
            {
                DelayedFadeOut();
                return;
            }
            this.Opacity -= .04;
            if (this.Opacity <= 0.2)
            {
                FadeOutTimer.Stop();
                this.Hide();
            }
        }

        /// <summary>
        /// Delayed fadeout
        /// </summary>
        public void DelayedFadeOut()
        {
            FadeOutTimer.Stop();
            this.Opacity = 1;
            DelayTimer.Stop();

            if (this.HideDelay > 0)
            {
                DelayTimer.Interval = this.HideDelay;
                DelayTimer.Start();
            }
        }

        private void frm_notify_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                FadeOutTimer.Stop();
                DelayTimer.Stop();
                FadeOutTimer.Dispose();
                DelayTimer.Dispose();
                if (BorderPath != null) BorderPath.Dispose();
                if (RegionPath != null) RegionPath.Dispose();
                if (BorderPen != null) BorderPen.Dispose();
            }
            catch { }
        }

        private void lbl_package1_MouseHover(object sender, EventArgs e)
        {
            if (strTip_package1 != "" && !strTip_package1_shown)
            {
                this.SuspendLayout();
                saved_lbl_Info = lbl_Info.Text;
                lbl_Info.Text = strTip_package1;
                this.DrawPackagePieChart(this.tps_cabinet.Packages[0], Brushes.DarkSeaGreen);
                strTip_package1_shown = true;
            }
        }

        private void lbl_package2_MouseHover(object sender, EventArgs e)
        {
            if (strTip_package2 != "" && !strTip_package2_shown)
            {
                this.SuspendLayout();
                saved_lbl_Info = lbl_Info.Text;
                lbl_Info.Text = strTip_package2;
                this.DrawPackagePieChart(this.tps_cabinet.Packages[1], Brushes.LightSeaGreen);
                strTip_package2_shown = true;
            }
        }

        private void DrawPackagePieChart(Package pkg, Brush graphBrush) {
            ///// draw traf use piechart ////
            if (pkg.TraffAll != 0 && pic_Graph.Visible)
            {
                Bitmap bmp = new Bitmap(pic_Graph.Width, pic_Graph.Height);
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.Bicubic;
                    g.Clear(Color.Transparent);
                    g.FillEllipse(graphBrush, 0, 0, bmp.Width - 1, bmp.Height - 1);
                    g.FillPie(Brushes.IndianRed, 0, 0, bmp.Width - 1, bmp.Height - 1, 0, pkg.TraffUsed * 360 / pkg.TraffAll);
                }
                if (pic_Graph.Image != null)
                {
                    saved_pic_Graph = (Image)pic_Graph.Image.Clone();
                    pic_Graph.Image.Dispose();
                    pic_Graph.Image = null;
                }
                pic_Graph.Image = bmp;
            }
        }

        private void lbl_package_MouseLeave(object sender, EventArgs e)
        {
            if (strTip_package1_shown || strTip_package2_shown)
            {
                if (pic_Graph.Visible && saved_pic_Graph != null)
                {
                    if (pic_Graph.Image != null)
                    {
                        pic_Graph.Image.Dispose();
                        pic_Graph.Image = null;
                    }
                    pic_Graph.Image = saved_pic_Graph;
                }
                lbl_Info.Text = saved_lbl_Info;
                this.ResumeLayout();
                strTip_package1_shown = false;
                strTip_package2_shown = false;
            }

        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
This package provides a low-level _library_ that performs static analysis
of Dart code. It is useful for tool
integration and embedding.

End-users should use the [dartanalyzer][analyzercli] command-line tool
to analyze their Dart code.

Integrators that want to add Dart support to their editor
should use the _Dart Analysis Server_.
The [Analysis Server API Specification][serverapi] is available.
If you are adding Dart support to an editor or IDE, please let us know
by emailing our [list][].

## Configuring the analyzer

Both `dartanalyzer` and Dart Analysis Server can be configured with either an
`analysis_options.yaml` or `.analysis_options` file. This YAML file can control
which files and paths are analyzed, which lints are applied, and more.

If you are embedding the analyzer library in your project, you are responsible
for finding the analysis options file, parsing it, and configuring the analyzer.

The analysis options file should live at the root of your project (for example,
next to your `pubspec.yaml`). Different embedders of analyzer, such as
`dartanalyzer` or Dart Analysis Server, may choose to find the file in various
different ways. Consult their documentation to learn more.

Here is an example file that instructs the analyzer to ignore two files:

```yaml
analyzer:
  exclude:
    - test/_data/p4/lib/lib1.dart
    - test/_data/p5/p5.dart
    - test/_data/bad*.dart
    - test/_brokendata/**
```

Note that you can use globs, as defined by the [glob package][glob].

Here is an example file that enables the analyzer's [strong mode][strongmode]:

```yaml
analyzer:
  strong-mode: true
```

Here is an example file that enables two lint rules:

```yaml
linter:
  rules:
    - camel_case_types
    - empty_constructor_bodies
```

Check out all the available [Dart lint rules][lintrules].

You can combine the `analyzer` section and the `linter` section into a single
configuration. Here is an example:

```yaml
analyzer:
  exclude:
    - test/_data/p4/lib/lib1.dart
linter:
  rules:
    - camel_case_types
```

## Who uses this library?

Many tools embed this library, such as:

* [dartfmt] - a formatter for Dart code
* [dartdoc] - a documentation generator for Dart code
* [Dart Analysis Server][analysis_sever] - a stateful server that supports IDEs and editors

## Support

Post issues and feature requests at https://github.com/dart-lang/sdk/issues

Questions and discussions are welcome at the
[Dart Analyzer Discussion Group][list].

## Background

The APIs in this package are, quite frankly, a mess at the moment. They were
originally machine generated by a translator and were based on an earlier Java
implementation. Several of the API's still look like their Java predecessors
(or worse) rather than clean Dart API's.

In addition, there is currently no clean distinction between public and internal
APIs. We plan to address this issue but doing so will, unfortunately,
require a large number of breaking changes. We will try to minimize the pain
this causes for our clients, but some pain is inevitable.

## License

See the [LICENSE] file.

[serverapi]: https://htmlpreview.github.io/?https://github.com/dart-lang/sdk/blob/master/pkg/analysis_server/doc/api.html
[analyzercli]: https://github.com/dart-lang/sdk/tree/master/pkg/analyzer_cli
[list]: https://groups.google.com/a/dartlang.org/forum/#!forum/analyzer-discuss
[lintrules]: http://dart-lang.github.io/linter/lints/
[strongmode]: https://github.com/dart-lang/dev_compiler/blob/master/STRONG_MODE.md
[glob]: https://pub.dartlang.org/packages/glob
[LICENSE]: https://github.com/dart-lang/sdk/blob/master/pkg/analyzer/LICENSE
[dartfmt]: https://github.com/dart-lang/dart_style
[dartdoc]: https://github.com/dart-lang/dartdoc
[analysis_sever]: https://github.com/dart-lang/sdk/tree/master/pkg/analysis_server


text:
package org.apereo.cas.util;

import lombok.val;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link HttpUtilsTests}.
 *
 * @author Misagh Moayyed
 * @since 6.3.0
 */
@Tag("Utility")
public class HttpUtilsTests {

    @Test
    public void verifyExec() {
        assertNull(HttpUtils.execute("http://localhost:1234", "GET", "user", "password", "entity"));
        assertNull(HttpUtils.execute("http://localhost:1234", "GET", Map.of()));
        assertNull(HttpUtils.executeGet("http://localhost:1234", "user", "password", Map.of()));
        assertNotNull(HttpUtils.executeGet("http://localhost:1234", "https://httpbin.org:443"));
        assertNotNull(HttpUtils.executeGet("http://localhost:1234", "http://httpbin.org"));
        assertNull(HttpUtils.executeDelete("http://localhost:1234", "user", "password", Map.of(), Map.of()));
    }

    @Test
    public void verifyClose() {
        assertDoesNotThrow(new Executable() {
            @Override
            public void execute() throws Exception {
                HttpUtils.close(null);
                val response = mock(CloseableHttpResponse.class);
                doThrow(new RuntimeException()).when(response).close();
                HttpUtils.close(response);
            }
        });
    }

}


text:
__author__ = 'Allan Saddi <allan@saddi.com>'
__version__ = '$Revision$'

import select
import struct
import socket
import errno
import types

__all__ = ['SCGIApp']

def encodeNetstring(s):
    return ''.join([str(len(s)), ':', s, ','])

class SCGIApp(object):
    def __init__(self, connect=None, host=None, port=None,
                 filterEnviron=True):
        if host is not None:
            assert port is not None
            connect=(host, port)

        assert connect is not None
        self._connect = connect

        self._filterEnviron = filterEnviron

    def __call__(self, environ, start_response):
        sock = self._getConnection()

        outfile = sock.makefile('w')
        infile = sock.makefile('r')

        sock.close()

        # Filter WSGI environ and send as request headers
        if self._filterEnviron:
            headers = self._defaultFilterEnviron(environ)
        else:
            headers = self._lightFilterEnviron(environ)
        # TODO: Anything not from environ that needs to be sent also?

        content_length = int(environ.get('CONTENT_LENGTH') or 0)
        if headers.has_key('CONTENT_LENGTH'):
            del headers['CONTENT_LENGTH']

        headers_out = ['CONTENT_LENGTH', str(content_length), 'SCGI', '1']
        for k,v in headers.items():
            headers_out.append(k)
            headers_out.append(v)
        headers_out.append('') # For trailing NUL
        outfile.write(encodeNetstring('\x00'.join(headers_out)))

        # Transfer wsgi.input to outfile
        while True:
            chunk_size = min(content_length, 4096)
            s = environ['wsgi.input'].read(chunk_size)
            content_length -= len(s)
            outfile.write(s)

            if not s: break

        outfile.close()

        # Read result from SCGI server
        result = []
        while True:
            buf = infile.read(4096)
            if not buf: break

            result.append(buf)

        infile.close()

        result = ''.join(result)

        # Parse response headers
        status = '200 OK'
        headers = []
        pos = 0
        while True:
            eolpos = result.find('\n', pos)
            if eolpos < 0: break
            line = result[pos:eolpos-1]
            pos = eolpos + 1

            # strip in case of CR. NB: This will also strip other
            # whitespace...
            line = line.strip()

            # Empty line signifies end of headers
            if not line: break

            # TODO: Better error handling
            header, value = line.split(':', 1)
            header = header.strip().lower()
            value = value.strip()

            if header == 'status':
                # Special handling of Status header
                status = value
                if status.find(' ') < 0:
                    # Append a dummy reason phrase if one was not provided
                    status += ' SCGIApp'
            else:
                headers.append((header, value))

        result = result[pos:]

        # Set WSGI status, headers, and return result.
        start_response(status, headers)
        return [result]

    def _getConnection(self):
        if isinstance(self._connect, types.StringTypes):
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.connect(self._connect)
        elif hasattr(socket, 'create_connection'):
            sock = socket.create_connection(self._connect)
        else:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(self._connect)
        return sock

    _environPrefixes = ['SERVER_', 'HTTP_', 'REQUEST_', 'REMOTE_', 'PATH_',
                        'CONTENT_']
    _environCopies = ['SCRIPT_NAME', 'QUERY_STRING', 'AUTH_TYPE']
    _environRenames = {}

    def _defaultFilterEnviron(self, environ):
        result = {}
        for n in environ.keys():
            for p in self._environPrefixes:
                if n.startswith(p):
                    result[n] = environ[n]
            if n in self._environCopies:
                result[n] = environ[n]
            if n in self._environRenames:
                result[self._environRenames[n]] = environ[n]

        return result

    def _lightFilterEnviron(self, environ):
        result = {}
        for n in environ.keys():
            if n.upper() == n:
                result[n] = environ[n]
        return result

if __name__ == '__main__':
    from flup.server.ajp import WSGIServer
    app = SCGIApp(connect=('localhost', 4000))
    #import paste.lint
    #app = paste.lint.middleware(app)
    WSGIServer(app).run()


text:
<?php

//Load Composer autoloader hiding errors
@include('vendor/autoload.php');

//Load Readability.php
use andreskrey\Readability\Readability as ReadabilityPHP;
use andreskrey\Readability\Configuration as ReadabilityPHPConf;

class fi_mod_readability
{

  public function perform_filter( $html, $config, $settings ){

    if (class_exists(ReadabilityPHP::class)) {
      Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Using Readability.php");

      $configuration = new ReadabilityPHPConf();
      if( isset( $config['relativeurl'] ) ) {
        Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php fixing relative URLS ".$config['relativeurl']);
        $configuration
        ->setFixRelativeURLs( true )
        ->setOriginalURL( $config['relativeurl'] );
      }
      if( isset( $config['normalize'] ) && is_bool( $config['normalize'] )  ) {
        Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php Normalizing content");
        $configuration
        ->setNormalizeEntities( $config['normalize'] );
      }
      if( isset( $config['removebyline'] ) && is_bool( $config['removebyline'] )  ) {
        Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php Removing ByLine");
        $configuration
        ->setArticleByLine( $config['removebyline'] );
      }
      //Load Readability with Configuration
      $readability = new ReadabilityPHP( $configuration );

      try {

        $readability->parse($html);

      } catch (Exception $e) {

        //Return unmodified html if Readability.php fails
        Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Readability.php failed to find content");
        return $html;

      }
      if( isset( $config['prependimage'] ) && ( $config['prependimage'] )  ) {
        Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php Prepending Main Image");
        $image = $readability->getImage();
        $content = '';
        $content .= $readability->getContent();
      }
      elseif( isset( $config['mainimage'] ) && ( $config['mainimage'] )  ) {
        $image = $readability->getImage();
        $content = '';
      }
      elseif( isset( $config['appendimages'] ) && ( $config['apendimages'] )  ) {
        $images = $readability->getImages();
        $content = $readability->getContent();
        foreach ( $images as $image ) {
          $content.='
';
        }
      }
      elseif( isset( $config['allimages'] ) && ( $config['allimages'] )  ) {
        $images = $readability->getImages();
        foreach ( $images as $image ) {
          $content.='
';
        }
      } else {
        $content = $readability->getContent();
      }
    }
    else {
      Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Using Legacy Readability");

      require_once 'php-readability/Readability.php';
      require_once 'php-readability/JSLikeHTMLElement.php';
      $readability = new Readability\Readability($html, $settings['link']);
      $readability->debug = false;
      $readability->convertLinksToFootnotes = true;
      $result = $readability->init();
      if (!$result) {
        Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability failed to find content");
        return $html;
      }
      else {
        $content = $readability->getContent()->innerHTML;
        Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Readability modified Source ".$settings['link'].":", $html);
      }
    }
    // Perform xpath on readability output
    if (isset($config['xpath'])){
      $html = ( new fi_mod_xpath() )->perform_filter( $html, $config, $settings );
      // If no xpath for readability output perform simple cleanup
    } elseif(($cconfig = Feediron_Helper::getCleanupConfig($config))!== false) {
      $html = $content;
      foreach($cconfig as $cleanup){
        Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Cleaning up", $cleanup);
        $html = preg_replace($cleanup, '', $html);
        Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "cleanup  result", $html);
      }
    } else {
      // If no extra config just return the content
      $html = $content;
    }
    return $html;
  }
}


text:
using System;
using System.Collections.Generic;
using Imgur.API.Enums;
using Imgur.API.JsonConverters;
using Newtonsoft.Json;

namespace Imgur.API.Models.Impl
{
    /// <summary>
    ///     The data model formatted for gallery albums.
    /// </summary>
    public class GalleryAlbum : GalleryItem, IGalleryAlbum
    {
        /// <summary>
        ///     The account ID of the account that uploaded it, or null.
        /// </summary>
        [JsonProperty("account_id")]
        public int? AccountId { get; set; }

        /// <summary>
        ///     The account username or null if it's anonymous.
        /// </summary>
        [JsonProperty("account_url")]
        public string AccountUrl { get; set; }

        /// <summary>
        ///     The ID of the album cover image.
        /// </summary>
        public string Cover { get; set; }

        /// <summary>
        ///     The height, in pixels, of the album cover image.
        /// </summary>
        [JsonProperty("cover_height")]
        public int? CoverHeight { get; set; }

        /// <summary>
        ///     The width, in pixels, of the album cover image.
        /// </summary>
        [JsonProperty("cover_width")]
        public int? CoverWidth { get; set; }

        /// <summary>
        ///     Utc timestamp of when the album was inserted into the gallery, converted from epoch time.
        /// </summary>
        [JsonConverter(typeof (EpochTimeConverter))]
        public DateTimeOffset DateTime { get; set; }

        /// <summary>
        ///     OPTIONAL, the deletehash, if you're logged in as the album owner.
        /// </summary>
        public string DeleteHash { get; set; }

        /// <summary>
        ///     The description of the album in the gallery.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        ///     Indicates if the current user favorited the album. Defaults to false if not signed in.
        /// </summary>
        public bool? Favorite { get; set; }

        /// <summary>
        ///     The ID for the image.
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        ///     A list of all the images in the album (only available when requesting the direct album).
        /// </summary>
        [JsonConverter(typeof (TypeConverter<IEnumerable<Image>>))]
        public IEnumerable<IImage> Images { get; set; } = new List<IImage>();

        /// <summary>
        ///     The total number of images in the album.
        /// </summary>
        [JsonProperty("images_count")]
        public int ImagesCount { get; set; }

        /// <summary>
        ///     The view layout of the album.
        /// </summary>
        public AlbumLayout? Layout { get; set; }

        /// <summary>
        ///     The URL link to the album.
        /// </summary>
        public string Link { get; set; }

        /// <summary>
        ///     Indicates if the image has been marked as nsfw or not. Defaults to null if information is not available.
        /// </summary>
        public bool? Nsfw { get; set; }

        /// <summary>
        ///     Order number of the album on the user's album page (defaults to 0 if their albums haven't been reordered).
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        ///     The privacy level of the album, you can only view public if not logged in as album owner.
        /// </summary>
        public AlbumPrivacy? Privacy { get; set; }

        /// <summary>
        ///     If the image has been categorized then this will contain the section the image belongs in. (funny, cats,
        ///     adviceanimals, wtf, etc)
        /// </summary>
        public string Section { get; set; }

        /// <summary>
        ///     The title of the album in the gallery.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        ///     The number of album views.
        /// </summary>
        public int Views { get; set; }

        /// <summary>
        ///     The current user's vote on the album. null if not signed in or if the user hasn't voted on it.
        /// </summary>
        public VoteOption? Vote { get; set; }
    }
}


text:
package org.onehippo.devx.webservices.jaxrs.jcr;

import java.net.URI;

import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.annotations.GZIP;
import org.apache.cxf.rs.security.cors.CrossOriginResourceSharing;
import org.onehippo.cms7.essentials.dashboard.utils.GlobalUtils;
import org.onehippo.devx.webservices.webfiles.WebFileUpdater;
import org.onehippo.devx.webservices.jaxrs.jcr.model.JcrProperty;
import org.onehippo.devx.webservices.jaxrs.jcr.util.JcrDataBindingHelper;
import org.onehippo.devx.webservices.jaxrs.jcr.util.ResponseConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Resource providing CRUD operations for JCR properties.
 *
 */
@GZIP
@Api(value = "properties", description = "JCR property API", position = 3)
@Path("properties")
@CrossOriginResourceSharing(allowAllOrigins = true)
public class PropertiesResource {

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

    @Context
    private HttpServletRequest request;

    /**
     * Gets a property by its path.
     */
    @GET
    @Path("{path:.*}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @ApiOperation(
            value = "Get a property",
            notes = "Returns a property from the specified path",
            response = JcrProperty.class
    )
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = ResponseConstants.STATUS_MESSAGE_OK, response = JcrProperty.class),
            @ApiResponse(code = 401, message = ResponseConstants.STATUS_MESSAGE_UNAUTHORIZED),
            @ApiResponse(code = 404, message = ResponseConstants.STATUS_MESSAGE_NODE_NOT_FOUND),
            @ApiResponse(code = 500, message = ResponseConstants.STATUS_MESSAGE_ERROR_OCCURRED)
    })
    public Response getPropertyByPath(@ApiParam(value = "Path of the node to retrieve e.g '/content/hippostd:foldertype'.", required = true) @PathParam("path") String path) throws RepositoryException {

        Session session = null;
        JcrProperty jcrProperty = null;

        try {
            session = GlobalUtils.createSession();
            String absolutePath = StringUtils.defaultIfEmpty(path, "/");
            if (!absolutePath.startsWith("/")) {
                absolutePath = "/" + absolutePath;
            }

            if (!session.propertyExists(absolutePath)) {
                return Response.status(Response.Status.NOT_FOUND).build();
            }
            final Property property = session.getProperty(absolutePath);
            jcrProperty = JcrDataBindingHelper.getPropertyRepresentation(property);
        } catch (RepositoryException e) {
            log.error("Error: {}", e);
            throw new WebApplicationException(e);
        } finally {
            GlobalUtils.cleanupSession(session);
        }
        return Response.ok(jcrProperty).build();
    }

    /**
     * Creates a new property.
     */
    @POST
    @Path("{path:.*}")
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @ApiOperation(value = "Add a property to a node", notes = "Adds a property to a node")
    @ApiResponses(value = {
            @ApiResponse(code = 201, message = ResponseConstants.STATUS_MESSAGE_CREATED, response = JcrProperty.class),
            @ApiResponse(code = 401, message = ResponseConstants.STATUS_MESSAGE_UNAUTHORIZED),
            @ApiResponse(code = 404, message = ResponseConstants.STATUS_MESSAGE_NODE_NOT_FOUND),
            @ApiResponse(code = 403, message = ResponseConstants.STATUS_MESSAGE_ACCESS_DENIED),
            @ApiResponse(code = 500, message = ResponseConstants.STATUS_MESSAGE_ERROR_OCCURRED)
    })
    public Response createPropertyByPath(@ApiParam(required = true, value = "Path of the node to which to add the property to e.g. '/content/documents/'")
                                         @PathParam("path") @DefaultValue("/") String parentPath,
                                         @Context UriInfo ui,
                                         JcrProperty jcrProperty) throws RepositoryException {
        Session session = null;
        URI newPropertyUri = null;

        try {
            session = GlobalUtils.createSession();
            String absolutePath = StringUtils.defaultIfEmpty(parentPath, "/");
            if (!absolutePath.startsWith("/")) {
                absolutePath = "/" + absolutePath;
            }

            if (!session.nodeExists(absolutePath)) {
                return Response.status(Response.Status.NOT_FOUND).build();
            }
            if (StringUtils.isEmpty(jcrProperty.getName())) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }

            if (StringUtils.isEmpty(jcrProperty.getType())) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }

            final Node parentNode = session.getNode(absolutePath);
            JcrDataBindingHelper.addPropertyToNode(parentNode, jcrProperty);
            session.save();
            UriBuilder ub = ui.getBaseUriBuilder().path(this.getClass()).path(this.getClass(), "getPropertyByPath");
            newPropertyUri = ub.build(parentNode.getProperty(jcrProperty.getName()).getPath().substring(1));
        } catch (Exception e) {
            log.error("Error: {}", e);
            throw new WebApplicationException(e);
        } finally {
            GlobalUtils.cleanupSession(session);
        }
        return Response.created(newPropertyUri).build();
    }

    /**
     * Updates a property.
     */
    @PUT
    @Path("{path:.*}")
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @ApiOperation(value = "Updates a property of a node", notes = "Updates a property of a node")
    @ApiResponses(value = {
            @ApiResponse(code = 204, message = ResponseConstants.STATUS_MESSAGE_UPDATED),
            @ApiResponse(code = 401, message = ResponseConstants.STATUS_MESSAGE_UNAUTHORIZED),
            @ApiResponse(code = 404, message = ResponseConstants.STATUS_MESSAGE_PROPERTY_NOT_FOUND),
            @ApiResponse(code = 403, message = ResponseConstants.STATUS_MESSAGE_ACCESS_DENIED),
            @ApiResponse(code = 500, message = ResponseConstants.STATUS_MESSAGE_ERROR_OCCURRED)
    })
    public Response updatePropertyByPath(@ApiParam(required = true, value = "Path of the property to update e.g. '/content/documents/hippostd:foldertypes'")
                                         @PathParam("path") @DefaultValue("/") String parentPath,
                                         @Context UriInfo ui,
                                         JcrProperty jcrProperty) throws RepositoryException {
        Session session = null;

        try {
            session = GlobalUtils.createSession();

            String absolutePath = StringUtils.defaultIfEmpty(parentPath, "/");
            if (!absolutePath.startsWith("/")) {
                absolutePath = "/" + absolutePath;
            }

            if (!session.propertyExists(absolutePath)) {
                return Response.status(Response.Status.NOT_FOUND).build();
            }
            if (StringUtils.isEmpty(jcrProperty.getName())) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }

            if (StringUtils.isEmpty(jcrProperty.getType())) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }

            final Property property = session.getProperty(absolutePath);
            final Node node = property.getParent();
            JcrDataBindingHelper.addPropertyToNode(node,jcrProperty);
            session.save();
            if(parentPath.startsWith("webfiles")) {
                String template = jcrProperty.getValues().get(0);
                WebFileUpdater.update(session, node, template);
            }
        } catch (Exception e) {
            log.error("Error: {}", e);
            throw new WebApplicationException(e);
        } finally {
            GlobalUtils.cleanupSession(session);
        }
        return Response.noContent().build();
    }

    /**
     * Delete a property by it's path
     *
     * @param path the path to the node
     * @return the Response status
     * @throws RepositoryException
     */
    @DELETE
    @Path("{path:.*}")
    @ApiOperation(value = "Delete a property", notes = "Deletes a property")
    @ApiResponses(value = {
            @ApiResponse(code = 204, message = ResponseConstants.STATUS_MESSAGE_DELETED),
            @ApiResponse(code = 404, message = ResponseConstants.STATUS_MESSAGE_NODE_NOT_FOUND),
            @ApiResponse(code = 500, message = ResponseConstants.STATUS_MESSAGE_ERROR_OCCURRED)
    })
    public Response deletePropertyByPath(@ApiParam(required = true, value = "Path of the property to delete e.g. '/content/hippostd:foldertype'.")
                                         @PathParam("path") String path) throws RepositoryException {
        Session session = null;

        try {
            session = GlobalUtils.createSession();
            String absolutePath = path;

            if (!absolutePath.startsWith("/")) {
                absolutePath = "/" + absolutePath;
            }

            if (StringUtils.isBlank(path)) {
                return Response.status(Response.Status.NOT_FOUND).build();
            }

            if (!session.propertyExists(absolutePath)) {
                return Response.status(Response.Status.NOT_FOUND).build();
            }

            final Property property = session.getProperty(absolutePath);
            property.remove();
            session.save();
        } catch (Exception e) {
            log.error("Error: {}", e);
            throw new WebApplicationException(e);
        } finally {
            GlobalUtils.cleanupSession(session);
        }
        return Response.noContent().build();

    }

}


text:
import { Component, OnInit, OnDestroy } from "@angular/core";

@Component({
    selector: "<%= singularKebabName %>",
    templateUrl: "<%= singularKebabName %>.component.html"
})
export class <%= singularName %>Component implements OnInit, OnDestroy {
    constructor() { }

    ngOnInit() { }

    ngOnDestroy() { }
}


text:
/**
 * @file GeoViewerBase.cpp
 * @author  Marvin Smith
 * @date    5/5/2017
 */
#include "GeoViewerBase.hpp"

/*********************************/
/*          Constructor          */
/*********************************/
GeoViewerBase::GeoViewerBase( const std::string&          base_config_profile,
                              System_Configuration::ptr_t sys_config,
                              QWidget *parent)
  : QWidget(parent),
    m_base_config_profile(base_config_profile),
    m_sys_config(sys_config),
    m_class_name("GeoViewerBase")
{

}


text:
set -o nounset
set -o errexit
set -o xtrace

package() {
    BIN_NAME_TAG=$CRATE_NAME-$TRAVIS_TAG-$TARGET
    if [[ $TARGET =~ .*windows.* ]]; then
        BIN_NAME_TAG=$BIN_NAME_TAG.exe
    fi

    cp -f target/$TARGET/release/$BIN_NAME bin/$BIN_NAME_TAG
    sha256sum "bin/$BIN_NAME_TAG" | tee "bin/$BIN_NAME_TAG.sha256"
}

release_tag() {
    cp -f target/$TARGET/release/$BIN_NAME bin/

    git config --global user.email "travis@travis-ci.org"
    git config --global user.name "Travis CI"

    git add --force bin/$BIN_NAME
    SHA=$(git rev-parse --short HEAD)
    git commit --message "Add binary. $SHA. $TRAVIS_TAG-$TARGET."
    tagname="binary-$TRAVIS_TAG-$TARGET"
    git tag --force "$tagname"
    git push --force https://${GITHUB_TOKEN}@github.com/autozimu/LanguageClient-neovim.git "$tagname"

    git reset --hard HEAD^
}

if [[ $TRAVIS_OS_NAME == 'osx' ]]; then
    export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
fi

TARGETS=(${TARGETS//:/ })
for TARGET in "${TARGETS[@]}"; do
    BIN_NAME=$CRATE_NAME
    if [[ $TARGET =~ .*windows.* ]]; then
        BIN_NAME=$BIN_NAME.exe
    fi

    cross build --release --target $TARGET
    release_tag
    package
done

if [[ $TRAVIS_OS_NAME == 'linux' ]]; then
    sudo apt-get update
    sudo apt-get install --yes python3-pip
    sudo pip3 install semver

    ci/cleanup-binary-tags.py
fi


text:
module Mozenda::Response
  class Base

    attr_reader :response

    def initialize http_response
      @response = http_response
      @xml = @response.body
    end

    def valid?
      !body_hash.nil?
    end

    def success?
      return false unless valid?
      result = body_hash["Result"] || ""
      result.downcase == "success"
    end

    def to_xml
      @xml
    end

    def to_h
      @hash ||= ::Nori.new.parse(@xml)
    end

    def name
      self.class.const_get(:NAME)
    end

    protected

    def body_hash
      to_h[name]
    end

  end
end


text:
TEST_CASE("check assert on non-varint access to varint") {
    const std::string buffer = load_data("int32/data-zero");

    protozero::pbf_reader item{buffer};
    REQUIRE(item.next());

    REQUIRE(item.get_int32() == 0);
    REQUIRE_THROWS_AS(item.get_fixed64(), assert_error);
    REQUIRE_THROWS_AS(item.get_string(), assert_error);
    REQUIRE_THROWS_AS(item.get_fixed32(), assert_error);
}

// protobuf wire type 1
TEST_CASE("check assert on non-fixed access to fixed64") {
    const std::string buffer = load_data("fixed64/data-zero");

    protozero::pbf_reader item{buffer};
    REQUIRE(item.next());

    REQUIRE_THROWS_AS(item.get_int32(), assert_error);
    REQUIRE(item.get_fixed64() == 0);
    REQUIRE_THROWS_AS(item.get_string(), assert_error);
    REQUIRE_THROWS_AS(item.get_fixed32(), assert_error);
}

// protobuf wire type 2
TEST_CASE("check assert on non-string access to string") {
    const std::string buffer = load_data("string/data-string");

    protozero::pbf_reader item{buffer};
    REQUIRE(item.next());

    REQUIRE_THROWS_AS(item.get_int32(), assert_error);
    REQUIRE_THROWS_AS(item.get_fixed64(), assert_error);
    REQUIRE(item.get_string() == "foobar");
    REQUIRE_THROWS_AS(item.get_fixed32(), assert_error);
}

// protobuf wire type 5
TEST_CASE("check assert on non-fixed access to fixed32") {
    const std::string buffer = load_data("fixed32/data-zero");

    protozero::pbf_reader item{buffer};
    REQUIRE(item.next());

    REQUIRE_THROWS_AS(item.get_int32(), assert_error);
    REQUIRE_THROWS_AS(item.get_fixed64(), assert_error);
    REQUIRE_THROWS_AS(item.get_string(), assert_error);
    REQUIRE(item.get_fixed32() == 0);
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.spi.connector;

import io.trino.spi.predicate.TupleDomain;

import static java.util.Objects.requireNonNull;

public class ConnectorResolvedIndex
{
    private final ConnectorIndexHandle indexHandle;
    private final TupleDomain<ColumnHandle> unresolvedTupleDomain;

    public ConnectorResolvedIndex(ConnectorIndexHandle indexHandle, TupleDomain<ColumnHandle> unresolvedTupleDomain)
    {
        this.indexHandle = requireNonNull(indexHandle, "indexHandle is null");
        this.unresolvedTupleDomain = requireNonNull(unresolvedTupleDomain, "unresolvedTupleDomain is null");
    }

    public ConnectorIndexHandle getIndexHandle()
    {
        return indexHandle;
    }

    public TupleDomain<ColumnHandle> getUnresolvedTupleDomain()
    {
        return unresolvedTupleDomain;
    }
}


text:
/**
 * Container for link between two Osm nodes
 *
 * @author ab
 */
package btools.router;

import java.util.Map;

import btools.expressions.BExpressionContextNode;
import btools.expressions.BExpressionContextWay;

final class KinematicModel extends OsmPathModel
{
  public OsmPrePath createPrePath()
  {
    return new KinematicPrePath();
  }

  public OsmPath createPath()
  {
    return new KinematicPath();
  }

  public double turnAngleDecayTime;
  public double f_roll;
  public double f_air;
  public double f_recup;
  public double p_standby;
  public double outside_temp;
  public double recup_efficiency;
  public double totalweight;
  public double vmax;
  public double leftWaySpeed;
  public double rightWaySpeed;

  // derived values
  public double pw; // balance power
  public double cost0; // minimum possible cost per meter

  private int wayIdxMaxspeed;
  private int wayIdxMaxspeedExplicit;
  private int wayIdxMinspeed;

  private int nodeIdxMaxspeed;

  protected BExpressionContextWay ctxWay;
  protected BExpressionContextNode ctxNode;
  protected Map<String,String> params;

  private boolean initDone = false;

  private double lastEffectiveLimit;
  private double lastBreakingSpeed;

  @Override
  public void init( BExpressionContextWay expctxWay, BExpressionContextNode expctxNode, Map<String,String> extraParams )
  {
    if ( !initDone )
    {
      ctxWay = expctxWay;
      ctxNode = expctxNode;
      wayIdxMaxspeed = ctxWay.getOutputVariableIndex( "maxspeed", false );
      wayIdxMaxspeedExplicit = ctxWay.getOutputVariableIndex( "maxspeed_explicit", false );
      wayIdxMinspeed = ctxWay.getOutputVariableIndex( "minspeed", false );
      nodeIdxMaxspeed = ctxNode.getOutputVariableIndex( "maxspeed", false );
      initDone = true;
    }

    params = extraParams;

    turnAngleDecayTime = getParam( "turnAngleDecayTime", 5.f );
    f_roll = getParam( "f_roll", 232.f );
    f_air = getParam( "f_air", 0.4f );
    f_recup = getParam( "f_recup", 400.f );
    p_standby = getParam( "p_standby", 250.f );
    outside_temp = getParam( "outside_temp", 20.f );
    recup_efficiency = getParam( "recup_efficiency", 0.7f );
    totalweight = getParam( "totalweight", 1640.f );
    vmax = getParam( "vmax", 80.f ) / 3.6;
    leftWaySpeed = getParam( "leftWaySpeed", 12.f ) / 3.6;
    rightWaySpeed = getParam( "rightWaySpeed", 12.f ) / 3.6;

    pw = 2. * f_air * vmax * vmax * vmax - p_standby;
    cost0 = (pw+p_standby)/vmax + f_roll + f_air*vmax*vmax;
  }

  protected float getParam( String name, float defaultValue )
  {
    String sval = params == null ? null : params.get( name );
    if ( sval != null )
    {
      return Float.parseFloat( sval );
    }
    float v = ctxWay.getVariableValue( name, defaultValue );
    if ( params != null )
    {
      params.put( name, "" + v );
    }
    return v;
  }

  public float getWayMaxspeed()
  {
    return ctxWay.getBuildInVariable( wayIdxMaxspeed ) / 3.6f;
  }

  public float getWayMaxspeedExplicit()
  {
    return ctxWay.getBuildInVariable( wayIdxMaxspeedExplicit ) / 3.6f;
  }

  public float getWayMinspeed()
  {
    return ctxWay.getBuildInVariable( wayIdxMinspeed ) / 3.6f;
  }

  public float getNodeMaxspeed()
  {
    return ctxNode.getBuildInVariable( nodeIdxMaxspeed ) / 3.6f;
  }

 /**
  * get the effective speed limit from the way-limit and vmax/vmin
  */
  public double getEffectiveSpeedLimit( )
  {
    // performance related inline coding
    double minspeed = getWayMinspeed();
    double espeed = minspeed > vmax ? minspeed : vmax;
    double maxspeed = getWayMaxspeed();
    return maxspeed < espeed ? maxspeed : espeed;
  }

 /**
  * get the breaking speed for current balance-power (pw) and effective speed limit (vl)
  */
  public double getBreakingSpeed( double vl )
  {
    if ( vl == lastEffectiveLimit )
    {
      return lastBreakingSpeed;
    }

    double v = vl*0.8;
    double pw2 = pw+p_standby;
    double e = recup_efficiency;
    double x0 = pw2/vl+f_air*e*vl*vl+(1.-e)*f_roll;
    for(int i=0;i<5;i++)
    {
      double v2 = v*v;
      double x = pw2/v+f_air*e*v2 - x0;
      double dx = 2.*e*f_air*v - pw2/v2;
      v -= x/dx;
    }
    lastEffectiveLimit = vl;
    lastBreakingSpeed = v;

    return v;
  }

}


text:
myIncludedVarIsOk=

function includedFunction {
    local includedLocalVar=
    echo $includedLocalVar
}

myIncludedVarIsOk2=
includedVarHasOtherPrefix=


text:
require 'test_helper'

class TestNode < Minitest::Test
  # These tests are somewhat fragile. It would be better to allocate lots
  # of memory after a GC run to make sure that potentially freed memory
  # isn't valid by accident.

  def test_drop_parent_reference
    doc = CommonMarker.render_doc('Hi *there*')
    text = doc.first_child.last_child.first_child
    doc = nil
    GC.start
    # Test that doc has not been freed.
    assert_equal "there", text.string_content
  end

  def test_drop_child_reference
    doc = CommonMarker.render_doc('Hi *there*')
    text = doc.first_child.last_child.first_child
    text = nil
    GC.start
    # Test that the cached child object is still valid.
    text = doc.first_child.last_child.first_child
    assert_equal "there", text.string_content
  end

  def test_remove_parent
    doc = CommonMarker.render_doc('Hi *there*')
    para = doc.first_child
    para.delete
    doc = nil
    para = nil
    # TODO: Test that the `para` node was actually freed after unlinking.
  end

  def test_add_parent
    doc = Node.new(:document)
    hrule = Node.new(:hrule)
    doc.append_child(hrule)
    # If the hrule node was erroneously freed, this would result in a double
    # free.
  end
end


text:
//
//  cc3MQOSampleLayer.h
//  cc3MQOSample
//
//  Created by T.Takabayashi on 11/09/14.
//  Copyright T.Takabayashi 2011. All rights reserved.
//

#import "CC3Layer.h"

/** A sample application-specific CC3Layer subclass. */
@interface cc3MQOSampleLayer : CC3Layer {}

@end


text:
"use strict";
var Ember = require("ember")["default"] || require("ember");

var alias = Ember.computed.alias;

exports["default"] = Ember.Component.extend({

  tagName: 'ic-autocomplete-list',

  attributeBindings: [
    'role',
    'aria-expanded'
  ],

  /**
   * Tells the screenreader how to deal with this element.
   * http://www.w3.org/TR/wai-aria/roles#listbox
   *
   * @property role
   * @private
   */

  role: 'listbox',

  /**
   * Tells the screenreader when this element is expanded or not.
   *
   * @property aria-expanded
   * @private
   */

  'aria-expanded': function() {
    return this.get('parentView.isOpen')+'';
  }.property('parentView.isOpen'),

  /**
   * @method registerWithParent
   * @private
   */

  registerWithParent: function() {
    this.get('parentView').registerList(this);
  }.on('didInsertElement')

});


text:
package seu.service;

import seu.domain.Teacher;
import seu.socket.Client;
import seu.socket.ClientRequest;

import java.util.List;

public class TeacherService {

    private Client client=new Client();

    public void setClient(Client client) {
        this.client = client;
    }

    private String serviceName;

    public TeacherService() {
        serviceName = "teacherService";
    }

    public int login(int teacherId, String passwd) {
        return (int) client.send(new ClientRequest(serviceName, "login", new Class[]{int.class, String.class}, new Object[]{teacherId, passwd})).getData();
    }

    //TODO: 增加返回值
    public void logout() {
        client.send(new ClientRequest(serviceName, "logout"));
    }

    public int insertTeacher(Teacher teacher) {
        return (int) client.send(new ClientRequest(serviceName, "insertTeacher", new Class[]{Teacher.class}, new Object[]{teacher})).getData();
    }

    public int deleteTeacher(int teacherID) {
        return (int) client.send(new ClientRequest(serviceName, "deleteTeacher", new Class[]{int.class}, new Object[]{teacherID})).getData();
    }

    public int updateTeacherPassword(int teacherID, String passsword) {
        return (int) client.send(new ClientRequest(serviceName, "updateTeacherPassword", new Class[]{int.class, String.class}, new Object[]{teacherID, passsword})).getData();
    }

    public int updateTeacher(Teacher teacher) {
        return (int) client.send(new ClientRequest(serviceName, "updateTeacher", new Class[]{Teacher.class}, new Object[]{teacher})).getData();
    }

    public Teacher queryTeacherByTeacherId(int teahcerID) {
        return (Teacher) client.send(new ClientRequest(serviceName, "queryTeacherByTeacherId", new Class[]{int.class}, new Object[]{teahcerID})).getData();
    }

    public Teacher queryTeacherByClassId(int classID) {
        return (Teacher) client.send(new ClientRequest(serviceName, "queryTeacherByClassId", new Class[]{int.class}, new Object[]{classID})).getData();
    }

    public Teacher queryTeacherByCourseId(int courseID) {
        return (Teacher) client.send(new ClientRequest(serviceName, "queryTeacherByCourseId", new Class[]{int.class}, new Object[]{courseID})).getData();
    }

    public List<Teacher> queryAllTeacher() {
        return (List<Teacher>) client.send(new ClientRequest(serviceName, "queryAllTeacher")).getData();
    }
}


text:
using System;

class HelloName
{
    static void Main()
    {
        string name = Console.ReadLine();
        Console.WriteLine(PrintHelloName(name));

    }

    static string PrintHelloName(string name)
    {
        string message = ($"Hello, {name}!");
        return message;
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.expressions;

import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.ConstantExpression;
import com.facebook.presto.spi.relation.InputReferenceExpression;
import com.facebook.presto.spi.relation.LambdaDefinitionExpression;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.relation.RowExpressionVisitor;
import com.facebook.presto.spi.relation.SpecialFormExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public final class RowExpressionTreeRewriter<C>
{
    private final RowExpressionRewriter<C> rewriter;
    private final RowExpressionVisitor<RowExpression, Context<C>> visitor;

    public static <C, T extends RowExpression> T rewriteWith(RowExpressionRewriter<C> rewriter, T node)
    {
        return new RowExpressionTreeRewriter<>(rewriter).rewrite(node, null);
    }

    public static <C, T extends RowExpression> T rewriteWith(RowExpressionRewriter<C> rewriter, T node, C context)
    {
        return new RowExpressionTreeRewriter<>(rewriter).rewrite(node, context);
    }

    public RowExpressionTreeRewriter(RowExpressionRewriter<C> rewriter)
    {
        this.rewriter = rewriter;
        this.visitor = new RewritingVisitor();
    }

    private List<RowExpression> rewrite(List<RowExpression> items, Context<C> context)
    {
        List<RowExpression> rewritenExpressions = new ArrayList<>();
        for (RowExpression expression : items) {
            rewritenExpressions.add(rewrite(expression, context.get()));
        }
        return Collections.unmodifiableList(rewritenExpressions);
    }

    @SuppressWarnings("unchecked")
    public <T extends RowExpression> T rewrite(T node, C context)
    {
        return (T) node.accept(visitor, new Context<>(context, false));
    }

    /**
     * Invoke the default rewrite logic explicitly. Specifically, it skips the invocation of the expression rewriter for the provided node.
     */
    @SuppressWarnings("unchecked")
    public <T extends RowExpression> T defaultRewrite(T node, C context)
    {
        return (T) node.accept(visitor, new Context<>(context, true));
    }

    private class RewritingVisitor
            implements RowExpressionVisitor<RowExpression, Context<C>>
    {
        @Override
        public RowExpression visitInputReference(InputReferenceExpression input, Context<C> context)
        {
            if (!context.isDefaultRewrite()) {
                RowExpression result = rewriter.rewriteInputReference(input, context.get(), RowExpressionTreeRewriter.this);
                if (result != null) {
                    return result;
                }
            }

            return input;
        }

        @Override
        public RowExpression visitCall(CallExpression call, Context<C> context)
        {
            if (!context.isDefaultRewrite()) {
                RowExpression result = rewriter.rewriteCall(call, context.get(), RowExpressionTreeRewriter.this);
                if (result != null) {
                    return result;
                }
            }

            List<RowExpression> arguments = rewrite(call.getArguments(), context);

            if (!sameElements(call.getArguments(), arguments)) {
                return new CallExpression(call.getDisplayName(), call.getFunctionHandle(), call.getType(), arguments);
            }
            return call;
        }

        @Override
        public RowExpression visitConstant(ConstantExpression literal, Context<C> context)
        {
            if (!context.isDefaultRewrite()) {
                RowExpression result = rewriter.rewriteConstant(literal, context.get(), RowExpressionTreeRewriter.this);
                if (result != null) {
                    return result;
                }
            }

            return literal;
        }

        @Override
        public RowExpression visitLambda(LambdaDefinitionExpression lambda, Context<C> context)
        {
            if (!context.isDefaultRewrite()) {
                RowExpression result = rewriter.rewriteLambda(lambda, context.get(), RowExpressionTreeRewriter.this);
                if (result != null) {
                    return result;
                }
            }

            RowExpression body = rewrite(lambda.getBody(), context.get());
            if (body != lambda.getBody()) {
                return new LambdaDefinitionExpression(lambda.getArgumentTypes(), lambda.getArguments(), body);
            }

            return lambda;
        }

        @Override
        public RowExpression visitVariableReference(VariableReferenceExpression variable, Context<C> context)
        {
            if (!context.isDefaultRewrite()) {
                RowExpression result = rewriter.rewriteVariableReference(variable, context.get(), RowExpressionTreeRewriter.this);
                if (result != null) {
                    return result;
                }
            }

            return variable;
        }

        @Override
        public RowExpression visitSpecialForm(SpecialFormExpression specialForm, Context<C> context)
        {
            if (!context.isDefaultRewrite()) {
                RowExpression result = rewriter.rewriteSpecialForm(specialForm, context.get(), RowExpressionTreeRewriter.this);
                if (result != null) {
                    return result;
                }
            }

            List<RowExpression> arguments = rewrite(specialForm.getArguments(), context);

            if (!sameElements(specialForm.getArguments(), arguments)) {
                return new SpecialFormExpression(specialForm.getForm(), specialForm.getType(), arguments);
            }
            return specialForm;
        }
    }

    public static class Context<C>
    {
        private final boolean defaultRewrite;
        private final C context;

        private Context(C context, boolean defaultRewrite)
        {
            this.context = context;
            this.defaultRewrite = defaultRewrite;
        }

        public C get()
        {
            return context;
        }

        public boolean isDefaultRewrite()
        {
            return defaultRewrite;
        }
    }

    @SuppressWarnings("ObjectEquality")
    private static <T> boolean sameElements(Collection<? extends T> a, Collection<? extends T> b)
    {
        if (a.size() != b.size()) {
            return false;
        }

        Iterator<? extends T> first = a.iterator();
        Iterator<? extends T> second = b.iterator();

        while (first.hasNext() && second.hasNext()) {
            if (first.next() != second.next()) {
                return false;
            }
        }

        return true;
    }
}


text:
package org.mimosaframework.core.server;

import java.util.List;

public interface ConnectionVindicator<T> extends Runnable {
    void setOver(boolean over);

    void setTimeout(long timeout);

    void setNodes(List<T> nodes);
}


text:
package reuse.jmx.numbers.operator;

public class Multiply extends AbstractBinaryOperator {
	private static final long serialVersionUID = 1L;

	public Multiply(Number left, Number right) {
		super(left, right);
	}

	@Override
	public double doubleValue() {
		return left.doubleValue() * right.doubleValue();
	}
}


text:
module Protean
  module Transformations
    class Uppercase < Base

      # {
      #   "field" => "last_name",
      #   "prep" => "uppercase"
      # }
      def process(shape)
        shape.update_value(shape.value.upcase)
      end

    end
  end
end


text:
<root>
  <item name='android.net.Uri android.net.Uri parse(java.lang.String)'>
    <annotation name='javax.annotation.Nonnull' />
  </item>
</root>


text:
#ifndef _UTIL_H
#define _UTIL_H

#include <ntddk.h>

#include "assert.h"

#define	P2ROUNDUP(_x, _a)   \
        (-(-(_x) & -(_a)))

static FORCEINLINE LONG
__ffs(
    IN  unsigned long long  mask
    )
{
    unsigned char           *array = (unsigned char *)&mask;
    unsigned int            byte;
    unsigned int            bit;
    unsigned char           val;

    val = 0;

    byte = 0;
    while (byte < 8) {
        val = array[byte];

        if (val != 0)
            break;

        byte++;
    }
    if (byte == 8)
        return -1;

    bit = 0;
    while (bit < 8) {
        if (val & 0x01)
            break;

        val >>= 1;
        bit++;
    }

    return (byte * 8) + bit;
}

#define __ffu(_mask)  \
        __ffs(~(_mask))

static FORCEINLINE LONG
__InterlockedAdd(
    IN  LONG    *Value,
    IN  LONG    Delta
    )
{
    LONG        New;
    LONG        Old;

    do {
        Old = *Value;
        New = Old + Delta;
    } while (InterlockedCompareExchange(Value, New, Old) != Old);

    return New;
}

static FORCEINLINE LONG
__InterlockedSubtract(
    IN  LONG    *Value,
    IN  LONG    Delta
    )
{
    LONG        New;
    LONG        Old;

    do {
        Old = *Value;
        New = Old - Delta;
    } while (InterlockedCompareExchange(Value, New, Old) != Old);

    return New;
}

typedef struct _NON_PAGED_BUFFER_HEADER {
    SIZE_T  Length;
    ULONG   Tag;
} NON_PAGED_BUFFER_HEADER, *PNON_PAGED_BUFFER_HEADER;

typedef struct _NON_PAGED_BUFFER_TRAILER {
    ULONG   Tag;
} NON_PAGED_BUFFER_TRAILER, *PNON_PAGED_BUFFER_TRAILER;

static FORCEINLINE PVOID
__AllocateNonPagedPoolWithTag(
    IN  SIZE_T                  Length,
    IN  ULONG                   Tag
    )
{
    PUCHAR                      Buffer;
    PNON_PAGED_BUFFER_HEADER    Header;
    PNON_PAGED_BUFFER_TRAILER   Trailer;

    ASSERT(Length != 0);

    Buffer = (PUCHAR)ExAllocatePoolWithTag(NonPagedPool,
                                   sizeof (NON_PAGED_BUFFER_HEADER) +
                                   Length +
                                   sizeof (NON_PAGED_BUFFER_TRAILER),
                                   Tag);
    if (Buffer == NULL)
        goto done;

    RtlZeroMemory(Buffer,
                  sizeof (NON_PAGED_BUFFER_HEADER) +
                  Length +
                  sizeof (NON_PAGED_BUFFER_TRAILER));

    Header = (PNON_PAGED_BUFFER_HEADER)Buffer;
    Header->Length = Length;
    Header->Tag = Tag;

    Buffer += sizeof (NON_PAGED_BUFFER_HEADER);

    Trailer = (PNON_PAGED_BUFFER_TRAILER)(Buffer + Length);
    Trailer->Tag = Tag;

done:
    return Buffer;
}

static FORCEINLINE VOID
__FreePoolWithTag(
    IN  PVOID                   _Buffer,
    IN  ULONG                   Tag
    )
{
    PUCHAR                      Buffer = (PUCHAR)_Buffer;
    SIZE_T                      Length;
    PNON_PAGED_BUFFER_HEADER    Header;
    PNON_PAGED_BUFFER_TRAILER   Trailer;

    ASSERT(Buffer != NULL);

    Buffer -= sizeof (NON_PAGED_BUFFER_HEADER);

    Header = (PNON_PAGED_BUFFER_HEADER)Buffer;
    ASSERT3U(Tag, ==, Header->Tag);
    Length = Header->Length;

    Buffer += sizeof (NON_PAGED_BUFFER_HEADER);

    Trailer = (PNON_PAGED_BUFFER_TRAILER)(Buffer + Length);
    ASSERT3U(Tag, ==, Trailer->Tag);

    Buffer -= sizeof (NON_PAGED_BUFFER_HEADER);

    RtlFillMemory(Buffer,
                  sizeof (NON_PAGED_BUFFER_HEADER) +
                  Length +
                  sizeof (NON_PAGED_BUFFER_TRAILER),
                  0xAA);

    ExFreePoolWithTag(Buffer, Tag);
}

static FORCEINLINE PMDL
__AllocatePage(
    VOID
    )
{
    PHYSICAL_ADDRESS    LowAddress;
    PHYSICAL_ADDRESS    HighAddress;
    LARGE_INTEGER       SkipBytes;
    SIZE_T              TotalBytes;
    PMDL                Mdl;
    PUCHAR              MdlMappedSystemVa;
    NTSTATUS            status;

    LowAddress.QuadPart = 0ull;
    HighAddress.QuadPart = ~0ull;
    SkipBytes.QuadPart = 0ull;
    TotalBytes = (SIZE_T)PAGE_SIZE;

    Mdl = MmAllocatePagesForMdlEx(LowAddress,
                                  HighAddress,
                                  SkipBytes,
                                  TotalBytes,
                                  MmCached,
                                  0);

    status = STATUS_NO_MEMORY;
    if (Mdl == NULL)
        goto fail1;

    ASSERT((Mdl->MdlFlags & (MDL_MAPPED_TO_SYSTEM_VA |
                             MDL_PARTIAL_HAS_BEEN_MAPPED |
                             MDL_PARTIAL |
                             MDL_PARENT_MAPPED_SYSTEM_VA |
                             MDL_SOURCE_IS_NONPAGED_POOL |
                             MDL_IO_SPACE)) == 0);

    MdlMappedSystemVa = MmMapLockedPagesSpecifyCache(Mdl,
                                                     KernelMode,
						                             MmCached,
						                             NULL,
						                             FALSE,
						                             NormalPagePriority);

    status = STATUS_UNSUCCESSFUL;
    if (MdlMappedSystemVa == NULL)
        goto fail2;

    ASSERT3P(MdlMappedSystemVa, ==, Mdl->MappedSystemVa);

    RtlZeroMemory(MdlMappedSystemVa, PAGE_SIZE);

    return Mdl;

fail2:
    Error("fail2\n");

    MmFreePagesFromMdl(Mdl);
    ExFreePool(Mdl);

fail1:
    Error("fail1 (%08x)\n", status);

    return NULL;
}

static FORCEINLINE VOID
__FreePage(
    IN	PMDL	Mdl
    )
{
    PUCHAR	MdlMappedSystemVa;

    ASSERT(Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA);
    MdlMappedSystemVa = Mdl->MappedSystemVa;

    RtlFillMemory(MdlMappedSystemVa, PAGE_SIZE, 0xAA);

    MmUnmapLockedPages(MdlMappedSystemVa, Mdl);

    MmFreePagesFromMdl(Mdl);
}

#endif  // _UTIL_H


text:
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (1, 1, 'In ce an a inceput Primul Razboi Mondial?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (2, 1, 'In ce an s-a destramat Uniunea Sovietica?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (3, 1, 'In ce zi a lunii decembrie este Ziua Nationala a Romaniei?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (4, 1, 'In ce an a inceput Al Doilea Razboi Mondial?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (5, 1, 'In ce an a fost revolutia in urma careia a cazut comunismul in Romania?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (6, 1, 'In ce an a fost semnat Pactul Ribbentrop-Molotov?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (7, 1, 'In ce an a abdicat Domnitorul Alexandru Ioan Cuza?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (8, 1, 'In ce an a intrat in vigoare Tratatul de la Trianon?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (9, 1, 'Aproximativ in ce an inainte de Hristos a fost fondat Regatul Roman?', 1, '0');
/
insert into tw_questions(question_id, domain_id, question_text, difficulty, tip)
  values (10, 1, 'Cati ani a condus Augustus, primul imparat al Romei, Imperiul Roman?', 1, '0');
/
--raspunsurile
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (1, '1918', '1916', '1909', '1914');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (2, '1999', '1989', '1919', '1991');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (3, '10', '6', '25', '1');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (4, '1949', '1945', '1936', '1939');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (5, '1999', '1945', '1991', '1989');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (6, '1941', '1936', '1945', '1939');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (7, '1857', '1860', '1859', '1866');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (8, '1918', '1919', '1920', '1921');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (9, '754', '752', '172', '753');/
insert into questions_answers(question_id, answer1, answer2, answer3, correct_answer)
  values (10, '41', '36', '39', '40');
COMMIT;


text:
module Sawarineko
  # Hold Sawarineko's version information.
  module Version
    STRING = '1.2.0'
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ page_title }}</title>

    <link href="theme.scss" rel="stylesheet">

    {{ content_for_header }}

              {% if site.has_meta_image? %}

              {% else %}

{{ site.long_name }}

              {% endif %}

          {% if site.has_header_image? %}

          {% endif %}

          {% if page.features_count > 0 %}

             {% include "features" %}

          {% endif %}

            	{{ content_for_notifications }}

                {% yield %}

Continue to {{ site.name }}

                {% if request.is_intern? and page.is_editing_available? %}

{{ "fugue-edit-signiture" | icon }} Edit this page

                {% endif %}

            {{ content_for_footer }}


text:
#ifndef AUGLAG_H
#define AUGLAG_H

#include "nlopt.h"
#include "nlopt-util.h"

#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */

extern int auglag_verbose;

nlopt_result auglag_minimize(int n, nlopt_func f, void *f_data,
			     int m, nlopt_constraint *fc,
			     int p, nlopt_constraint *h,
			     const double *lb, const double *ub, /* bounds */
			     double *x, /* in: initial guess, out: minimizer */
			     double *minf,
			     nlopt_stopping *stop,
			     nlopt_opt sub_opt, int sub_has_fc);

#ifdef __cplusplus
}  /* extern "C" */
#endif /* __cplusplus */

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/draw_layer_message_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/gradient_vertical"
        android:layout_gravity="bottom"
        android:paddingTop="32dp"
        android:paddingBottom="32dp">

        <TextView
            android:id="@+id/draw_layer_message"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:paddingTop="8dp"
            android:text="@string/draw_layer_instruction" />

        <!--<TextView-->
            <!--android:id="@+id/geo_get_started"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="match_parent"-->
            <!--android:gravity="center"-->
            <!--android:paddingTop="16dp"-->
            <!--android:textAppearance="@style/textAppearanceSubtitle2_light_heavy"-->
            <!--android:textColor="@color/nga_primary_light"-->
            <!--android:text="Get Started" />-->

</LinearLayout>


text:
@implementation Recording

@end


text:
<?php

namespace app\models;

class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
	public $id;
	public $username;
	public $password;
	public $authKey;

	private static $users = [
		'100' => [
			'id' => '100',
			'username' => 'admin',
			'password' => 'admin',
			'authKey' => 'test100key',
		],
		'101' => [
			'id' => '101',
			'username' => 'demo',
			'password' => 'demo',
			'authKey' => 'test101key',
		],
	];

	public static function findIdentity($id)
	{
		return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
	}

	public static function findByUsername($username)
	{
		foreach (self::$users as $user) {
			if (strcasecmp($user['username'], $username) === 0) {
				return new static($user);
			}
		}
		return null;
	}

	public function getId()
	{
		return $this->id;
	}

	public function getAuthKey()
	{
		return $this->authKey;
	}

	public function validateAuthKey($authKey)
	{
		return $this->authKey === $authKey;
	}

	public function validatePassword($password)
	{
		return $this->password === $password;
	}
}


text:
/*! HTML5 Boilerplate v4.3.0 | MIT License | http://h5bp.com/ */
/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */
/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */
html,
button,
input,
select,
textarea {
  color: #222; }

html {
  font-size: 1em;
  line-height: 1.4; }

/*
 * Remove text-shadow in selection highlight: h5bp.com/i
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */
::-moz-selection {
  background: #b3d4fc;
  text-shadow: none; }

::selection {
  background: #b3d4fc;
  text-shadow: none; }

/*
 * A better looking default horizontal rule
 */
hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #ccc;
  margin: 1em 0;
  padding: 0; }

/*
 * Remove the gap between images, videos, audio and canvas and the bottom of
 * their containers: h5bp.com/i/440
 */
audio,
canvas,
img,
video {
  vertical-align: middle; }

/*
 * Remove default fieldset styles.
 */
fieldset {
  border: 0;
  margin: 0;
  padding: 0; }

/*
 * Allow only vertical resizing of textareas.
 */
textarea {
  resize: vertical; }

/* ==========================================================================
   Browse Happy prompt
   ========================================================================== */
.browsehappy {
  margin: 0.2em 0;
  background: #ccc;
  color: #000;
  padding: 0.2em 0; }

/* ==========================================================================
   Author's custom styles
   ========================================================================== */
html {
  height: 100%;
  overflow: hidden; }

body {
  height: 100%;
  font-size: 1vw; }
  @media (max-width: 1200px) and (min-width: 801px) {
    body {
      font-size: 2vw; } }
  @media (max-width: 800px) {
    body {
      font-size: 3vw; } }

a {
  text-decoration: none;
  color: inherit; }

a:hover {
  color: #2196F3; }

#title {
  width: 100%;
  text-align: center;
  font-family: "Amatic SC";
  font-size: 500%;
  font-weight: bold; }

.content {
  margin: 0 25% 0 25%;
  font-family: "Merriweather";
  text-align: justify;
  font-size: 120%; }
  @media (max-width: 1200px) and (min-width: 801px) {
    .content {
      margin: 0 20% 0 20%; } }
  @media (max-width: 800px) {
    .content {
      margin: 0 15% 0 15%; } }

#name, #subtitle {
  width: 100%;
  text-align: center;
  font-family: "Amatic SC"; }

#name {
  font-size: 3rem;
  font-weight: bold; }

#subtitle {
  font-size: 200%; }

ul {
  list-style: none;
  margin: 0 25% 0 25%;
  text-align: center;
  font-size: 200%;
  padding: 0; }
  ul li {
    display: inline; }

/* ==========================================================================
   Helper classes
   ========================================================================== */
/*
 * Image replacement
 */
.ir {
  background-color: transparent;
  border: 0;
  overflow: hidden;
  /* IE 6/7 fallback */
  *text-indent: -9999px; }

.ir:before {
  content: "";
  display: block;
  width: 0;
  height: 150%; }

/*
 * Hide from both screenreaders and browsers: h5bp.com/u
 */
.hidden {
  display: none !important;
  visibility: hidden; }

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */
.visuallyhidden {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px; }

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
  clip: auto;
  height: auto;
  margin: 0;
  overflow: visible;
  position: static;
  width: auto; }

/*
 * Hide visually and from screenreaders, but maintain layout
 */
.invisible {
  visibility: hidden; }

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */
.clearfix:before,
.clearfix:after {
  content: " ";
  /* 1 */
  display: table;
  /* 2 */ }

.clearfix:after {
  clear: both; }

/*
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.clearfix {
  *zoom: 1; }

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */
@media only screen and (min-width: 35em) {
  /* Style adjustments for viewports that meet the condition */ }
@media print, (-o-min-device-pixel-ratio: 5 / 4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
  /* Style adjustments for high resolution devices */ }
/* ==========================================================================
   Print styles.
   Inlined to avoid required HTTP connection: h5bp.com/r
   ========================================================================== */
@media print {
  * {
    background: transparent !important;
    color: #000 !important;
    /* Black prints faster: h5bp.com/s */
    box-shadow: none !important;
    text-shadow: none !important; }

  a,
  a:visited {
    text-decoration: underline; }

  a[href]:after {
    content: " (" attr(href) ")"; }

  abbr[title]:after {
    content: " (" attr(title) ")"; }

  /*
   * Don't show links for images, or javascript/internal links
   */
  .ir a:after,
  a[href^="javascript:"]:after,
  a[href^="#"]:after {
    content: ""; }

  pre,
  blockquote {
    border: 1px solid #999;
    page-break-inside: avoid; }

  thead {
    display: table-header-group;
    /* h5bp.com/t */ }

  tr,
  img {
    page-break-inside: avoid; }

  img {
    max-width: 100% !important; }

  @page {
    margin: 0.5cm; }
  p,
  h2,
  h3 {
    orphans: 3;
    widows: 3; }

  h2,
  h3 {
    page-break-after: avoid; } }


text:
class WAYPOINTLIST
{
#ifdef USE_SH_POOLS
public:
    // Overload new/delete to use a SmartHeap pool
    void *operator new(size_t size)
    {
        return MemAllocPtr(UI_Pools[UI_CONTROL_POOL], size, FALSE);
    };
    void operator delete(void *mem)
    {
        if (mem) MemFreePtr(mem);
    };
#endif
public:
    long ID;
    long Type;
    long Flags;
    long Group;
    short state;
    short x, y;
    float worldx, worldy;
    C_Button *Icon;
    short Dragable;
    COLORREF LineColor_[3];
    WAYPOINTLIST *Next;
};

class C_Waypoint : public C_Control
{
#ifdef USE_SH_POOLS
public:
    // Overload new/delete to use a SmartHeap pool
    void *operator new(size_t size)
    {
        return MemAllocPtr(UI_Pools[UI_CONTROL_POOL], size, FALSE);
    };
    void operator delete(void *mem)
    {
        if (mem) MemFreePtr(mem);
    };
#endif
private:
    WAYPOINTLIST *Root_, *LastWP_;

    long Font_;

    IMAGE_RSC *Images_[8];

    float MinWorldX_, MinWorldY_;
    float MaxWorldX_, MaxWorldY_;

    short WPScaleType_;

    short Dragging_;
    UI95_RECT last_;
    float scale_;
    long DefaultFlags_;

public:
    C_Waypoint();
    C_Waypoint(char **stream);
    C_Waypoint(FILE *fp);
    ~C_Waypoint();
    long Size();
    void Save(char **)
    {
        ;
    }
    void Save(FILE *)
    {
        ;
    }

    // Setup Functions
    void Setup(long ID, short Type);
    void Cleanup(void);
    void SetMainImage(long imageID);
    void SetDefaultFlags()
    {
        SetFlags(DefaultFlags_);
    }
    long GetDefaultFlags()
    {
        return(DefaultFlags_);
    }
    void SetWorldRange(float minx, float miny, float maxx, float maxy)
    {
        MinWorldX_ = minx;
        MinWorldY_ = miny;
        MaxWorldX_ = maxx;
        MaxWorldY_ = maxy;
    }

    void SetFont(long ID)
    {
        Font_ = ID;
    }
    long GetFont()
    {
        return(Font_);
    }

    WAYPOINTLIST *AddWaypointToList(long CampID, short type, long NormID, long SelID, long OthrID, float x, float y, short Dragable);
    BOOL UpdateInfo(long ID, float x, float y);
    void EraseWaypointList();
    void EraseWaypointGroup(long groupid);
    BOOL ShowByType(long mask);
    BOOL HideByType(long mask);
    void SetScaleFactor(float scale);
    void SetScaleType(short scaletype);
    WAYPOINTLIST *FindID(long ID);
    void SetWPGroup(long ID, long group);
    void SetState(long ID, short state);
    void SetGroupState(long group, short state);
    void SetLabel(long ID, _TCHAR *txt);
    void SetLabelColor(long ID, COLORREF norm, COLORREF sel, COLORREF othr);
    void SetLineColor(long ID, COLORREF norm, COLORREF sel, COLORREF othr);
    _TCHAR *GetLabel(long ID);
    void SetTextOffset(long ID, short x, short y);

    WAYPOINTLIST *GetRoot()
    {
        return(Root_);
    }
    WAYPOINTLIST *GetLast()
    {
        return(LastWP_);
    }

    // Handler/Window Functions
    long CheckHotSpots(long relX, long relY);
    BOOL Dragable(long)
    {
        return(GetFlags() bitand C_BIT_DRAGABLE);
    }
    BOOL Process(long ID, short ButtonHitType);
    BOOL MouseOver(long relX, long relY, C_Base *);
    void GetItemXY(long ID, long *x, long *y);
    BOOL Drag(GRABBER *Drag, WORD MouseX, WORD MouseY, C_Window *over);
    BOOL Drop(GRABBER *, WORD , WORD , C_Window *);
    void Refresh();
    void Draw(SCREEN *surface, UI95_RECT *cliprect);
    short  Dragging()
    {
        return(Dragging_);
    }
    void SetSubParents(C_Window *par);
};

#endif