text:
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using FeedBuilder.Properties;

namespace FeedBuilder
{
	public partial class frmMain : Form
	{
		public frmMain()
		{
			InitializeComponent();
		}

		#region " Private constants/variables"

		private const string DialogFilter = "Feed configuration files (*.config)|*.config|All files (*.*)|*.*";
		private const string DefaultFileName = "FeedBuilder.config";
		private OpenFileDialog _openDialog;

		#endregion

		private ArgumentsParser _argParser;

		#region " Properties"

		public string FileName { get; set; }
		public bool ShowGui { get; set; }

		#endregion

		#region " Loading/Initialization/Lifetime"

		private void frmMain_Load(Object sender, EventArgs e)
		{
			Visible = false;
			InitializeFormSettings();
			string[] args = Environment.GetCommandLineArgs();
			// The first arg is the path to ourself
			//If args.Count >= 2 Then
			//    If File.Exists(args(1)) Then
			//        Dim p As New FeedBuilderSettingsProvider()
			//        p.LoadFrom(args(1))
			//        Me.FileName = args(1)
			//    End If
			//End If

			// The first arg is the path to ourself
			_argParser = new ArgumentsParser(args);

			if (!_argParser.HasArgs)
			{
				FreeConsole();
				return;
			}

			FileName = _argParser.FileName;
			if (!string.IsNullOrEmpty(FileName))
			{
				if (File.Exists(FileName))
				{
					FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
					p.LoadFrom(FileName);
					InitializeFormSettings();
				}
				else
				{
					_argParser.ShowGui = true;
					_argParser.Build = false;
					UpdateTitle();
				}
			}
			if (_argParser.ShowGui) Show();
			if (_argParser.Build) Build();
			if (!_argParser.ShowGui) Close();
		}

		private void InitializeFormSettings()
		{
			if (string.IsNullOrEmpty(Settings.Default.OutputFolder))
			{
				txtOutputFolder.Text = string.Empty;
			}
			else
			{
				string path = GetFullDirectoryPath(Settings.Default.OutputFolder);
				txtOutputFolder.Text = Directory.Exists(path) ? Settings.Default.OutputFolder : string.Empty;
			}

			txtFeedXML.Text = string.IsNullOrEmpty(Settings.Default.FeedXML) ? string.Empty : Settings.Default.FeedXML;
			txtBaseURL.Text = string.IsNullOrEmpty(Settings.Default.BaseURL) ? string.Empty : Settings.Default.BaseURL;

			chkVersion.Checked = Settings.Default.CompareVersion;
			chkSize.Checked = Settings.Default.CompareSize;
			chkDate.Checked = Settings.Default.CompareDate;
			chkHash.Checked = Settings.Default.CompareHash;
			chkSign.Checked = Settings.Default.Sign;
			txtSignFile.Text = Settings.Default.SignFile;

			chkIgnoreSymbols.Checked = Settings.Default.IgnoreDebugSymbols;
			chkIgnoreVsHost.Checked = Settings.Default.IgnoreVsHosting;
			chkCopyFiles.Checked = Settings.Default.CopyFiles;
			chkCleanUp.Checked = Settings.Default.CleanUp;
			txtAddExtension.Text = Settings.Default.AddExtension;

			if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
			ReadFiles();
			UpdateTitle();
		}

		private void UpdateTitle()
		{
			if (string.IsNullOrEmpty(FileName)) Text = "Feed Builder";
			else Text = "Feed Builder - " + FileName;
		}

		private void SaveFormSettings()
		{
			if (!string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) && Directory.Exists(txtOutputFolder.Text.Trim()))
				Settings.Default.OutputFolder = txtOutputFolder.Text.Trim();
			// ReSharper disable AssignNullToNotNullAttribute
			if (!string.IsNullOrEmpty(txtFeedXML.Text.Trim()) && Directory.Exists(Path.GetDirectoryName(txtFeedXML.Text.Trim())))
				Settings.Default.FeedXML = txtFeedXML.Text.Trim();
			// ReSharper restore AssignNullToNotNullAttribute
			if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) Settings.Default.BaseURL = txtBaseURL.Text.Trim();

