text:
package gov.nih.nci.caadapter.dvts.common.util;

import gov.nih.nci.caadapter.dvts.common.Log;
import gov.nih.nci.caadapter.dvts.common.Message;

import java.io.InputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage ;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 * This class defines a list of default settings for GUI Settings.
 *
 * @author OWNER: Scott Jiang
 * @author LAST UPDATE $Author: phadkes $
 * @version Since caAdapter v1.2
 *          revision    $Revision: 1.12 $
 *          date        $Date: 2008-06-09 19:53:51 $
 */
public class DefaultSettings
{

	private static final String PROPERTY_FONT = "Font";
	public static final Font DEFAULT_FONT;

	private static final Object[] uiDefaults = {PROPERTY_FONT, new Font("Sans Serif", Font.PLAIN, 12),
			//		PROPERTY_FONT, new Font("Serif", Font.PLAIN, 14),
			//		"Red", Color.red,
			//		"Yellow", Color.yellow,
			//		"Blue", Color.blue
	};

	private static final UIDefaults newDefaults = new UIDefaults(uiDefaults);
	private static JFileChooser defaultFileChooser;
	private static File lastPathLocation;

	static
	{
		DEFAULT_FONT = (Font) newDefaults.get(PROPERTY_FONT);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Config.FRAME_DEFAULT_HEIGHT = (int) screenSize.getHeight() - 60;//considering the existence of underneath task bar.
		Config.FRAME_DEFAULT_WIDTH = (int) screenSize.getWidth() - 20;
		installLookAndFeel();
		installFonts();
	}

	private static final JFileChooser getJFileChooser(boolean newOne)
	{
		if (newOne)
		{
			return new JFileChooser();
		}
		else
		{
			if (defaultFileChooser == null)
			{
				defaultFileChooser = new JFileChooser();
			}
			return defaultFileChooser;
		}
	}