			if (!string.IsNullOrEmpty(txtAddExtension.Text.Trim())) Settings.Default.AddExtension = txtAddExtension.Text.Trim();

			Settings.Default.CompareVersion = chkVersion.Checked;
			Settings.Default.CompareSize = chkSize.Checked;
			Settings.Default.CompareDate = chkDate.Checked;
			Settings.Default.CompareHash = chkHash.Checked;
			Settings.Default.Sign = chkSign.Checked;
			Settings.Default.SignFile = txtSignFile.Text;

			Settings.Default.IgnoreDebugSymbols = chkIgnoreSymbols.Checked;
			Settings.Default.IgnoreVsHosting = chkIgnoreVsHost.Checked;
			Settings.Default.CopyFiles = chkCopyFiles.Checked;
			Settings.Default.CleanUp = chkCleanUp.Checked;

			if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
			Settings.Default.IgnoreFiles.Clear();
			foreach (ListViewItem thisItem in lstFiles.Items)
			{
				if (!thisItem.Checked) Settings.Default.IgnoreFiles.Add(thisItem.Text);
			}
		}

		private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
		{
			SaveFormSettings();
			Settings.Default.Save();
		}

		#endregion

		#region " Commands Events"

		private void cmdBuild_Click(Object sender, EventArgs e)
		{
			Build();
		}

		private void btnOpenOutputs_Click(object sender, EventArgs e)
		{
			OpenOutputsFolder();
		}

		private void btnNew_Click(Object sender, EventArgs e)
		{
			Settings.Default.Reset();
			InitializeFormSettings();
		}

		private void btnOpen_Click(Object sender, EventArgs e)
		{
			OpenFileDialog dlg;
			if (_openDialog == null)
			{
				dlg = new OpenFileDialog
				{
					CheckFileExists = true,
					FileName = string.IsNullOrEmpty(FileName) ? DefaultFileName : FileName
				};
				_openDialog = dlg;
			}
			else dlg = _openDialog;
			dlg.Filter = DialogFilter;
			if (dlg.ShowDialog() != DialogResult.OK) return;
			FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
			p.LoadFrom(dlg.FileName);
			FileName = dlg.FileName;
			InitializeFormSettings();
		}

		private void btnSave_Click(Object sender, EventArgs e)
		{
			Save(false);
		}

		private void btnSaveAs_Click(Object sender, EventArgs e)
		{
			Save(true);
		}

		private void btnRefresh_Click(Object sender, EventArgs e)
		{
			ReadFiles();
		}

		#endregion

		#region " Options Events"

		private void cmdOutputFolder_Click(Object sender, EventArgs e)
		{
			fbdOutputFolder.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			if (fbdOutputFolder.ShowDialog(this) != DialogResult.OK) return;
			txtOutputFolder.Text = fbdOutputFolder.SelectedPath;
			ReadFiles();
		}

		private void cmdFeedXML_Click(Object sender, EventArgs e)
		{
			sfdFeedXML.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			if (sfdFeedXML.ShowDialog(this) == DialogResult.OK) txtFeedXML.Text = sfdFeedXML.FileName;
		}

		private void chkIgnoreSymbols_CheckedChanged(object sender, EventArgs e)
		{
			ReadFiles();
		}

		private void chkCopyFiles_CheckedChanged(Object sender, EventArgs e)
		{
			chkCleanUp.Enabled = chkCopyFiles.Checked;
			if (!chkCopyFiles.Checked) chkCleanUp.Checked = false;
		}

		#endregion

		#region " Helper Methods "

		private void Build()
		{
			AttachConsole(ATTACH_PARENT_PROCESS);

			Console.WriteLine("Building NAppUpdater feed '{0}'", txtBaseURL.Text.Trim());
			if (string.IsNullOrEmpty(txtFeedXML.Text))
			{
				const string msg = "The feed file location needs to be defined.\n" +
				                   "The outputs cannot be generated without this.";
				if (_argParser.ShowGui) MessageBox.Show(msg);
				Console.WriteLine(msg);
				return;
			}
			// If the target folder doesn't exist, create a path to it
			string dest = txtFeedXML.Text.Trim();
			var destDir = Directory.GetParent(GetFullDirectoryPath(Path.GetDirectoryName(dest)));
			if (!Directory.Exists(destDir.FullName)) Directory.CreateDirectory(destDir.FullName);

			XmlDocument doc = new XmlDocument();
			XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

			doc.AppendChild(dec);
			XmlElement feed = doc.CreateElement("Feed");
			if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) feed.SetAttribute("BaseUrl", txtBaseURL.Text.Trim());
			doc.AppendChild(feed);

			XmlElement tasks = doc.CreateElement("Tasks");

			Console.WriteLine("Processing feed items");
			int itemsCopied = 0;
			int itemsCleaned = 0;
			int itemsSkipped = 0;
			int itemsFailed = 0;
			int itemsMissingConditions = 0;
			foreach (ListViewItem thisItem in lstFiles.Items)
			{
				string destFile = "";
				string filename = "";
				try
				{
					filename = thisItem.Text;
					destFile = Path.Combine(destDir.FullName, filename);
				}
				catch
				{
				}
				if (destFile == "" || filename == "")
				{
					string msg = string.Format("The file could not be pathed:\nFolder:'{0}'\nFile:{1}", destDir.FullName, filename);
					if (_argParser.ShowGui) MessageBox.Show(msg);
					Console.WriteLine(msg);
					continue;
				}

				if (thisItem.Checked)
				{
					var fileInfoEx = (FileInfoEx) thisItem.Tag;
					XmlElement task = doc.CreateElement("FileUpdateTask");
					task.SetAttribute("localPath", fileInfoEx.RelativeName);

					// generate FileUpdateTask metadata items
					task.SetAttribute("lastModified",
						fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
					if (!string.IsNullOrEmpty(txtAddExtension.Text))
					{
						task.SetAttribute("updateTo", AddExtensionToPath(fileInfoEx.RelativeName, txtAddExtension.Text));
					}

					task.SetAttribute("fileSize", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
					if (!string.IsNullOrEmpty(fileInfoEx.FileVersion)) task.SetAttribute("version", fileInfoEx.FileVersion);

					XmlElement conds = doc.CreateElement("Conditions");
					XmlElement cond;

					//File Exists
					cond = doc.CreateElement("FileExistsCondition");
					cond.SetAttribute("type", "or-not");
					conds.AppendChild(cond);

					//Version
					if (chkVersion.Checked && !string.IsNullOrEmpty(fileInfoEx.FileVersion))
					{
						cond = doc.CreateElement("FileVersionCondition");
						cond.SetAttribute("type", "or");
						cond.SetAttribute("what", "below");
						cond.SetAttribute("version", fileInfoEx.FileVersion);
						conds.AppendChild(cond);
					}

					//Size
					if (chkSize.Checked)
					{
						cond = doc.CreateElement("FileSizeCondition");
						cond.SetAttribute("type", "or-not");
						cond.SetAttribute("what", "is");
						cond.SetAttribute("size", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
						conds.AppendChild(cond);
					}

					//Date
					if (chkDate.Checked)
					{
						cond = doc.CreateElement("FileDateCondition");
						cond.SetAttribute("type", "or");
						cond.SetAttribute("what", "older");
						// local timestamp, not UTC
						cond.SetAttribute("timestamp",
							fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
						conds.AppendChild(cond);
					}

					//Hash
					if (chkHash.Checked)
					{
						cond = doc.CreateElement("FileChecksumCondition");
						cond.SetAttribute("type", "or-not");
						cond.SetAttribute("checksumType", "sha256");
						cond.SetAttribute("checksum", fileInfoEx.Hash);
						conds.AppendChild(cond);
					}

					if (conds.ChildNodes.Count == 0) itemsMissingConditions++;
					task.AppendChild(conds);
					tasks.AppendChild(task);

					if (chkCopyFiles.Checked)
					{
						if (CopyFile(fileInfoEx.FileInfo.FullName, destFile)) itemsCopied++;
						else itemsFailed++;
					}
				}
				else
				{
					try
					{
						if (chkCleanUp.Checked & File.Exists(destFile))
						{
							File.Delete(destFile);
							itemsCleaned += 1;
						}
						else itemsSkipped += 1;
					}
					catch (IOException)
					{
						itemsFailed += 1;
					}
				}
			}
			feed.AppendChild(tasks);

			if (chkSign.Checked)
			{
				try
				{
					string signature = SignUpdate(doc, txtSignFile.Text);
					feed.SetAttribute("RSASignature", signature);
				}
				catch (Exception)
				{
					Console.WriteLine("Could not sign the file. Probably the private key file is invalid");
					return;
				}
			}

			string xmlDest = Path.Combine(destDir.FullName, Path.GetFileName(dest));
			doc.Save(xmlDest);

			// open the outputs folder if we're running from the GUI or
			// we have an explicit command line option to do so
			if (!_argParser.HasArgs || _argParser.OpenOutputsFolder) OpenOutputsFolder();
			Console.WriteLine("Done building feed.");
			if (itemsCopied > 0) Console.WriteLine("{0,5} items copied", itemsCopied);
			if (itemsCleaned > 0) Console.WriteLine("{0,5} items cleaned", itemsCleaned);
			if (itemsSkipped > 0) Console.WriteLine("{0,5} items skipped", itemsSkipped);
			if (itemsFailed > 0) Console.WriteLine("{0,5} items failed", itemsFailed);
			if (itemsMissingConditions > 0) Console.WriteLine("{0,5} items without any conditions", itemsMissingConditions);
		}

		private string SignUpdate(XmlDocument doc, string pathToSignFile)
		{
			string keyFileContent = null;
			if (string.IsNullOrEmpty(pathToSignFile))
			{
				throw new Exception("signature file not specified");
			}
			try
			{
				using (var file = File.Open(pathToSignFile, FileMode.Open))
				{
					StreamReader sr = new StreamReader(file);
					keyFileContent = sr.ReadToEnd();
				}
			}
			catch (Exception)
			{
				throw new Exception("Could not open or read file: " + keyFileContent);
			}
			if (string.IsNullOrEmpty(keyFileContent))
			{
				throw new Exception("key file was empty");
			}

			RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
			provider.PersistKeyInCsp = false;
			try
			{
				provider.FromXmlString(keyFileContent);
				if (provider.PublicOnly)
				{
					throw new Exception();
				}
			}
			catch (Exception)
			{
				throw new Exception(
					"Could not read signing key. It needs to have an xml format, as required by RSACryptoServiceProvider, and it needs to contain both private and public parts");
			}

			SHA512Managed sha = new SHA512Managed();
			var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(doc.InnerXml));
			string signature = Convert.ToBase64String(provider.SignHash(hash, "sha512"));
			return signature;
		}

		private bool CopyFile(string sourceFile, string destFile)
		{
			// If the target folder doesn't exist, create the path to it
			var fi = new FileInfo(destFile);
			var d = Directory.GetParent(fi.FullName);
			if (!Directory.Exists(d.FullName)) CreateDirectoryPath(d.FullName);
			if (!string.IsNullOrEmpty(txtAddExtension.Text))
			{
				destFile = AddExtensionToPath(destFile, txtAddExtension.Text);
			}

			// Copy with delayed retry
			int retries = 3;
			while (retries > 0)
			{
				try
				{
					if (File.Exists(destFile)) File.Delete(destFile);
					File.Copy(sourceFile, destFile);
					retries = 0; // success
					return true;
				}
				catch (IOException)
				{
					// Failed... let's try sleeping a bit (slow disk maybe)
					if (retries-- > 0) Thread.Sleep(200);
				}
				catch (UnauthorizedAccessException)
				{
					// same handling as IOException
					if (retries-- > 0) Thread.Sleep(200);
				}
			}
			return false;
		}

		private void CreateDirectoryPath(string directoryPath)
		{
			// Create the folder/path if it doesn't exist, with delayed retry
			int retries = 3;
			while (retries > 0 && !Directory.Exists(directoryPath))
			{
				Directory.CreateDirectory(directoryPath);
				if (retries-- < 3) Thread.Sleep(200);
			}
		}

		private void OpenOutputsFolder()
		{
			string path = txtOutputFolder.Text.Trim();

			if (string.IsNullOrEmpty(path))
			{
				return;
			}

			string dir = GetFullDirectoryPath(path);

			CreateDirectoryPath(dir);
			Process process = new Process
			{
				StartInfo =
				{
					UseShellExecute = true,
					FileName = dir
				}
			};
			process.Start();
		}

		private int GetImageIndex(string ext)
		{
			switch (ext.Trim('.'))
			{
				case "bmp":
					return 1;
				case "dll":
					return 2;
				case "doc":
				case "docx":
					return 3;
				case "exe":
					return 4;
				case "htm":
				case "html":
					return 5;
				case "jpg":
				case "jpeg":
					return 6;
				case "pdf":
					return 7;
				case "png":
					return 8;
				case "txt":
					return 9;
				case "wav":
				case "mp3":
					return 10;
				case "wmv":
					return 11;
				case "xls":
				case "xlsx":
					return 12;
				case "zip":
					return 13;
				default:
					return 0;
			}
		}

		private void ReadFiles()
		{
			string outputDir = GetFullDirectoryPath(txtOutputFolder.Text.Trim());

			if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir))
			{
				return;
			}

			outputDir = GetFullDirectoryPath(outputDir);

			lstFiles.BeginUpdate();
			lstFiles.Items.Clear();

			FileSystemEnumerator enumerator = new FileSystemEnumerator(outputDir, "*.*", true);
			foreach (FileInfo fi in enumerator.Matches())
			{
				string filePath = fi.FullName;

				if ((IsIgnorable(filePath)))
				{
					continue;
				}

				FileInfoEx fileInfo = new FileInfoEx(filePath, outputDir.Length);

				ListViewItem item = new ListViewItem(fileInfo.RelativeName, GetImageIndex(fileInfo.FileInfo.Extension));
				item.SubItems.Add(fileInfo.FileVersion);
				item.SubItems.Add(fileInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
				item.SubItems.Add(fileInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture));
				item.SubItems.Add(fileInfo.Hash);
				item.Checked = (!Settings.Default.IgnoreFiles.Contains(fileInfo.RelativeName));
				item.Tag = fileInfo;
				lstFiles.Items.Add(item);
			}

			lstFiles.EndUpdate();
		}

		private string GetFullDirectoryPath(string path)
		{
			string absolutePath = path;

			if (!Path.IsPathRooted(absolutePath))
			{
				absolutePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), path);
			}

			if (!absolutePath.EndsWith("\\"))
			{
				absolutePath += "\\";
			}

			return Path.GetFullPath(absolutePath);
		}

		private bool IsIgnorable(string filename)
		{
			string ext = Path.GetExtension(filename);
			if ((chkIgnoreSymbols.Checked && ext == ".pdb")) return true;
			return (chkIgnoreVsHost.Checked && filename.ToLower().Contains("vshost.exe"));
		}

		private string AddExtensionToPath(string filePath, string extension)
		{
			string sanitizedExtension = (extension.Trim().StartsWith(".") ? String.Empty : ".") + extension.Trim();
			return filePath + sanitizedExtension;
		}

		private void Save(bool forceDialog)
		{
			SaveFormSettings();
			if (forceDialog || string.IsNullOrEmpty(FileName))
			{
				SaveFileDialog dlg = new SaveFileDialog
				{
					Filter = DialogFilter,
					FileName = DefaultFileName
				};
				DialogResult result = dlg.ShowDialog();
				if (result == DialogResult.OK)
				{
					FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
					p.SaveAs(dlg.FileName);
					FileName = dlg.FileName;
				}
			}
			else
			{
				FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
				p.SaveAs(FileName);
			}
			UpdateTitle();
		}

		#endregion

		private void frmMain_DragEnter(object sender, DragEventArgs e)
		{
			string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
			if (files.Length == 0) return;
			e.Effect = files[0].EndsWith(".config") ? DragDropEffects.Move : DragDropEffects.None;
		}

		private void frmMain_DragDrop(object sender, DragEventArgs e)
		{
			string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
			if (files.Length == 0) return;
			try
			{
				string fileName = files[0];
				FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
				p.LoadFrom(fileName);
				FileName = fileName;
				InitializeFormSettings();
			}
			catch (Exception ex)
			{
				MessageBox.Show("The file could not be opened: \n" + ex.Message);
			}
		}

		private void helpfulTextBox1_TextChanged(object sender, EventArgs e)
		{
		}

		private void button1_Click(object sender, EventArgs e)
		{
			openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			if (openFileDialog1.ShowDialog(this) != DialogResult.OK) return;
			txtSignFile.Text = openFileDialog1.FileName;
		}

		private void chkSign_CheckedChanged(object sender, EventArgs e)
		{
			lblSignFile.Enabled = chkSign.Checked;
			cmdSignFile.Enabled = chkSign.Checked;
			txtSignFile.Enabled = chkSign.Checked;
			cmdCreateSigFile.Enabled = chkSign.Checked;

			if (!chkHash.Checked && chkSign.Checked)
			{
				chkHash.Checked = true;
			}
			chkHash.Enabled = !chkSign.Checked;
		}

		private void cmdCreateSigFile_Click(object sender, EventArgs e)
		{
			var win = new frmCreateNewSignatureFile();
			win.Show();
			win.FormClosing += (a, b) => { txtSignFile.Text = win.SelectedPublicKeyPath; };
		}

		private static readonly int ATTACH_PARENT_PROCESS = -1;

		[DllImport("kernel32.dll")]
		private static extern bool AttachConsole(int dwProcessId);

		[DllImport("kernel32.dll")]
		private static extern bool FreeConsole();
	}
}


text:
package com.thoughtworks.go.apiv2.packages.representers;

import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.api.representers.JsonReader;
import com.thoughtworks.go.domain.packagerepository.PackageRepository;
import com.thoughtworks.go.spark.Routes;

public class PackageRepositoryRepresenter {
    public static void toJSON(OutputWriter outputWriter, PackageRepository packageRepository) {
        outputWriter.addLinks(linkWriter -> {
            linkWriter.addLink("self", Routes.PackageRepository.self(packageRepository.getId()));
            linkWriter.addAbsoluteLink("doc", Routes.PackageRepository.DOC);
            linkWriter.addLink("find", Routes.PackageRepository.FIND);
        });
        outputWriter.add("id", packageRepository.getId());
        outputWriter.add("name", packageRepository.getName());
    }

    public static PackageRepository fromJSON(JsonReader jsonReader) {
        PackageRepository packageRepository = new PackageRepository();
        jsonReader.readStringIfPresent("id", packageRepository::setId);
        jsonReader.readStringIfPresent("name", packageRepository::setName);
        return packageRepository;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.thecoffeine.virtuoso.music.controller;

import com.thecoffeine.virtuoso.music.model.entity.Song;
import com.thecoffeine.virtuoso.music.model.entity.Staff;
import com.thecoffeine.virtuoso.music.model.entity.StaffType;
import com.thecoffeine.virtuoso.music.model.entity.Style;
import com.thecoffeine.virtuoso.music.model.service.SongService;
import com.thecoffeine.virtuoso.music.model.service.StaffService;
import com.thecoffeine.virtuoso.music.model.service.StaffTypeService;
import com.thecoffeine.virtuoso.music.model.service.StyleService;
import com.thecoffeine.virtuoso.music.view.form.StaffForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static org.springframework.util.Assert.notNull;

/**
 * Controller for work with staffs.
 *
 * @version 1.0
 */
@RestController
@RequestMapping( value = "/music/staffs" )
public class StaffController {

    /// *** Properties  *** ///
    @Autowired
    private SongService songService;

    @Autowired
    private StaffTypeService staffTypeService;

    @Autowired
    private StyleService styleService;

    /**
     * Service for work with staffs.
     */
    @Autowired
    private StaffService staffService;

    /// *** Methods     *** ///
    /**
     * Find all and filtering by page.
     *
     * @param page     Number of page.
     * @param limit    Count items per page.
     *
     * @return List of staffs.
     */
    @RequestMapping( method = RequestMethod.GET )
    @ResponseBody
    public List<Staff> findAllAction(
        @RequestParam( value = "page", required = false, defaultValue = "1" )
        int page,

        @RequestParam( value = "limit", required = false, defaultValue = "10" )
        int limit
    ) {
        return this.staffService.findAll(
            Math.min( page - 1, 0 ),
            limit
        );
    }

    /**
     * Create a new Staff.
     *
     * @param staffForm    Input.
     * @param response     Use for work with HTTP.
     *
     * @return Create staff.
     */
    @RequestMapping( method = RequestMethod.POST )
    @ResponseBody
    public Staff createAction(
        @Valid
        @RequestBody
        StaffForm staffForm,

        HttpServletResponse response
    ) {
        try {
            //- Search depended entities -//
            Song song = this.songService.find( staffForm.getSongId() );
            Style style = this.styleService.find( staffForm.getStyleId() );
            StaffType staffType = this.staffTypeService.find( staffForm.getStaffTypeId() );

            //- Check -//
            notNull( song );
            notNull( style );
            notNull( staffType );

            //- Set status -//
            response.setStatus( HttpServletResponse.SC_CREATED );

            //- Create a new Staff -//
            return this.staffService.create(
                new Staff(
                    song,
                    staffType,
                    style,
                    staffForm.getLocale()
                )
            );
        } catch ( IllegalArgumentException | DataIntegrityViolationException e ) {
            //- Failure. Cannot find depended entities -//
            response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
        }

        return null;
    }

    /**
     * Find.
     *
     * @param id          Id of staff.
     * @param response    Use for work with HTTP.
     *
     * @return Found staff.
     */
    @RequestMapping( value = "/{id}", method = RequestMethod.GET )
    @ResponseBody
    public Staff find(
        @PathVariable( "id" )
        Long id,

        HttpServletResponse response
    ) {
        try {
            //- Search staff -//
            Staff staff = this.staffService.find( id );

            //- Check -//
            notNull( staff );

            return staff;
        } catch ( IllegalArgumentException e ) {
            //- Failure. Cannot find staff -//
            response.setStatus( HttpServletResponse.SC_NOT_FOUND );
        }

        return null;
    }

    /**
     * Update staff.
     *
     * @param id           Id of staff.
     * @param staffForm    Input.
     * @param response     Use for work with HTTP.
     *
     * @return Updated staff.
     */
    @RequestMapping( value = "/{id}", method = RequestMethod.PUT )
    @ResponseBody
    public Staff updateAction(
        @PathVariable( "id" )
        Long id,

        @Valid
        @RequestBody
        StaffForm staffForm,

        HttpServletResponse response
    ) {
        try {
            Staff staff = this.staffService.find( id );

            notNull( staff );

            //- Search depended entities -//
            Song song = this.songService.find( staffForm.getSongId() );
            Style style = this.styleService.find( staffForm.getStyleId() );
            StaffType staffType = this.staffTypeService.find( staffForm.getStaffTypeId() );

            //- Check -//
            notNull( song );
            notNull( style );
            notNull( staffType );

            staff.setSong( song );
            staff.setStyle( style );
            staff.setStaffType( staffType );

            return this.staffService.update( staff );
        } catch ( IllegalArgumentException | DataIntegrityViolationException e ) {
            //- Failure. Cannot update staff -//
            response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
        }

        return null;
    }

    /**
     * Delete.
     *
     * @param id          Id of staff.
     * @param response    Use for work with HTTP.
     */
    @RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
    @ResponseBody
    public void deleteAction(
        @PathVariable( "id" )
        Long id,

        HttpServletResponse response
    ) {
        try {
            //- Delete staff -//
            this.staffService.delete( id );
        } catch ( DataAccessException e ) {
            //- Failure. Cannot find staff -//
            response.setStatus( HttpServletResponse.SC_NOT_FOUND );
        }
    }
}


text:
var protoclass = require("protoclass");

/**
 */

function Comment(nodeValue) {
  this.nodeValue = nodeValue || "";
  this.target    = this;
}

protoclass(Comment, {
  nodeType: 8,
  freeze: function(options) {
    return options.document.createComment(this.nodeValue);
  }
});

/**
 */

module.exports = function(nodeValue) {
  return new Comment(nodeValue);
};


text:
#include "config.h"

#if ENABLE(WEB_RTC)

#include "RTCDTMFSender.h"

#include "ExceptionCode.h"
#include "MediaStreamTrack.h"
#include "RTCDTMFSenderHandler.h"
#include "RTCDTMFToneChangeEvent.h"
#include "RTCPeerConnectionHandler.h"
#include "ScriptExecutionContext.h"

namespace WebCore {

static const long minToneDurationMs = 40;
static const long defaultToneDurationMs = 100;
static const long maxToneDurationMs = 6000;
static const long minInterToneGapMs = 30;
static const long defaultInterToneGapMs = 70;

RefPtr<RTCDTMFSender> RTCDTMFSender::create(ScriptExecutionContext* context, RTCPeerConnectionHandler* peerConnectionHandler, PassRefPtr<MediaStreamTrack> prpTrack, ExceptionCode& ec)
{
    RefPtr<MediaStreamTrack> track = prpTrack;
    std::unique_ptr<RTCDTMFSenderHandler> handler = peerConnectionHandler->createDTMFSender(&track->source());
    if (!handler) {
        ec = NOT_SUPPORTED_ERR;
        return nullptr;
    }

    RefPtr<RTCDTMFSender> dtmfSender = adoptRef(new RTCDTMFSender(context, track, WTFMove(handler)));
    dtmfSender->suspendIfNeeded();
    return dtmfSender;
}

RTCDTMFSender::RTCDTMFSender(ScriptExecutionContext* context, PassRefPtr<MediaStreamTrack> track, std::unique_ptr<RTCDTMFSenderHandler> handler)
    : ActiveDOMObject(context)
    , m_track(track)
    , m_duration(defaultToneDurationMs)
    , m_interToneGap(defaultInterToneGapMs)
    , m_handler(WTFMove(handler))
    , m_stopped(false)
    , m_scheduledEventTimer(*this, &RTCDTMFSender::scheduledEventTimerFired)
{
    m_handler->setClient(this);
}

RTCDTMFSender::~RTCDTMFSender()
{
}

bool RTCDTMFSender::canInsertDTMF() const
{
    return m_handler->canInsertDTMF();
}

MediaStreamTrack* RTCDTMFSender::track() const
{
    return m_track.get();
}

String RTCDTMFSender::toneBuffer() const
{
    return m_handler->currentToneBuffer();
}

void RTCDTMFSender::insertDTMF(const String& tones, Optional<int> duration, Optional<int> interToneGap, ExceptionCode& ec)
{
    if (!canInsertDTMF()) {
        ec = NOT_SUPPORTED_ERR;
        return;
    }

    if (duration && (duration.value() > maxToneDurationMs || duration.value() < minToneDurationMs)) {
        ec = SYNTAX_ERR;
        return;
    }

    if (interToneGap && interToneGap.value() < minInterToneGapMs) {
        ec = SYNTAX_ERR;
        return;
    }

    m_duration = duration.valueOr(defaultToneDurationMs);
    m_interToneGap = interToneGap.valueOr(defaultInterToneGapMs);

    if (!m_handler->insertDTMF(tones, m_duration, m_interToneGap))
        ec = SYNTAX_ERR;
}

void RTCDTMFSender::didPlayTone(const String& tone)
{
    scheduleDispatchEvent(RTCDTMFToneChangeEvent::create(tone));
}

void RTCDTMFSender::stop()
{
    m_stopped = true;
    m_handler->setClient(nullptr);
}

const char* RTCDTMFSender::activeDOMObjectName() const
{
    return "RTCDTMFSender";
}

bool RTCDTMFSender::canSuspendForDocumentSuspension() const
{
    // FIXME: We should try and do better here.
    return false;
}

void RTCDTMFSender::scheduleDispatchEvent(Ref<Event>&& event)
{
    m_scheduledEvents.append(WTFMove(event));

    if (!m_scheduledEventTimer.isActive())
        m_scheduledEventTimer.startOneShot(0);
}

void RTCDTMFSender::scheduledEventTimerFired()
{
    if (m_stopped)
        return;

    Vector<Ref<Event>> events;
    events.swap(m_scheduledEvents);

    for (auto& event : events)
        dispatchEvent(event);
}

} // namespace WebCore

#endif // ENABLE(WEB_RTC)