	/**
	 * Installs the default LookAndFeel.
	 */
	private static void installLookAndFeel()
	{
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception e)
		{
			Log.logException(e, e);
		}
	}

	/**
	 * Installs the default fonts.  Currently sets to Sans Serif 11.
	 */
	private static void installFonts()
	{
		Font newFont = (Font) newDefaults.get(PROPERTY_FONT);
		//keep them in alphabetical order
		UIDefaults currentDefaults = UIManager.getDefaults();
		//		dumpMap(currentDefaults);
		currentDefaults.put("AbstractButton.clickText.font", newFont);
		currentDefaults.put("Button.clickText.font", newFont);
		currentDefaults.put("Button.font", newFont);
		currentDefaults.put("CheckBox.font", newFont);
		currentDefaults.put("CheckBoxMenuItem.acceleratorFont", newFont);
		currentDefaults.put("CheckBoxMenuItem.font", newFont);
		currentDefaults.put("ColorChooser.font", newFont);
		currentDefaults.put("ComboBox.font", newFont);
		currentDefaults.put("DesktopIcon.font", newFont);
		currentDefaults.put("EditorPane.font", newFont);
		currentDefaults.put("FileChooser.listFont", newFont);
		currentDefaults.put("InternalFrame.font", newFont);
		currentDefaults.put("Label.font", newFont);
		currentDefaults.put("List.font", newFont);
		currentDefaults.put("Menu.acceleratorFont", newFont);
		currentDefaults.put("Menu.font", newFont);
		currentDefaults.put("MenuBar.font", newFont);
		currentDefaults.put("MenuItem.font", newFont);
		currentDefaults.put("MenuItem.acceleratorFont", newFont);
		//		currentDefaults.put("MenuItem.accelerator.font", newFont);
		currentDefaults.put("OptionPane.font", newFont);
		currentDefaults.put("Panel.font", newFont);
		currentDefaults.put("PasswordField.font", newFont);
		currentDefaults.put("PopupMenu.font", newFont);
		currentDefaults.put("ProgressBar.font", newFont);
		currentDefaults.put("RadioButton.font", newFont);
		currentDefaults.put("RadioButtonMenuItem.acceleratorFont", newFont);
		currentDefaults.put("RadioButtonMenuItem.font", newFont);
		currentDefaults.put("ScrollPane.font", newFont);
		currentDefaults.put("TabbedPane.font", newFont);
		currentDefaults.put("Table.font", newFont);
		currentDefaults.put("TableHeader.font", newFont);
		currentDefaults.put("TextArea.font", newFont);
		currentDefaults.put("TextField.font", newFont);
		currentDefaults.put("TextPane.font", newFont);
		currentDefaults.put("TitledBorder.font", newFont);
		currentDefaults.put("ToggleButton.font", newFont);
		currentDefaults.put("ToolBar.font", newFont);
		currentDefaults.put("ToolTip.font", newFont);
		currentDefaults.put("Tree.font", newFont);
		currentDefaults.put("Viewport.font", newFont);
		currentDefaults.put("win.frame.captionFont", newFont);
		currentDefaults.put("win.messagebox.font", newFont);
		//		dumpMap(currentDefaults);
	}

	/**
	 * Returns the classname without the package.
	 * Example: If the input class is java.lang.String
	 * than the return value is String.
	 *
	 * @param cl The class to inspect
	 * @return The classname
	 */
	public static String getClassNameWithoutPackage(Class cl)
	{
		// build the name for this action
		// without the package prefix
		String className = cl.getName();
		int pos = className.lastIndexOf('.') + 1;
		if (pos == -1)
		{
			pos = 0;
		}
		String name = className.substring(pos);
		return name;
	}

	/**
	 * Center the window to the middle of the screen.
	 *
	 * @param frame
	 */
	public static void centerWindow(Window frame)
	{
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = frame.getSize();
		frame.setLocation(screenSize.width / 2 - (frameSize.width / 2), screenSize.height / 2 - (frameSize.height / 2));
	}

	/**
	 * Title shall better contain "open" or "save" to indicate whether to open or save.
	 *
	 * @param parentComponent
	 * @param fileExtension
	 * @param title
	 * @param saveMode		if true, it will show a SaveDialog
	 * @param checkDuplicate  if true, will check if user specified file already exists and will ask for either overwrite or specify another one;
	 * @return The File Object that contains user input; null if user cancelled the input dialog.
	 */
	public static final File getUserInputOfFileFromGUI(Component parentComponent, String fileExtension, String title, boolean saveMode, boolean checkDuplicate)
	{
		if (lastPathLocation == null)
		{
			lastPathLocation = new File(FileUtil.getUIWorkingDirectoryPath());
		}
		return getUserInputOfFileFromGUI(parentComponent, lastPathLocation.getAbsolutePath(), fileExtension, title, saveMode, checkDuplicate);
	}

	/**
	 * Title shall better contain "open" or "save" to indicate whether to open or save.
	 *
	 * @param parentComponent
	 * @param workingDirectoryPath
	 * @param fileExtension
	 * @param title
	 * @param saveMode			 if true, it will show a SaveDialog
	 * @param checkDuplicate	   if true, will check if user specified file already exists and will ask for either overwrite or specify another one;
	 * @return The File Object that contains user input; null if user cancelled the input dialog.
	 */
	public static final File getUserInputOfFileFromGUI(Component parentComponent, String workingDirectoryPath, String fileExtension, String title, boolean saveMode, boolean checkDuplicate)
	{
		File file = null;

		JFileChooser fileChooser = getJFileChooser(true);
		fileChooser.setCurrentDirectory(new File(workingDirectoryPath));
		boolean toSelectedDir=false;
		ArrayList<FileFilter> fileFilters=new ArrayList<FileFilter>();
		if ((fileExtension==null)||(fileExtension.trim().equals("")))
		{
			fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			toSelectedDir=true;
		}
        else if ((fileExtension.equals("*.*"))||(fileExtension.equals(".*")))      //JFileChooser.FILES_AND_DIRECTORIES
		{
			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//.DIRECTORIES_ONLY);
			toSelectedDir=true;
		}
        else if (fileExtension.equals("*"))      //JFileChooser.FILES_AND_DIRECTORIES
		{
			fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);//.DIRECTORIES_ONLY);
			toSelectedDir=true;
		}
        else
		{
			StringTokenizer stk=new StringTokenizer(fileExtension,";");
			while (stk.hasMoreElements())
			{
				String nxtExt=(String)stk.nextElement();
				FileFilter singleFileFilter = new SingleFileFilter(nxtExt);
				fileFilters.add(singleFileFilter);
				fileChooser.addChoosableFileFilter(singleFileFilter);
			}
		}
		fileChooser.setDialogTitle(title);

		do
		{
			int returnVal = -1;
			file = null;
			if (saveMode || (title != null && title.toLowerCase().indexOf("save") != -1))
			{
				returnVal = fileChooser.showSaveDialog(parentComponent);
			}
			else if (toSelectedDir)
				returnVal = fileChooser.showDialog(parentComponent, "Select");
			else
			{
				returnVal = fileChooser.showOpenDialog(parentComponent);
			}

			if (returnVal == JFileChooser.APPROVE_OPTION)
			{
				file = fileChooser.getSelectedFile();
				if (file == null)
				{//this condition could happen when a double click occurred in the file selection panel, but did not select anything
					JOptionPane.showMessageDialog(parentComponent, "No file is selected. Please select a file.", "No file selected", JOptionPane.ERROR_MESSAGE);
					continue;
				}

				//since this point on, file will not be null.
				for(FileFilter fileFilter:fileFilters)
				{
				if (GeneralUtilities.areEqual(fileFilter, fileChooser.getFileFilter()))
				{//if and only if the currently used file filter in fileChooser is the same as the given fileFilter.
					file = FileUtil.appendFileNameWithGivenExtension(file, ((SingleFileFilter)fileFilter).getExtension(), true);
					break;
				}
				}
				if (checkDuplicate)
				{
					if (file.exists())
					{
						String msg = "'" + file.getName() + "' already exists in the specified directory. Would you like to overwrite it?";
						int userChoice = JOptionPane.showConfirmDialog(parentComponent, msg, "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
						if (userChoice == JOptionPane.YES_OPTION)
						{
							break;
						}
					}
					else
					{
						break;
					}
				}
				else
				{//do not check duplicate, then check if file exists for Open mode.
					if (!saveMode)
					{//if not in save mode, it will be in open mode
						if (!file.exists())
						{
							String msg = "'" + file.getName() + "' does not exist in the specified directory. Please select another file.";
							JOptionPane.showMessageDialog(parentComponent, msg, "File does not exist", JOptionPane.ERROR_MESSAGE);
							continue;
						}
					}
					break;
				}
			}
			else
			{
				break;
			}
		}
		while (true);

		if (file != null)
		{
			lastPathLocation = file.getParentFile();
		}

		//clear out the file filter after usage.
		for(FileFilter fileFilter:fileFilters)
		fileChooser.removeChoosableFileFilter(fileFilter);

		System.out.println("DefaultSettings.getUserInputOfFileFromGUI()..currentDir:"+fileChooser.getCurrentDirectory());

		return file;
	}

	/**
	 * @param imageFileName the name of the file, does not need path information
	 * @return the image retrieved from the system.
	 */
	public static final Image getImage(String imageFileName)
	{
		String imgFilePath="images/";
		imgFilePath = imgFilePath + imageFileName;
		//Thread.currentThread().getContextClassLoader().getResource( imgFilePath );

//		URL imgUrl=Thread.currentThread().getContextClassLoader().getResource( imgFilePath );
//		return Toolkit.getDefaultToolkit().createImage(imgUrl);
		Image rtnImg=null;
		//URL imgUrl=ClassLoader.getSystemResource(imgFilePath);
		try {
			InputStream imgStream=DefaultSettings.class.getClassLoader().getResource(imgFilePath).openStream();
			BufferedImage bfImage=ImageIO.read(imgStream);
			rtnImg=(Image)bfImage;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.logException("Failed to load image:"+imageFileName, e);
			e.printStackTrace();
		}
		return rtnImg;
	}

	/**
	 * Currently will setOneTouchExpandable to be true and setDividerSize to be Config.DEFAULT_DIVIDER_SIZE.
	 *
	 * @param splitPane
	 */
	public static final void setDefaultFeatureForJSplitPane(JSplitPane splitPane)
	{
		if (splitPane != null)
		{
			splitPane.setBorder(BorderFactory.createEmptyBorder());
			splitPane.setOneTouchExpandable(true);
			splitPane.setDividerSize(Config.DEFAULT_DIVIDER_SIZE);
		}
	}

	/**
	 * Currently utilize JOptionPane to report any given throwable to UI.
	 *
	 * @param t					 the throwable
	 * @param alternativeMessageStr if null or empty, just ignore;
	 * @param parentComponent
	 * @param substitute			if true and alternativeMessageStr is not null or empty,, will use alternativeMessageStr for display other than the error message within the Throwable.
	 * @param supressToUI		   if true, the message will not report to UI; otherwise, it will report to UI.
	 */
	public static void reportThrowableToLogAndUI(Object sender, Throwable t, String alternativeMessageStr, Component parentComponent, boolean substitute, boolean supressToUI)
	{
		String reportMsg = null;
		if (substitute && !GeneralUtilities.isBlank(alternativeMessageStr))
		{
			reportMsg = alternativeMessageStr;
		}
		else
		{
			if (t instanceof Error || t instanceof RuntimeException)
			{//unchecked exception occurred. Just report the nice one
				Message msg = MessageResources.getMessage("GEN0", new Object[]{t.getMessage()});
				reportMsg = msg.toString();
			}
			else
			{//checked exception, just report directly.
				if (t != null)
				{//throwable is not null, pick message from it
					String message = t.getMessage();
					if (GeneralUtilities.isBlank(message))
					{//if its own message is empty, pick from stack trace.
						StringWriter sw = new StringWriter();
						PrintWriter pw = new PrintWriter(sw);
						t.printStackTrace(pw);
						pw.flush();
						reportMsg = sw.toString();
					}
					else
					{//otherwise, use its message directly.
						reportMsg = message;
					}
				}
				else
				{
					reportMsg = "Unknown Error.";
				}
			}
		}
		if (t instanceof Error || t instanceof RuntimeException)
		{//unchecked exception occurred. Just report the nice one
			//			Log.logError(sender, reportMsg);
			Log.logError(sender, t);
		}
		else if (t != null)
		{//checked exception, just report directly.
			Log.logException(sender, reportMsg, t);
		}
		else
		{//t is null, so log the report msg
			Log.logInfo(sender, reportMsg);
		}

		if (!supressToUI)
		{
			if (parentComponent != null && !(parentComponent instanceof Container))
			{
				JOptionPane.showMessageDialog(parentComponent.getParent(), reportMsg, "Exception Occurred(1)", JOptionPane.ERROR_MESSAGE);
			}
			else
			{
				JOptionPane.showMessageDialog(parentComponent, reportMsg, "Exception Occurred(2)", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Find the root container class of the given component.
	 *
	 * @param component
	 * @return null if nothing is found or the given component is null.
	 */
	public static Container findRootContainer(JComponent component)
	{
		if (component != null)
		{
			Container container = null;
			JRootPane rootPane = component.getRootPane();
			if (rootPane != null)
			{
				container = rootPane.getParent();
			}
			return container;
		}
		else
		{
			return null;
		}
	}
}
/**
 * HISTORY      : $Log: not supported by cvs2svn $
 * HISTORY      : Revision 1.11  2008/05/29 00:30:18  umkis
 * HISTORY      : add a FileChooser option 'DIRECTORY_FILE' onto getUserInputOfFileFromGUI().
 * HISTORY      :
 * HISTORY      : Revision 1.10  2008/04/01 21:07:18  umkis
 * HISTORY      : minor change
 * HISTORY      :
 * HISTORY      : Revision 1.9  2008/01/31 21:44:22  umkis
 * HISTORY      : csv converting from multi message included v2 file.
 * HISTORY      :
 * HISTORY      : Revision 1.8  2007/11/28 15:05:40  wangeug
 * HISTORY      : setup UI environment with DefaultSettings implementation
 * HISTORY      :
 * HISTORY      : Revision 1.7  2007/11/14 20:55:57  wangeug
 * HISTORY      : clean codes
 * HISTORY      :
 * HISTORY      : Revision 1.6  2007/09/18 15:25:52  wangeug
 * HISTORY      : modify FileChooser to select Directory
 * HISTORY      :
 * HISTORY      : Revision 1.5  2007/08/10 16:48:24  wangeug
 * HISTORY      : make File choose work with multiple extensions
 * HISTORY      :
 * HISTORY      : Revision 1.4  2007/07/14 20:26:18  umkis
 * HISTORY      : add a comment about 'imageFileName'
 * HISTORY      :
 * HISTORY      : Revision 1.3  2007/06/12 15:47:59  wangeug
 * HISTORY      : load image with "getResource()" as an input stream and read the image with bufferedImage
 * HISTORY      :
 * HISTORY      : Revision 1.2  2007/06/07 15:15:14  schroedn
 * HISTORY      : Edits to sync with new codebase and java webstart
 * HISTORY      :
 * HISTORY      : Revision 1.1  2007/04/03 16:17:14  wangeug
 * HISTORY      : initial loading
 * HISTORY      :
 * HISTORY      : Revision 1.40  2006/08/02 18:44:24  jiangsc
 * HISTORY      : License Update
 * HISTORY      :
 * HISTORY      : Revision 1.39  2006/01/09 17:49:11  umkis
 * HISTORY      : change the icon image of mainFrame
 * HISTORY      :
 * HISTORY      : Revision 1.38  2006/01/03 19:16:53  jiangsc
 * HISTORY      : License Update
 * HISTORY      :
 * HISTORY      : Revision 1.37  2006/01/03 18:56:26  jiangsc
 * HISTORY      : License Update
 * HISTORY      :
 * HISTORY      : Revision 1.36  2005/12/29 23:06:16  jiangsc
 * HISTORY      : Changed to latest project name.
 * HISTORY      :
 * HISTORY      : Revision 1.35  2005/12/29 15:39:06  chene
 * HISTORY      : Optimize imports
 * HISTORY      :
 * HISTORY      : Revision 1.34  2005/12/14 21:37:18  jiangsc
 * HISTORY      : Updated license information
 * HISTORY      :
 * HISTORY      : Revision 1.33  2005/11/23 20:03:30  jiangsc
 * HISTORY      : Enhancement on mapping validations.
 * HISTORY      :
 * HISTORY      : Revision 1.32  2005/11/16 22:33:50  jiangsc
 * HISTORY      : Update License Information
 * HISTORY      :
 * HISTORY      : Revision 1.31  2005/11/14 19:55:51  jiangsc
 * HISTORY      : Implementing UI enhancement
 * HISTORY      :
 * HISTORY      : Revision 1.30  2005/11/11 19:23:59  jiangsc
 * HISTORY      : Support Pseudo Root in Mapping Panel.
 * HISTORY      :
 * HISTORY      : Revision 1.29  2005/11/08 23:09:48  jiangsc
 * HISTORY      : Save point
 * HISTORY      :
 * HISTORY      : Revision 1.28  2005/10/31 21:31:52  jiangsc
 * HISTORY      : Fix to Defect 164 and 162.
 * HISTORY      :
 * HISTORY      : Revision 1.27  2005/10/26 18:12:29  jiangsc
 * HISTORY      : replaced printStackTrace() to Log.logException
 * HISTORY      :
 * HISTORY      : Revision 1.26  2005/10/26 16:22:10  jiangsc
 * HISTORY      : Face lift to provide better error report.
 * HISTORY      :
 * HISTORY      : Revision 1.25  2005/10/21 15:12:19  jiangsc
 * HISTORY      : Reporting error enhancement
 * HISTORY      :
 * HISTORY      : Revision 1.24  2005/10/18 14:44:04  jiangsc
 * HISTORY      : Fixed the defect that caused file name not populated in the FileChooser upon double clicking.
 * HISTORY      :
 * HISTORY      : Revision 1.23  2005/10/14 21:03:50  jiangsc
 * HISTORY      : Minor update
 * HISTORY      :
 * HISTORY      : Revision 1.22  2005/10/13 17:37:42  jiangsc
 * HISTORY      : Enhanced UI reporting on exceptions.
 * HISTORY      :
 * HISTORY      : Revision 1.21  2005/10/13 15:44:39  jiangsc
 * HISTORY      : Re-engineered exception reporting to DefaultSettings class.
 * HISTORY      :
 * HISTORY      : Revision 1.20  2005/10/12 21:42:46  jiangsc
 * HISTORY      : Added validation on invalid file type.
 * HISTORY      :
 * HISTORY      : Revision 1.19  2005/10/10 20:49:02  jiangsc
 * HISTORY      : Enhanced dialog operation.
 * HISTORY      :
 * HISTORY      : Revision 1.18  2005/10/04 20:22:22  jiangsc
 * HISTORY      : Updated FileChooser with consistent look and feel.
 * HISTORY      :
 * HISTORY      : Revision 1.17  2005/10/04 17:20:30  jiangsc
 * HISTORY      : Keep Open/Save dialog remember last location.
 * HISTORY      :
 * HISTORY      : Revision 1.16  2005/09/29 22:16:02  jiangsc
 * HISTORY      : Save point
 * HISTORY      :
 * HISTORY      : Revision 1.15  2005/09/16 23:19:08  chene
 * HISTORY      : Database prototype GUI support, but can not be loaded
 * HISTORY      :
 * HISTORY      : Revision 1.14  2005/08/11 22:10:37  jiangsc
 * HISTORY      : Open/Save File Dialog consolidation.
 * HISTORY      :
 * HISTORY      : Revision 1.13  2005/08/04 22:22:24  jiangsc
 * HISTORY      : Updated license and class header information.
 * HISTORY      :
 */


text:
#if !defined(BOOST_SPIRIT_X3_LITERAL_CHAR_APRIL_16_2006_1051AM)
#define BOOST_SPIRIT_X3_LITERAL_CHAR_APRIL_16_2006_1051AM

#include <boost/spirit/home/x3/char/char_parser.hpp>
#include <boost/spirit/home/x3/support/utility/utf8.hpp>
#include <boost/type_traits/is_same.hpp>

namespace boost { namespace spirit { namespace x3
{
    template <typename Encoding, typename Attribute = typename Encoding::char_type>
    struct literal_char : char_parser<literal_char<Encoding, Attribute>>
    {
        typedef typename Encoding::char_type char_type;
        typedef Encoding encoding;
        typedef Attribute attribute_type;
        static bool const has_attribute =
            !is_same<unused_type, attribute_type>::value;

        template <typename Char>
        literal_char(Char ch)
          : ch(static_cast<char_type>(ch)) {}

        template <typename Char, typename Context>
        bool test(Char ch_, Context const& context) const
        {
            return ((sizeof(Char) <= sizeof(char_type)) || encoding::ischar(ch_))
                && (get_case_compare<encoding>(context)(ch, char_type(ch_)) == 0);
        }

        char_type ch;
    };

    template <typename Encoding, typename Attribute>
    struct get_info<literal_char<Encoding, Attribute>>
    {
        typedef std::string result_type;
        std::string operator()(literal_char<Encoding, Attribute> const& p) const
        {
            return '\'' + to_utf8(Encoding::toucs4(p.ch)) + '\'';
        }
    };
}}}

#endif

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Aesculus chekiangensis Hu & Fang

### Remarks
null


text:
using System.Collections.Generic;

namespace Inlinq.Impl
{
    public sealed class InlinqSortedSet<T> : Collection<T, SortedSet<T>.Enumerator>
    {
        private SortedSet<T> source;
        public InlinqSortedSet(SortedSet<T> source) => this.source = source;
        public override int Count => source.Count;
        public override bool Contains(T item) => source.Contains(item);
        public override void CopyTo(T[] array, int arrayIndex) => source.CopyTo(array, arrayIndex);
        public override SortedSet<T>.Enumerator GetEnumerator() => source.GetEnumerator();
    }
}


text:
<nav>
{{ partial "docs/brand" . }}
{{ partial "docs/search" . }}
{{ if .Site.IsMultiLingual }}
  {{ partial "docs/languages" . }}
{{ end }}

{{ partial "docs/inject/menu-before" . }}
{{ partial "docs/menu-hugo" .Site.Menus.before }}

{{ if .Site.Params.BookMenuBundle }}
  {{ partial "docs/menu-bundle" . }}
{{ else }}
  {{ partial "docs/menu-filetree" . }}
{{ end }}

{{ partial "docs/menu-hugo" .Site.Menus.after }}
{{ partial "docs/inject/menu-after" . }}
</nav>

<!-- Restore menu position as soon as possible to avoid flickering -->
{{ $script := resources.Get "menu-reset.js" | resources.Minify }}
{{ with $script.Content }}
  <script>{{ . | safeJS }}</script>
{{ end }}


text:
$:.unshift File.join(File.dirname(__FILE__), "..", "..", "lib")
require 'neptune'

$:.unshift File.join(File.dirname(__FILE__), "..", "test", "integration")
require 'test_helper'

require 'test/unit'

class TestC < Test::Unit::TestCase
  # unlike the other language interfaces, we don't run c code yet
  # just compile it - this may change in the future

  def test_c_compile
    ring_code = <<BAZ
#include <stdio.h>

int main() {
  printf("hello world!");
  return 0;
}
BAZ

    contents = TestHelper.get_random_alphanumeric(1024)
    folder = "hello-world-#{TestHelper.get_random_alphanumeric}"
    source = "HelloWorld.c"

    tmp_folder = "/tmp/#{folder}"
    FileUtils.mkdir_p(tmp_folder)
    compiled = "#{tmp_folder}-compiled"
    compiled_code = "#{compiled}/HelloWorld"

    local = "#{tmp_folder}/#{source}"
    TestHelper.write_file(local, ring_code)

    output = TestHelper.get_output_location(folder)

    compile_c_code(tmp_folder, source, compiled)

    FileUtils.rm_rf(tmp_folder)
    FileUtils.rm_rf(compiled)
  end

  def compile_c_code(location, main_file, compiled)
    std_out, std_err = TestHelper.compile_code(location, main_file, compiled)

    make = "gcc -o HelloWorld HelloWorld.c -Wall"
    msg = "The C Hello World code did not compile as expected. It should have " +
      "compiled with the command [#{make}] instead of [#{std_out}]."
    assert(std_out.include?(make), msg)

    msg = "The C Hello World code did not compile successfully. It reported " +
      "the following error: #{std_err}"
    assert_nil(std_err, msg)
  end
end


text:
        <a href="<?php echo site_url()?>bed/admin"><?php echo $link1 ?>
        <?php echo $link2 ?>

 <?php echo $link1 ?>

<?php echo $link2 ?>

                    Aksi Table

                        <button class="btn btn-box-tool" data-widget="collapse"></button>

                    <button class="btn btn-xs btn-success" data-rel="tooltip" title="Add Data" onClick="add()">Add</button>
                    <button class="btn btn-xs btn-default" data-rel="tooltip" title="Refresh data" onClick="reload_table()"> Reload</button>
                    <button class="btn btn-xs btn-danger" data-rel="tooltip" title="Hapus Data" onClick="bulk_delete()"> Bulk Action</button>

                                  <input type="checkbox" id="check-all">
                                  No
                                  Nama Kamar
                                  Kelas
                                  Paviliun
                                  Aksi

                                  <input type="checkbox" id="check-all">
                                  No
                                  Nama Kamar
                                  Kelas
                                  Paviliun
                                  Aksi

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

                <form action="#" id="form" class="form-horizontal" class='has-error' method="post">

                      <form role="form">

                          Paviliun
                          <input type="hidden" class="form-control input-sm" id="id_pk" name="id_pk" placeholder="Enter ..." >
                          <select class="form-control select2" style="width: 100%;" name="id_paviliun" id="id_paviliun">
                          <?php
                              foreach ($paviliun as $row) {
                                echo "<option value=".$row->id_paviliun.">".strtoupper($row->nama_paviliun)."</option>";
                              }
                          ?>
                          </select>
                          Help block with error

                          Nama Kamar
                          <input type="text" class="form-control input-sm" id="nama_kamar" name="nama_kamar" placeholder="Enter ...">
                          Help block with error

                          Kelas
                          <select class="form-control" name="kelas" style="width: 100%;">
                            <option selected="selected" value='kelas I'>Kelas I</option>
                            <option value="kelas II">Kelas II</option>
                            <option value="kelas III">Kelas III</option>
                            <option value="VIP">VIP</option>
                            <option value="VVIP">VVIP</option>
                          </select>
                          Help block with error

                      </form>

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>


text:
module BioVcf
end


text:
title: "Fleet Specification"
linkTitle: "Fleet"
date: 2019-01-03T03:58:52Z
description: "A `Fleet` is a set of warm GameServers that are available to be allocated from."
weight: 20
---

To allocate a `GameServer` from a `Fleet`, use a `GameServerAllocation`.

Like any other Kubernetes resource you describe a `Fleet`'s desired state via a specification written in YAML or JSON to the Kubernetes API. The Agones controller will then change the actual state to the desired state.

A full `Fleet` specification is available below and in the {{< ghlink href="examples/fleet.yaml" >}}example folder{{< /ghlink >}} for reference :

```yaml
apiVersion: "agones.dev/v1"
kind: Fleet
# Fleet Metadata
# {{< k8s-api href="#objectmeta-v1-meta" >}}
metadata:
  name: fleet-example
spec:
  # the number of GameServers to keep Ready or Allocated in this Fleet
  replicas: 2
  # defines how GameServers are organised across the cluster.
  # Options include:
  # "Packed" (default) is aimed at dynamic Kubernetes clusters, such as cloud providers, wherein we want to bin pack
  # resources
  # "Distributed" is aimed at static Kubernetes clusters, wherein we want to distribute resources across the entire
  # cluster
  scheduling: Packed
  # a GameServer template - see:
  # https://agones.dev/site/docs/reference/gameserver/ for all the options
  strategy:
    # The replacement strategy for when the GameServer template is changed. Default option is "RollingUpdate",
    # "RollingUpdate" will increment by maxSurge value on each iteration, while decrementing by maxUnavailable on each
    # iteration, until all GameServers have been switched from one version to another.
    # "Recreate" terminates all non-allocated GameServers, and starts up a new set with the new details to replace them.
    type: RollingUpdate
    # Only relevant when `type: RollingUpdate`
    rollingUpdate:
      # the amount to increment the new GameServers by. Defaults to 25%
      maxSurge: 25%
      # the amount to decrements GameServers by. Defaults to 25%
      maxUnavailable: 25%
  template:
    # GameServer metadata
    metadata:
      labels:
        foo: bar
    # GameServer specification
    spec:
      ports:
      - name: default
        portPolicy: Dynamic
        containerPort: 26000
      health:
        initialDelaySeconds: 30
        periodSeconds: 60
      # Parameters for game server sidecar
      sdkServer:
        logLevel: Info
        grpcPort: 9357
        httpPort: 9358
      # The GameServer's Pod template
      template:
        spec:
          containers:
          - name: simple-game-server
            image: {{< example-image >}}
```

Since Agones defines a new
[Custom Resources Definition (CRD)](https://kubernetes.io/docs/concepts/api-extension/custom-resources/)
we can define a new resource using the kind `Fleet` with the custom group `agones.dev` and API
version `v1`.

You can use the metadata field to target a specific
[namespaces](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) but also
attach specific [annotations](https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/)
and [labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) to your resource.
This is a very common pattern in the Kubernetes ecosystem.

The length of the `name` field of the fleet should be at most 63 characters.

The `spec` field is the actual `Fleet` specification and it is composed as follow:

- `replicas` is the number of `GameServers` to keep Ready or Allocated in this Fleet
- `scheduling` defines how GameServers are organised across the cluster. Affects backing Pod scheduling, as well as scale
                 down mechanics.
                 "Packed" (default) is aimed at dynamic Kubernetes clusters, such as cloud providers, wherein we want to bin pack
                 resources. "Distributed" is aimed at static Kubernetes clusters, wherein we want to distribute resources across the entire
                 cluster. See [Scheduling and Autoscaling]({{< relref "../Advanced/scheduling-and-autoscaling.md" >}}) for more details.
- `strategy` is the `GameServer` replacement strategy for when the `GameServer` template is edited.
  - `type` is replacement strategy for when the GameServer template is changed. Default option is "RollingUpdate", but "Recreate" is also available.
    - `RollingUpdate` will increment by `maxSurge` value on each iteration, while decrementing by `maxUnavailable` on each iteration, until all GameServers have been switched from one version to another.
    - `Recreate` terminates all non-allocated `GameServers`, and starts up a new set with the new `GameServer` configuration to replace them.
  - `rollingUpdate` is only relevant when `type: RollingUpdate`
    - `maxSurge` is the amount to increment the new GameServers by. Defaults to 25%
    - `maxUnavailable` is the amount to decrements GameServers by. Defaults to 25%
- `template` a full `GameServer` configuration template.
   See the [GameServer]({{< relref "gameserver.md" >}}) reference for all available fields.

## Fleet Scale Subresource Specification

Scale subresource is defined for a Fleet. Please refer to [Kubernetes docs](https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#subresources).

You can use the following command to scale the fleet with name simple-game-server:

```bash
kubectl scale fleet simple-game-server --replicas=10
```
```
fleet.agones.dev/simple-game-server scaled
```

You can also use [Kubernetes API]({{< ref "/docs/Guides/access-api.md" >}}) to get or update the Replicas count:

```bash
curl http://localhost:8001/apis/agones.dev/v1/namespaces/default/fleets/simple-game-server/scale
```
```
{
  "kind": "Scale",
  "apiVersion": "autoscaling/v1",
  "metadata": {
    "name": "simple-game-server",
    "namespace": "default",
    "selfLink": "/apis/agones.dev/v1/namespaces/default/fleets/simple-game-server/scale",
    "uid": "4dfaa310-2566-11e9-afd1-42010a8a0058",
    "resourceVersion": "292652",
    "creationTimestamp": "2019-01-31T14:41:33Z"
  },
  "spec": {
    "replicas": 10
  },
  "status": {
    "replicas": 10
  }
```

Also exposing a Scale subresource would allow you to configure HorizontalPodAutoscaler and PodDisruptionBudget for a fleet in the future. However these features have not been tested, and are not currently supported - but if you are looking for these features, please be sure to let us know in the [ticket](https://github.com/googleforgames/agones/issues/553).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using RichardSzalay.MockHttp.Matchers;
using RichardSzalay.MockHttp.Tests.Infrastructure;
using Xunit;

namespace RichardSzalay.MockHttp.Tests.Matchers
{
    public class FormDataMatcherTests
    {
        [Fact]
        public void Should_match_in_order()
        {
            bool result = Test(
                expected: "key1=value1&key2=value2",
                actual: "key1=value1&key2=value2"
                );

            Assert.True(result);
        }

        [Fact]
        public void Should_match_out_of_order()
        {
            bool result = Test(
                expected: "key2=value2&key1=value1",
                actual: "key1=value1&key2=value2"
                );

            Assert.True(result);
        }

        [Fact]
        public void Should_match_multiple_values()
        {
            bool result = Test(
                expected: "key1=value1&key1=value2",
                actual: "key1=value2&key1=value1"
                );

            Assert.True(result);
        }

        [Fact]
        public void Should_support_matching_empty_values()
        {
            bool result = Test(
                expected: "key2=value2&key1",
                actual: "key1&key2=value2"
                );

            Assert.True(result);
        }

        [Fact]
        public void Should_fail_for_incorrect_values()
        {
            bool result = Test(
                expected: "key1=value1&key2=value3",
                actual: "key1=value1&key2=value2"
                );

            Assert.False(result);
        }

        [Fact]
        public void Should_fail_for_missing_keys()
        {
            bool result = Test(
                expected: "key2=value2&key1=value1",
                actual: "key1=value1&key3=value3"
                );

            Assert.False(result);
        }

        [Fact]
        public void Should_not_fail_for_additional_keys_when_exact_is_false()
        {
            bool result = Test(
                expected: "key1=value1&key2=value2",
                actual: "key1=value1&key2=value2&key3=value3",
                exact: false
                );

            Assert.True(result);
        }

        [Fact]
        public void Should_fail_for_additional_keys_when_exact_is_true()
        {
            bool result = Test(
                expected: "key1=value1&key2=value2",
                actual: "key1=value1&key2=value2&key3=value3",
                exact: true
                );

            Assert.False(result);
        }

        private bool Test(string expected, string actual, bool exact = false)
        {
            var sut = new FormDataMatcher(expected, exact);

            FormUrlEncodedContent content = new FormUrlEncodedContent(
                HttpHelpers.ParseQueryString(actual)
                );

            return sut.Matches(new HttpRequestMessage(HttpMethod.Get,
                "http://tempuri.org/home") { Content = content });
        }

        [Fact]
        public void Should_support_matching_dictionary_data_with_url_encoded_values1()
        {
            var data = new Dictionary<string, string>();
            data.Add("key", "Value with spaces");

            var content = new FormUrlEncodedContent(data);

            var sut = new FormDataMatcher(data);

            var actualMatch = sut.Matches(new HttpRequestMessage(HttpMethod.Get, "http://tempuri.org/home") { Content = content });

            Assert.True(actualMatch, "FormDataMatcher.Matches() should match dictionary data with URL encoded query string values.");
        }

        [Fact]
        public void Should_support_matching_dictionary_data_with_url_encoded_values2()
        {
            var data = new Dictionary<string, string>();
            data.Add("key", "Value with spaces");

            var content = new FormUrlEncodedContent(data);

            var sut = new FormDataMatcher("key=Value+with%20spaces");

            var actualMatch = sut.Matches(new HttpRequestMessage(HttpMethod.Get, "http://tempuri.org/home") { Content = content });

            Assert.True(actualMatch, "FormDataMatcher.Matches() should match dictionary data with URL encoded query string values.");
        }

        [Fact]
        public void Should_fail_for_non_form_data()
        {
            var content = new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key=value"));
            content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

            var result = Test(
                expected: "key=value",
                actual: content
                );

            Assert.False(result);
        }

        [Fact]
        public void Supports_multipart_formdata_content()
        {
            var content = new MultipartFormDataContent
            {
                new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key=value"))
            };

            var result = Test(
                expected: "key=value",
                actual: content
                );

            Assert.True(result);
        }

        [Fact]
        public void Matches_form_data_across_multipart_entries()
        {
            var content = new MultipartFormDataContent
            {
                new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key1=value1")),
                new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key2=value2"))
            };

            var result = Test(
                expected: "key1=value1&key2=value2",
                actual: content
                );

            Assert.True(result);
        }

        [Fact]
        public void Does_not_match_form_data_on_non_form_data_multipart_entries()
        {
            var content = new MultipartFormDataContent
            {
                new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key1=value1")),
                new FormUrlEncodedContent(HttpHelpers.ParseQueryString("key2=value2"))
            };

            content.First().Headers.ContentType = new MediaTypeHeaderValue("text/plain");

            var result = Test(
                expected: "key1=value1&key2=value2",
                actual: content
                );

            Assert.False(result);
        }

        private bool Test(string expected, HttpContent actual)
        {
            var sut = new FormDataMatcher(expected);

            return sut.Matches(new HttpRequestMessage(HttpMethod.Get,
                "http://tempuri.org/home") { Content = actual });
        }
    }
}


text:
If you wish to configure your app to use different Branch environments for different
builds, you can use custom build configurations in Xcode and build types or
product flavors with Gradle. For example, you may want to use the test environment
for debug builds and the live environment for release builds. Or you may choose
to use a different criterion. Everything described here is a matter of one-time project
setup. Afterward, whenever you do a build of a particular kind, it will automatically
use the correct Branch key.

All changes must be made in the native app projects. There is currently no support
for doing this from JavaScript.

## Prerequisites

[Account Settings]: https://dashboard.branch.io/account-settings/app

- Obtain your Branch live and test keys from the Branch Dashboard:

  See the [Account Settings] page in the Branch Dashboard to find your Branch live and test keys. Select "Live" or "Test" at the upper left to switch keys.
- Perform basic integration of the react-native-branch SDK in your app.

# Add both live and test keys to your project

First, you must define both the live and test keys within your Android and iOS projects. Once this is done, you'll specify when to use each key.

## Android

Add both keys to the `AndroidManifest.xml` within the `<application>` tag:

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.branch.sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application>
        <!-- Other existing entries -->

        <!-- Branch live and test keys -->
        <meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_xxxxxxx" />
        <meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_yyyyyyy" />
    </application>
</manifest>
```

## iOS

In the `Info.plist` for your project, make the `branch_key` a dictionary instead of a string, and add entries for keys "live" and "test" with string values. Add your keys from the Branch Dashboard as the values of the corresponding keys.

![Branch keys in Info.plist](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/branch-keys-info-plist.png)

# Option 1 (basic): Use test key for debug builds and live key for release builds

## Android

Simply add the following file to your Android project as `android/app/src/debug/AndroidManifest.xml`:

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.mypackage">
   <application>
       <meta-data android:name="io.branch.sdk.TestMode" android:value="true" /> <!-- Set to true to use Branch_Test_Key -->
   </application>
</manifest>
```

Replace `com.example.mypackage` with the package name from your main AndroidManifest.xml.

By default, the Branch SDK uses the live key. If you prefer, you can add a similar file with `android:value="false"` as `android/app/src/release/AndroidManifest.xml`, but this
is not necessary.

Gradle automatically merges the main manifest with the manifest for each build type and product flavor.

### iOS

In your `AppDelegate.m` or `AppDelegate.swift` source file,
add a conditional call to `[RNBranch useTestInstance]` (Obj-C) or `RNBranch.useTestInstance()` (Swift) before calling `initSession`.

_Obj-C_
```Objective-C
#ifdef DEBUG
    [RNBranch useTestInstance];
#endif

    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];
```
_Swift_
```Swift
#if DEBUG
    RNBranch.useTestInstance()
#endif

    RNBranch.initSession(launchOptions: launchOptions, isReferrable: true)
```

# Option 2 (advanced): Select live or test key based on user-defined criteria

If you want to use different criteria to determine when to use each key, you need to do a little more setup.
For example, you want to build different versions of the app that point to different versions of your
application API, such as production and staging, and you want to select the Branch key based on this

## Android

Define custom `productFlavors` for your app in the `android/app/build.gradle` file:

```gradle
android {
    ...
    defaultConfig { ... }
    buildTypes { ... }
    productFlavors {
        stage {
            applicationIdSuffix ".stage"
            versionNameSuffix "-stage"
        }
    }
}
```

Now add the following file as `android/app/src/<productFlavor>/AndroidManifest.xml` for each flavor
that uses the test key, e.g. `android/app/src/stage/AndroidManifest.xml`:

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.mypackage">
   <application>
       <meta-data android:name="io.branch.sdk.TestMode" android:value="true" /> <!-- Set to true to use Branch_Test_Key -->
   </application>
</manifest>
```

Replace `com.example.mypackage` with the package name from your main AndroidManifest.xml.

By default (for the main product flavor), the Branch SDK uses the live key.

You can also specify settings for combinations of build type and product flavor, e.g. in
`android/app/src/stageDebug/AndroidManifest.xml` or `android/app/src/stageRelease/AndroidManifest.xml`.

See the [Android documentation](https://developer.android.com/studio/build/build-variants.html) for more details on configuring Android build variants.

## iOS

React Native does not directly support custom build configurations automatically
when using `react-native link` to build your app. Supporting this in your React
Native app requires either manual modification of the Xcode projects installed
in `node_modules` or custom automation to update them properly each time you update
your NPM dependencies. This process is not documented here or currently
supported by this SDK.

If instead you are using the React, react-native-branch and Branch-SDK pods in
your Podfile to integrate the SDK, you can add custom build configurations to
your projects.

The following instructions show how to add a new configuration and scheme to your app that can be used to connect to the Branch test environment.

### Step 1: Add a new build configuration

By default, all Xcode projects include Debug and Release configurations. Define a new configuration called Test-Debug by copying the existing Debug configuration.

On the Info tab of the Project settings, click the + button under the list of Configurations. Select `Duplicate "Debug" Configuration`.

![Copy Debug Configuration](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/1-add-configuration.png)

Name the new configuration `Test-Debug`.

![Name New Configuration](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/2-rename-configuration.png)

### Step 2: Add a new build scheme to use the new configuration

From the Xcode task bar, select Product > Scheme > New Scheme....

![New Scheme](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/3-new-scheme.png)

Add `-Test` to the end of the scheme name. If your app is named `MyApp`, the default scheme name will be `MyApp`. Change it to `MyApp-Test`.

![Name New Scheme](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/4-name-new-scheme.png)

Notice that the scheme pulldown at the upper left of Xcode has changed to show your new scheme.

### Step 3: Configure the new scheme to use the new configuration

From the Xcode task bar, select Product > Scheme > Edit Scheme....

![Edit New Scheme](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/5-edit-scheme.png)

Check the box at the bottom of the dialog marked Shared to make this a shared scheme:

![Share New Scheme](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/6-share-scheme.png)

For each task listed in the sidebar of the dialog that currently uses the Debug configuration (Run, Test, Analyze), select the new `Test-Debug` configuration instead.

![Use New Config](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/7-use-new-config-in-scheme.png)

Once this is complete, click Close to dismiss the scheme dialog.

### Step 4: Add a custom preprocessor macro to the new configuration

Go to the Build Settings tab in the Project settings. Note that all settings can now be configured separately for the new `Test-Debug` configuration. It is currently configured the same as the `Debug` configuration.

Under Apple LLVM 8.1 - Preprocessing, find the Preprocessor Macros setting. Double-click the value for `Test-Debug`, which should be bold and show `DEBUG=1`. This brings up a dialog. Click the + button at the bottom of the dialog to add a new macro. Type in `USE_BRANCH_TEST_INSTANCE=1`.

![Add Preprocessor Macro](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/8-add-preprocessor-macro.png)

Click outside the dialog to exit. The value of the setting for `Test-Debug` should now read `DEBUG=1 USE_BRANCH_TEST_INSTANCE=1`.

![Modified Preprocessor Macro](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/9-modified-preprocessor-macro.png)

#### (Optional) Add a Swift compilation flag

If you are also using Swift in your app, add a similar setting under Swift-Compiler - Custom Flags. Under Active Compilation Conditions, add `USE_BRANCH_TEST_INSTANCE` to the setting for Test-Debug.

![Add Optional Swift Flag](https://raw.githubusercontent.com/BranchMetrics/react-native-branch-deep-linking-attribution/master/docs/assets/10-optional-add-swift-flag.png)

### Step 5: Conditional compilation in code

In your AppDelegate, before calling initSession, add a conditional call to useTestInstance using the compiler flag you've specified.

_Objective-C_
```Objective-C
#ifdef USE_BRANCH_TEST_INSTANCE
    [RNBranch useTestInstance];
#endif

    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];
```

_Swift_
```Swift
#if USE_BRANCH_TEST_INSTANCE
    RNBranch.useTestInstance()
#endif

    RNBranch.initSession(launchOptions: launchOptions, isReferrable: true)
```

### Step 6: Repeat for Release configuration

If you also want to use the same compilation option for release builds (i.e., make release builds that use the Branch test instance), repeat Steps 1, 3 and 4 for the Release configuration:

- Copy the existing `Release` configuration and name it `Test-Release`.
- Use Project > Scheme > Edit Scheme... and assign `Test-Release` to tasks that currently use `Release`: Profile and Archive.
- Add `USE_BRANCH_TEST_INSTANCE` to the compilation flags for Test-Release as well as Test-Debug. **Note:** Do not set the `DEBUG` option in the Test-Release configuration.

### Step 7: Update Podfile

Add your new configurations to your Podfile:

```Ruby
platform :ios, "8.0"

pod "React", path: "../node_modules/react-native"
pod "react-native-branch", path: "../node_modules/react-native-branch"
pod "Branch-SDK", path: "../node_modules/react-native-branch/ios"

target "ExampleProject"
target "ExampleProjectTests"

# Add this line
project "ExampleProject", "Test-Debug" => :debug, "Test-Release" => :release
```

And now run `pod install` after modifying the Podfile. This ensures that when you use Test-Debug,
all pods will be built in debug mode. The default is `:release`, so it's not necessary to specify
the Test-Release configuration, but adding it may make things clearer.

### Step 8: Try it out

Now whenever you use the new scheme for any task, including debugging and archiving, the Branch
test instance will be used. If you use the original scheme, the Branch live instance will be used.

The scheme can also be passed to xcodebuild using the -scheme argument when you build or test, e.g.
`xcodebuild -scheme MyApp-Test`. This is also true for other build tools like Fastlane's `gym` and `scan`
actions.

The `webview_example_native_ios` and `testbed_example_native_ios` examples in this repo are both set up exactly as described here, for reference.


text:
module StashEngine
  class CounterLogger

    # this logs the following items in TSV format, we may need to encode tabs and/or pipes (for metadata separators) in some cases
    # see below for what we're logging and in what order

    def self.general_hit(request:, resource: nil, file: nil)
      # request and resource are required for all and identifier, version and much info can be obtained from resource
      filename = nil
      size = nil
      if file
        filename = file.upload_file_name
        size = file.upload_file_size
        resource = file.resource
      end
      log_line(request: request, resource: resource, filename: filename, size: size)
    end

    def self.version_download_hit(request:, resource:)
      log_line(request: request, resource: resource, size: resource.size)
    end

    #
    # these are helper methods
    #

    def self.log_line(request:, resource:, filename: nil, size: nil)
      line = log_array(request: request, resource: resource, filename: filename, size: size)
      StashEngine.counter_log(line)
    end

    # rubocop:disable Metrics/MethodLength
    def self.log_array(request:, resource:, filename:, size:)
      [
        request.remote_ip, # user's IP Address
        nil, # we don't track a session cookie (that expires when a user closes the browser as indicated online as a definition of a session cookie)
        request.session_options[:id], # Session ID (this is a user's session id that references a cookie)
        request.session['user_id'], # this is a user's id number from our database (if they happen to be logged in, rarely the case)
        request.original_url, # the URL the user is requesting
        resource.identifier.to_s, # the identifier for the dataset
        filename, # the filename they requested for download if any
        size, # the size of the download (for a file, if any)
        request.user_agent # the agent sent by the client
      ].concat(log_metadata_array(resource: resource))
    end
    # rubocop:enable Metrics/MethodLength

    # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
    def self.log_metadata_array(resource:)
      [
        resource.title,
        resource.try(:publisher).try(:publisher),
        resource.tenant.publisher_id, # - publisher id, we're using grid ids
        resource.authors.map { |a| a.author_standard_name.gsub('|', '%7c') }.join('|'), # - creators, escape any pipes in author names
        resource.publication_date,
        resource.try(:stash_version).try(:version),
        '', # - other id
        resource.try(:identifier).try(:target), # The landing page url with correct domain and all
        resource.notional_publication_year
      ]
    end
    # rubocop:enable Metrics/MethodLength, Metrics/AbcSize

  end
end


text:
ColouriseElements = new Mongo.Collection('colouriseelements');
ColourisePalette = new Mongo.Collection('colourisepalette');

Meteor.publish('colouriseelements', function () {
	return ColouriseElements.find({});
});

Meteor.publish('colourisepalette', function () {
	return ColourisePalette.find({});
});

Meteor.methods({
	insertCE: function (target, targetFgColour, targetBgColour) {
		ColouriseElements.insert({
			nodeSelector: target.selector,
			nodeEnabled: true,
			fgColour: targetFgColour ? targetFgColour : '',
			bgColour: targetBgColour ? targetBgColour : ''
		});
	},
	updateCE: function (target, targetFgColour, targetBgColour) {
		ColouriseElements.update({nodeSelector: target.selector}, {$set: {
			nodeEnabled: true,
			fgColour: targetFgColour ? targetFgColour : '',
			bgColour: targetBgColour ? targetBgColour : ''
		}}, {upsert: true});
	},
	resetCE: function () {
		ColouriseElements.remove({});
		return true;
	},
	insertColour: function (newColour) {
		if (typeof newColour == 'array') {
			_.each(newColour, function (cc) {
				ColourisePalette.update({colour: cc}, {$set: {colour: cc}}, {upsert: true});
			});
		} else {
			ColourisePalette.update({colour: newColour}, {$set: {colour: newColour}}, {upsert: true});
		}
	},
	resetColours: function (newColour) {
		ColourisePalette.remove({});
	}
});


text:
import View from 'brindille-view';
import template from './componentTest.html';
import defaults from 'defaults';

export default class extends View {
  constructor(model) {
    super({
      template: template,
      model: defaults(model, {
        label: 'test',
        url: 'http://google.com'
      })
    });
  }
};


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom'

import AppsView from "./containers/AppsView";
import SentenceSuggester from './containers/SentenceSuggester.js';
import KeywordExtractor from './containers/KeywordExtractor.js';
import SentimentAnalyzer from './containers/SentimentAnalyzer.js';
import SimilarityChecker from './containers/SimilarityChecker.js';
import NamedEntityRecognizer from './containers/NamedEntityRecognizer.js';
import TextSummarizer from './containers/TextSummarizer.js';
import ContentEnricher from './containers/ContentEnricher.js';

import Layout from "./components/Layout";
import NavigationBar from "./components/NavigationBar";
import Footer from "./components/Footer";

import './index.css';
import './bootstrap.css';
import 'font-awesome/css/font-awesome.css';

ReactDOM.render((
        <Router>
            <Layout>
                <NavigationBar />
                <Route exact
                       name="appsView"
                       path="/"
                       component={AppsView}/>
                <Route name="sentenceSuggester"
                       path="/sentence-suggester"
                       component={SentenceSuggester}/>
                <Route name="sentimentAnalyzer"
                       path="/sentiment-analyzer"
                       component={SentimentAnalyzer}/>
                <Route name="keywordsExtractor"
                       path="/keywords-extractor"
                       component={KeywordExtractor}/>
                <Route name="similarityChecker"
                       path="/similarity-checker"
                       component={SimilarityChecker}/>
                <Route name="NamedEntityRecognizer"
                       path="/named-entity-recognizer"
                       component={NamedEntityRecognizer}/>
                <Route name="TextSummarizer"
                       path="/text-summarizer"
                       component={TextSummarizer}/>
                <Route name="ContentEnricher"
                       path="/content-enricher"
                       component={ContentEnricher}/>
                <Footer />
            </Layout>
        </Router>
    ),
    document.getElementById('root')
);


text:
var app = require('./app');
var config = require('x-config');

app.init(config, function(){
    app.listen();
});


text:
import os
import sys
import argparse
import subprocess
import tempfile

class TextutilConverter(object):
	def convert(self, src, dst):
		subprocess.check_call(['textutil', '-convert', 'html', '-output', dst, src])

class UnrtfConverter(object):
	def convert(self, src, dst):
		subprocess.check_call(['unrtf', '--html', src],
			stdout=open(dst, 'w'), stderr=open(os.devnull, 'w'))

# Check if path exists
def which(program):
	for d in os.environ['PATH'].split(os.pathsep):
		f = os.path.join(d, program)
		if os.access(f, os.X_OK):
			return f
	return None

# Return o
def converter():
	if which('textutil'):
		return TextutilConverter()
	elif which('unrtf'):
		return UnrtfConverter()
	else:
		raise Exception("No converter available")

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description="Sync OS X Stickies with HTML files")
	parser.add_argument('stickies', help="stickies database to parse")
	parser.add_argument('outDir', help="directory for HTML files")
	parser.add_argument('-c', '--cache', dest='cache', help="directory for intermediaries")
	args = parser.parse_args()

	# Clean up cache
	cacheDir = args.cache or tempfile.mkdtemp()
	if not os.path.exists(cacheDir):
		os.makedirs(cacheDir)
	for f in os.listdir(cacheDir):
		os.remove(os.path.join(cacheDir, f))

	# Run pystickies
	pystickies = os.path.join(os.path.dirname(__file__), 'pystickies.py')
	subprocess.check_call([pystickies, '--rtf', cacheDir, args.stickies])

	# Sync it up
	if not os.path.exists(args.outDir):
		os.makedirs(args.outDir)
	unwanted = set(os.listdir(args.outDir))

	cvt = converter()
	for srcName in os.listdir(cacheDir):
		name, ext = os.path.splitext(srcName)
		if ext != ".rtf":
			continue
		dstName = name + ".html"

		src = os.path.join(cacheDir, srcName)
		dst = os.path.join(args.outDir, dstName)
		cvt.convert(src, dst)
		unwanted.discard(dstName)
	for f in unwanted:
		os.remove(os.path.join(args.outDir, f))


text:
package tcp

import (
	"context"
	"io"
	"net"

	"github.com/plgd-dev/go-coap/v2/message"
	"github.com/plgd-dev/go-coap/v2/mux"
	"github.com/plgd-dev/go-coap/v2/tcp/message/pool"
)

type ClientTCP struct {
	cc *ClientConn
}

func NewClientTCP(cc *ClientConn) *ClientTCP {
	return &ClientTCP{
		cc: cc,
	}
}

func (c *ClientTCP) Ping(ctx context.Context) error {
	return c.cc.Ping(ctx)
}

func (c *ClientTCP) Delete(ctx context.Context, path string, opts ...message.Option) (*message.Message, error) {
	resp, err := c.cc.Delete(ctx, path, opts...)
	if err != nil {
		return nil, err
	}
	defer pool.ReleaseMessage(resp)
	return pool.ConvertTo(resp)
}

func (c *ClientTCP) Put(ctx context.Context, path string, contentFormat message.MediaType, payload io.ReadSeeker, opts ...message.Option) (*message.Message, error) {
	resp, err := c.cc.Put(ctx, path, contentFormat, payload, opts...)
	if err != nil {
		return nil, err
	}
	defer pool.ReleaseMessage(resp)
	return pool.ConvertTo(resp)
}

func (c *ClientTCP) Post(ctx context.Context, path string, contentFormat message.MediaType, payload io.ReadSeeker, opts ...message.Option) (*message.Message, error) {
	resp, err := c.cc.Post(ctx, path, contentFormat, payload, opts...)
	if err != nil {
		return nil, err
	}
	defer pool.ReleaseMessage(resp)
	return pool.ConvertTo(resp)
}

func (c *ClientTCP) Get(ctx context.Context, path string, opts ...message.Option) (*message.Message, error) {
	resp, err := c.cc.Get(ctx, path, opts...)
	if err != nil {
		return nil, err
	}
	defer pool.ReleaseMessage(resp)
	return pool.ConvertTo(resp)
}

func (c *ClientTCP) Close() error {
	return c.cc.Close()
}

func (c *ClientTCP) RemoteAddr() net.Addr {
	return c.cc.RemoteAddr()
}

func (c *ClientTCP) Context() context.Context {
	return c.cc.Context()
}

func (c *ClientTCP) SetContextValue(key interface{}, val interface{}) {
	c.cc.Session().SetContextValue(key, val)
}

func (c *ClientTCP) WriteMessage(req *message.Message) error {
	r, err := pool.ConvertFrom(req)
	if err != nil {
		return err
	}
	defer pool.ReleaseMessage(r)
	return c.cc.WriteMessage(r)
}

func (c *ClientTCP) Do(req *message.Message) (*message.Message, error) {
	r, err := pool.ConvertFrom(req)
	if err != nil {
		return nil, err
	}
	defer pool.ReleaseMessage(r)
	resp, err := c.cc.Do(r)
	if err != nil {
		return nil, err
	}
	defer pool.ReleaseMessage(resp)
	return pool.ConvertTo(resp)
}

func createClientConnObserveHandler(observeFunc func(notification *message.Message)) func(n *pool.Message) {
	return func(n *pool.Message) {
		muxn, err := pool.ConvertTo(n)
		if err != nil {
			return
		}
		observeFunc(muxn)
	}
}

func (c *ClientTCP) Observe(ctx context.Context, path string, observeFunc func(notification *message.Message), opts ...message.Option) (mux.Observation, error) {
	return c.cc.Observe(ctx, path, createClientConnObserveHandler(observeFunc), opts...)
}

// Sequence acquires sequence number.
func (c *ClientTCP) Sequence() uint64 {
	return c.cc.Sequence()
}

// ClientConn get's underlaying client connection.
func (c *ClientTCP) ClientConn() interface{} {
	return c.cc
}


text:
@implementation BKTradePair

@dynamic currencyVolume;
@dynamic identifier;
@dynamic lastRate;
@dynamic marketVolume;
@dynamic maxRate;
@dynamic minRate;
@dynamic primaryCurrencyId;
@dynamic secondaryCurrencyId;

@end


text:
layout: doc
title: Updating RDF Lists with SPARQL
---

Andy Seaborne

Migrated from the original (2011):
[Updating RDF Lists with SPARQL](http://seaborne.blogspot.com/2011/03/updating-rdf-lists-with-sparql.html).

Something the [SPARQL 1.1 Working Group](http://www.w3.org/2009/sparql/wiki/Main_Page)
discussed was updates to RDF lists.

RDF lists are hard to deal with because they are not [first class
objects](http://en.wikipedia.org/wiki/First-class_object) in the RDF data
model. Instead they are "encoded" in triples. The encoding using a
[cons cell](http://en.wikipedia.org/wiki/Cons)-like structure whereby each
element of the list is a blank node (not necessary a blank node but it nearly
always is). It's a one-way link list.

RDF lists are correctly called "[RDF collections](http://www.w3.org/TR/rdf-primer/#collections)"
but as it's the list-nature (elements in order) that matters, I'll call them lists in this note.

Turtle and SPARQL has syntax for lists, but it's only surface syntax, and there
are really triples in the RDF graph:

    PREFIX : <http://example/>
    :x :p (1 2 3) .

is the RDF:

    :x    :p         _:b0 .
    _:b0  rdf:first  1 .
    _:b0  rdf:rest   _:b1 .
    _:b1  rdf:first  2 .
    _:b1  rdf:rest   _:b2 .
    _:b2  rdf:first  3 .
    _:b2  rdf:rest   rdf:nil

RDF toolkits help by presenting lists as progamming language lists.  This also
helps in keeping the lists well formed.  In all those triples, there is one
`rdf:rest` and one `rdf:first` per list element - but it's legal RDF to have
several uses of the properties, or none, on one subject.

As an addition quirk, the empty list isn't any RDF triples, so looking for lists isn't just looking for <tt>rdf:rest</tt> properties.

    PREFIX : <http://example/>
    :x :p () .

is the RDF:

    :x :p rdf:nil .

### Lists, Property Paths and Update

[SPARQL 1.1 Query](http://www.w3.org/TR/sparql11-query/) adds
[property paths](http://www.w3.org/TR/sparql11-query/#propertypaths), which make working
with lists a bit easier, but it's not perfect.  List elements do not necessarily
come out in order.

    { :list rdf:rest*/rdf:first ?element }

But what about [SPARQL 1.1 Update](http://www.w3.org/TR/sparql11-update/)?
How can we work with RDF lists?  Here are some scripts for list operations.  By
using property paths they work on arbitrary length lists.

* [Add an element to the start of a list](#add-first)
* [Add an element to the end of a list](#add-last)
* [Delete the element at the start of a list](#del-first)
* [Delete an element to the end of a list](#del-last)
* [Delete the whole list](#del-all-1) (version 1 - common case)
* [Delete the whole list](#del-all-2) (version 2 - more general case)

All the scripts are self-contained - they include tests data.

They are examples - they aren't necessarily fully general, for example, if lists
are badly formed or the property `:p` is also used to relate the subject to
things that aren't lists.  The last example shows a way to address that by
finding and marking relavent points in the graph, doing some work and going back
and tidying up.  The graph updated is also being used as a scratch pad.

## Add an element to the start of a list

    PREFIX :    <http://example/>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    INSERT DATA {
      :x0 :p () .
      :x1 :p (1) .
      :x2 :p (1 2) .
      :x3 :p (1 2 3) .
    } ;

    DELETE { ?x :p ?list }
    INSERT { ?x :p [ rdf:first 0 ;
                     rdf:rest ?list ]
    } WHERE {
      ?x :p ?list .
    }

This one is relatively easy. Find the list start <tt>?x :p ?list</tt>, which works whether the list is zero length or already has elements,  delete the old triple that connected to the start of the list, put in a new cons cell (the <tt>[...]</tt>) at the start, and link to it.

### Add an element to the end of a list

    PREFIX :    <http://example/>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    INSERT DATA {
      :x0 :p () .
      :x1 :p (1) .
      :x2 :p (1 2) .
      :x3 :p (1 2 3) .
    } ;

    # The order here is important.
    # Must do list >= 1 first.

    # List of length >= 1
    DELETE { ?elt rdf:rest rdf:nil }
    INSERT { ?elt rdf:rest [ rdf:first 98 ; rdf:rest rdf:nil ] }
    WHERE
    {
      ?x :p ?list .
      # List of length >= 1
      ?list rdf:rest* ?elt .
      ?elt rdf:rest rdf:nil .
      # ?elt is last cons cell
    } ;

    # List of length = 0
    DELETE { ?x :p rdf:nil . }
    INSERT { ?x :p [ rdf:first 99 ; rdf:rest rdf:nil ] }
    WHERE
    {
       ?x :p rdf:nil .
    }

This is a bit harder - there are two cases, lists of length 0 and lists of
length one or more. The element before the insertion point needs changing and
that can be a cons cell (list length >= 1) or the empty list (the triple
pointing to it).

Do the lists of length one or more first, otherwise the adding to a list of
length zero will be caught again by the adding to a list of length one.

For a list of length 1 or more: find the last element.  The <tt>WHERE</tt> finds <tt>?elt</tt> by finding all elements of the list <tt>rdf:rest+</tt>, and checking it's the last element by looking for <tt>?elt rdf:rest rdf:nil</tt>.

Then delete the <tt>rdf:rest</tt>, and insert the new cons cell
<tt>[ rdf:first 98 ; rdf:rest rdf:nil ]</tt>.

For a list of length 0, the style is the same but the finding the triple to
delete-insert to attach the cons cell is different.

### Delete the element at the start of a list

    PREFIX :      <http://example/>
    PREFIX rdf:   <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    INSERT DATA {
      :x3 :p (1 2 3) .
      :x2 :p (1 2) .
      :x1 :p (1) .
      :x0 :p () .
    } ;

    DELETE {
       ?x :p ?list .
       ?list rdf:first ?first ;
             rdf:rest  ?rest }
    INSERT { ?x :p ?rest }
    WHERE
    {
      ?x :p ?list .
      ?list rdf:first ?first ;
            rdf:rest ?rest .
    }

This can be done in one step - we are not interested in lists of length 0
because they have no element to delete.  So find the pattern at the start of the
list, delete it (note the <tt>WHERE</tt> pattern and <tt>DELETE</tt> template
are the same), and insert the new triple that links the list directly to the
previous <tt>rdf:rest</tt>.

### Delete the element at the end of a list

    PREFIX :     <http://example/>
    PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    INSERT DATA {
      :x3 :p (1 2 3) .
      :x2 :p (1 2) .
      :x1 :p (1) .
      :x0 :p () .
    } ;

    # List of length 1
    # Do before other lists.

    DELETE { ?x :p ?elt .
             ?elt  rdf:first ?v .
             ?elt  rdf:rest  rdf:nil .
           }
    INSERT { ?x :p rdf:nil . }
    WHERE
    {
      ?x :p ?elt .
      ?elt rdf:first ?v ;
           rdf:rest rdf:nil .
    } ;

    # List of length >= 2
    DELETE { ?elt1 rdf:rest ?elt .
             ?elt  rdf:first ?v .
             ?elt  rdf:rest  rdf:nil .
           }
    INSERT { ?elt1 rdf:rest rdf:nil }
    WHERE
    {
      ?x :p ?list .
      ?list rdf:rest* ?elt1 .

      # Second to end.
      ?elt1 rdf:rest ?elt .
      # End.
      ?elt rdf:first ?v ;
       rdf:rest rdf:nil .
}

The cases to consider are lists of exactly one and lists of two or more
elements.  It's the treatment of the element before the element we're deleteing
that is different.

The style is the same though - find the place before the deleting, and the
delete that cons cell.

For the list of length 2 or more, <tt>rdf:rest*</tt> is used which, is all
elements including the <tt>?list</tt> case of zero steps - then the structure
beyond that is tested for being the end.  There are 2 <tt>rdf:rest</tt> uses in
the test for the end, hence list of length 2 or more.

### Delete the whole list (common case)

    PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX :     <http://example/>

    INSERT DATA {
        :x0 :p () .
        :x0 :q "abc" .

        :x1 :p (1) .
        :x1 :q "def" .

        :x2 :p (1 2) .
        :x2 :q "ghi" .
    } ;

    # Delete the cons cells.
    DELETE
        { ?z rdf:first ?head ; rdf:rest ?tail . }
    WHERE {
          [] :p ?list .
          ?list rdf:rest* ?z .
          ?z rdf:first ?head ;
             rdf:rest ?tail .
          } ;

    # Delete the triples that connect the lists.
    DELETE WHERE { ?x :p ?z . }

This version is not fully general because it assume that <tt>:p</tt> is a link
to the list and not also to any other RDF terms (non-lists) which we would want
to keep.

The first <tt>DELETE</tt> finds and removes all cons cells.  The second
<tt>DELETE</tt> removes the triple with <tt>:p</tt> connecting the list to the
subject.

### Delete the whole list (general case)

    PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX :     <http://example/>

    INSERT DATA {
        :x0 :p () .
        :x0 :p "String 0" .
        :x0 :p [] .

        :x1 :p (1) .
        :x1 :p "String 1" .
        :x1 :p [] .

        :x2 :p (1 2) .
        :x2 :p "String 2" .
        :x2 :p [] .

        # A list not connected.
        (1 2) .

        # Not legal RDF.
        # () .

    } ;

    INSERT { ?list :deleteMe true . }
    WHERE {
       ?x :p ?list .
       FILTER (?list = rdf:nil || EXISTS{?list rdf:rest ?z} )
    } ;

    # Delete the cons cells.
    DELETE
        { ?z rdf:first ?head ; rdf:rest ?tail . }
    WHERE {
          [] :p ?list .
          ?list rdf:rest* ?z .
          ?z rdf:first ?head ;
             rdf:rest ?tail .
          } ;

    # Delete the marked nodes
    DELETE
    WHERE { ?x :p ?z .
            ?z :deleteMe true .
    } ;

    ## ------
    ## Unconnected lists.

    DELETE
        { ?z rdf:first ?head ; rdf:rest ?tail . }
    WHERE {
          ?list rdf:rest ?z2 .
          FILTER NOT EXISTS { ?s ?p ?list }
          ?list rdf:rest* ?z .
          ?z rdf:first ?head ;
             rdf:rest ?tail .
          }

Deep breath.

This one is quite long.

The first step is to find and mark all the triples from a subject to a list via
<tt>:p</tt>. We will need to delete at the end of the process but the property
might also be used for non-lists and after the middle <tt>DELETE</tt> step all
evidence of the lists is lost. The test:

    FILTER (?list = rdf:nil || EXISTS{?list rdf:rest ?z} )

catches both zero length lists and lists with elements.

Second step: delete all list elements, any subjects with properties <tt>rdf:first</tt> and <tt>rdf:rest</tt>.

Third step: remove the connecting triples and the markers.

Finally, we delete any lists where the start isn't connected to anything, which is
the

    FILTER NOT EXISTS { ?s ?p ?list }

test.

### License and Copyright

This page and the SPARQL 1.1 Update scripts are (c)
Epimorphics Ltd and licensed under a
Creative Commons Attribution 3.0
License.


text:
require 'test_helper'

module JGrowlRails
  class NotificationTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
import sys
import time
from pyhive import hive
from TCLIService.ttypes import TOperationState

import simplejson as json

HIVESTORE='localhost'

AVROLOADPATH = '../../metadata-events/mxe-schemas/src/renamed/avro/com/linkedin/mxe/MetadataChangeEvent.avsc'
KAFKATOPIC = 'MetadataChangeEvent_v4'
BOOTSTRAP = 'localhost:9092'
SCHEMAREGISTRY = 'http://localhost:8081'

def hive_query(query):
    """
    Execute the query to the HiveStore.
    """
    cursor = hive.connect(HIVESTORE).cursor()
    cursor.execute(query, async_=True)
    status = cursor.poll().operationState
    while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
        logs = cursor.fetch_logs()
        for message in logs:
            sys.stdout.write(message)
        status = cursor.poll().operationState
    results = cursor.fetchall()
    return results

def build_hive_dataset_mce(dataset_name, schema, metadata):
    """
    Create the MetadataChangeEvent via dataset_name and schema.
    """
    actor, type, created_time, upstreams_dataset, sys_time = "urn:li:corpuser:" + metadata[2][7:], str(metadata[-1][11:-1]), int(metadata[3][12:]), metadata[-28][10:], int(time.time())
    owners = {"owners":[{"owner":actor,"type":"DATAOWNER"}],"lastModified":{"time":sys_time,"actor":actor}}
    upstreams = {"upstreams":[{"auditStamp":{"time":sys_time,"actor":actor},"dataset":"urn:li:dataset:(urn:li:dataPlatform:hive," + upstreams_dataset + ",PROD)","type":"TRANSFORMED"}]}
    elements = {"elements":[{"url":HIVESTORE,"description":"sample doc to describe upstreams","createStamp":{"time":sys_time,"actor":actor}}]}
    schema_name = {"schemaName":dataset_name,"platform":"urn:li:dataPlatform:hive","version":0,"created":{"time":created_time,"actor":actor},
                  "lastModified":{"time":sys_time,"actor":actor},"hash":"","platformSchema":{"com.linkedin.pegasus2avro.schema.OtherSchema": {"rawSchema": schema}},
                   "fields":[{"fieldPath":"","description":{"string":""},"nativeDataType":"string","type":{"type":{"com.linkedin.pegasus2avro.schema.StringType":{}}}}]}

    mce = {"auditHeader": None,
           "proposedSnapshot":{"com.linkedin.pegasus2avro.metadata.snapshot.DatasetSnapshot":
                               {"urn": "urn:li:dataset:(urn:li:dataPlatform:hive,"+ dataset_name +",PROD)"
                               ,"aspects": [
                                   {"com.linkedin.pegasus2avro.common.Ownership": owners}
                                 , {"com.linkedin.pegasus2avro.dataset.UpstreamLineage": upstreams}
                                 , {"com.linkedin.pegasus2avro.common.InstitutionalMemory": elements}
                                 , {"com.linkedin.pegasus2avro.schema.SchemaMetadata": schema_name}
                                 ]}},
           "proposedDelta": None}

    print(json.dumps(mce))

databases = hive_query('show databases')
for database in databases:
    tables = hive_query('show tables in ' + database[0])
    for table in tables:
        dataset_name = database[0] + '.' + table[0]
        description = hive_query('describe extended ' + dataset_name)
        build_hive_dataset_mce(dataset_name, str(description[:-1][:-1]), description[-1][1].split(','))

sys.exit(0)


text:
package de.da_sense.moses.client.util;

import java.io.File;

import android.content.Context;
import android.content.ContextWrapper;

/**
 * Class to manage the file and folder locations.
 */
public class FileLocationUtil {
	/** the filename for the user study notification database */
	private static final String USERSTUDY_NOTIFICATION_DB_FILENAME = "userstudyNotifications";
	/** the filename for the installed apps */
	private static final String APPDATABASE_FILENAME = "installedApps";
	/** the filename for the local history of the participated user studies */
	private static final String HISTORYDATABASE_FILENAME = "localHistory";

	/**
	 * Create a folder for the installed app database.
	 * @param context the context
	 * @return the folder
	 */
	public static File getApkDownloadFolder(Context privateContext) {
		File dir = new ContextWrapper(privateContext).getExternalFilesDir("apk");
		return dir;
	}

	/**
	 * Create a folder for the settings.
	 * @param context the context
	 * @return the folder
	 */
	private static File getSettingsFolder(Context privateContext) {
		File dir = new ContextWrapper(privateContext).getExternalFilesDir(null);
		return dir;
	}

	/**
	 * Create a file for the installed app database.
	 * @param context the context
	 * @return the database file
	 */
	public static File getAppDatabaseFile(Context context) {
		return new File(getSettingsFolder(context), FileLocationUtil.APPDATABASE_FILENAME);
	}

	/**
	 * Create a file for the history database.
	 * @param context the context
	 * @return the database file
	 */
	public static File getHistoryDatabaseFile(Context context) {
		return new File(getSettingsFolder(context), FileLocationUtil.HISTORYDATABASE_FILENAME);
	}

	/**
	 * Create a file for the user study notification database.
	 * @param context the context
	 * @return the database file
	 */
	public static File getNotificationDatabaseFile(Context context) {
		return new File(getSettingsFolder(context), USERSTUDY_NOTIFICATION_DB_FILENAME);
	}

}


text:
# The ServiceStack Server Web Framework

This project holds the core implementation that makes up the ServiceStack Web Framework.


text:
package de.fhbielefeld.newsboard.rest;

import com.google.common.collect.ImmutableList;
import de.fhbielefeld.newsboard.model.access.Access;
import de.fhbielefeld.newsboard.model.access.AccessDao;
import de.fhbielefeld.newsboard.model.document.*;
import de.fhbielefeld.newsboard.model.module.ExternalModule;
import de.fhbielefeld.newsboard.model.module.ExternalModuleDao;
import de.fhbielefeld.newsboard.model.module.ModuleId;
import de.fhbielefeld.newsboard.xml.ClassificationParsedHandler;
import de.fhbielefeld.newsboard.xml.XmlDocumentReader;
import de.fhbielefeld.newsboard.xml.XmlDocumentWriter;
import de.fhbielefeld.newsboard.xml.XmlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.*;

/**
 * Controller for REST-Api.
 *
 * @author Lukas Taake
 */
@RestController
@RequestMapping("/rest")
public class RestApiController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestApiController.class);

    private final XmlDocumentReader xmlReader;
    private final XmlDocumentWriter xmlWriter;
    private final RawDocumentProcessor documentProcessor;
    private final DocumentDao documentDao;
    private final AccessDao accessDao;
    private final ExternalModuleDao moduleDao;
    private final ClassificationDao classificationDao;

    @Autowired
    public RestApiController(XmlDocumentReader xmlReader, XmlDocumentWriter xmlWriter, RawDocumentProcessor documentProcessor,
                             DocumentDao documentDao, AccessDao accessDao, ExternalModuleDao moduleDao, ClassificationDao classificationDao) {
        this.xmlReader = xmlReader;
        this.xmlWriter = xmlWriter;
        this.documentProcessor = documentProcessor;
        this.documentDao = documentDao;
        this.accessDao = accessDao;
        this.moduleDao = moduleDao;
        this.classificationDao = classificationDao;
    }

    /**
     * Print out a list of all documents, containing only their metadata.
     * Intended for: any kind of user interface (like a single-page-app, or a mobile app).
     */
    @RequestMapping(path = "/document", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
    public String listDocuments(HttpServletResponse response) {
        List<Document> documents = documentDao.findLatest(0xFFFF);
        try {
            return xmlWriter.writeStubList(documents);
        } catch (XMLStreamException e) {
            return handleServerError(response, e);
        }
    }

    /**
     * Put one or more new documents into the newsboard.
     * Intended for: external crawler modules
     */
    @RequestMapping(path = "/document", method = RequestMethod.PUT)
    public String putDocument(HttpServletRequest request, HttpServletResponse response, @RequestBody String body) {
        Optional<ExternalModule> authenticationResult = checkAuthentication(request);
        if (!authenticationResult.isPresent()) {
            return handleAuthenticationError(response);
        }
        ExternalModule crawler = authenticationResult.get();
        try {
            xmlReader.readDocument(new StringReader(body), (title, author, source, creationTime, crawlTime, rawText) -> {
                RawDocument rawDocument = new RawDocument(title, author, source, creationTime, crawlTime, crawler.getId(), rawText);
                Document document = documentProcessor.processDocument(rawDocument);
                documentDao.create(document);
            });
        } catch (XmlException e) {
            return handleClientError(response, e);
        }
        return "OK";
    }

    /**
     * Print out a single document in it's complete structure including sentences and their classifications.
     * Intended for: external UI modules
     */
    @RequestMapping(value = "/document/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
    public String getDocument(HttpServletResponse response, @PathVariable String id) {
        int docId = Integer.parseInt(id);
        Document doc = documentDao.get(new DocumentId(docId));
        List<DocumentClassification> classifications = classificationDao.findForDocument(doc);
        try {
            return xmlWriter.writeDocument(doc, classifications);
        } catch (XMLStreamException e) {
            return handleServerError(response, e);
        }
    }

    /**
     * Print out a list of all documents that aren't classified by a specified external module.
     * Intended for: external classifiers modules
     */
    @RequestMapping(path = "/unclassified/{moduleId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
    public String getUnclassified(HttpServletResponse response, @PathVariable String moduleId) {
        List<Document> documents = documentDao.findUnclassifiedForModule(new ModuleId(moduleId));
        Map<Document, List<DocumentClassification>> classificationMap = new HashMap<>();
        for (Document document : documents) {
            classificationMap.put(document, classificationDao.findForDocument(document));
        }
        try {
            return xmlWriter.writeDocumentList(classificationMap);
        } catch (XMLStreamException e) {
            return handleServerError(response, e);
        }
    }

    /**
     * Put one or more new classifications for existing documents into the newsboard.
     * Intended for: external classifier modules
     */
    @RequestMapping(path = "/classify", method = RequestMethod.PUT)
    public String classify(HttpServletRequest request, HttpServletResponse response, @RequestBody String body) {
        Optional<ExternalModule> authenticationResult = checkAuthentication(request);
        if (!authenticationResult.isPresent()) {
            return handleAuthenticationError(response);
        }
        ExternalModule classifier = authenticationResult.get();
        ImmutableList.Builder<ClassificationValue> values = ImmutableList.builder();
        StringReader in = new StringReader(body);
        try {
            xmlReader.readClassifications(in,
                    new ClassificationParsedHandler() {
                        @Override
                        public void onValueParsed(double value, OptionalDouble confidence) {
                            if (confidence.isPresent()) {
                                values.add(ClassificationValue.of(value, confidence.getAsDouble()));
                            } else {
                                values.add(ClassificationValue.of(value));
                            }
                        }

                        @Override
                        public void onClassificationParsed(int documentId, String classifierId) {
                            if (!classifierId.equals(classifier.getId().raw())) {
                                handleClientError(response, new Exception("Authentication doesn't match supplied classifier name"));
                            }
                            Document document = documentDao.get(new DocumentId(documentId));
                            DocumentClassification classification = document.addClassification(new ModuleId(classifierId), values.build());
                            classificationDao.create(classification);
                        }
                    });
        } catch (Exception e) {
            return handleClientError(response, e);
        }
        LOGGER.info("Added new classification");
        return "OK";
    }

    private Optional<ExternalModule> checkAuthentication(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Basic")) {
            String base64Credentials = authorization.substring("Basic".length()).trim();
            String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
            String[] values = credentials.split(":", 2);
            ExternalModule module = moduleDao.get(new ModuleId(values[0]));
            if (module != null) {
                Access access = accessDao.get(module.getAccessId());
                if (access.isEnabled() && access.getPassphrase().equals(values[1])) {
                    return Optional.of(module);
                }
            }
        }
        return Optional.empty();
    }

    private String handleClientError(HttpServletResponse response, Exception e) {
        LOGGER.warn("Client error: {}", e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "FAILED: " + e.getMessage();
    }

    private String handleServerError(HttpServletResponse response, XMLStreamException e) {
        LOGGER.warn("Server error occurred", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return "Internal Error: " + e.getMessage();
    }

    private String handleAuthenticationError(HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return "Authentication failed.";
    }
}