text:
package git4idea;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.util.text.StringUtil;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;

import java.util.Arrays;
import java.util.List;

import static git4idea.GitCucumberWorld.myNotificator;
import static git4idea.GitCucumberWorld.virtualCommits;
import static git4idea.test.GitExecutor.git;
import static git4idea.test.GitExecutor.touch;
import static git4idea.test.GitScenarios.checkout;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * @author Kirill Likhodedov
 */
public class GeneralStepdefs {

  @Given("^file (.+) '(.+)'$")
  public void file_untracked_txt(String fileName, String content) throws Throwable {
    touch(fileName, content);
  }

  @Given("^new committed file (.*) '(.*)'$")
  public void new_committed_file(String filename, String content) throws Throwable {
    touch(filename, content);
    git("add %s", filename);
    git("commit -m 'adding %s'", filename);
  }

  @Given("^commit (.+) on branch (.+)$")
  public void commit_on_branch(String hash, String branch, String commitDetails) throws Throwable {
    CommitDetails commit = CommitDetails.parse(hash, commitDetails);
    // we implicitly assume that we always are on master (maybe except some certain test cases which should handle it separately
    if (!branch.equals("master")) {
      checkout(branch);
    }
    commit.apply();
    if (!branch.equals("master")) {
      checkout("master");
    }
  }

  @Then("^(success|warning|error) notification is shown '(.+)'$")
  public void error_notification_is_shown(String notificationType, String title, String content) {
    NotificationType type = notificationType.equals("success") ? NotificationType.INFORMATION :
                            notificationType.equals("warning") ? NotificationType.WARNING :
                            notificationType.equals("error") ? NotificationType.ERROR : null;
    Notification actualNotification = lastNotification();
    assertNotNull("Notification should be shown", actualNotification);
    assertEquals("Notification type is incorrect in " + actualNotification, type, actualNotification.getType());
    assertEquals("Notification title is incorrect in" + actualNotification, title, actualNotification.getTitle());
    assertNotificationContent(content, actualNotification.getContent());
  }

  private static void assertNotificationContent(String expected, String actual) {
    expected = virtualCommits.replaceVirtualHashes(expected);
    assertEquals("Notification content is incorrect", StringUtil.convertLineSeparators(expected),
                 StringUtil.convertLineSeparators(adjustNotificationContent(actual)));
  }

  private static String adjustNotificationContent(String content) {
    return content.replaceAll("
", "\n")      // we don't want to type
 in features
                  .replaceAll("([^\n])?
", "$1\n
")         // surround
 with newlines
                  .replaceAll("
([^\n])?", "
\n$1");

  }

  private static Notification lastNotification() {
    return myNotificator.getLastNotification();
  }

  @And("^no notification is shown$")
  public void no_notification_is_shown() throws Throwable {
    assertNull("Notification should not be shown", lastNotification());
  }

  @Given("^new committed files (.+) with initial content$")
  public void new_committed_files_file_txt_a_txt_b_txt_with_initial_content(String listOfFiles) throws Throwable {
    List<String> files = splitByComma(listOfFiles);
    for (String file : files) {
      touch(file, "initial content");
    }
    git("add %s", StringUtil.join(files, " "));
    git("commit -m 'adding files with initial content'");
  }

  public static List<String> splitByComma(String listOfItems) {
    return Arrays.asList(listOfItems.split(", ?"));
  }

  @Given("^branch (.+)$")
  public void branch(String branchName) throws Throwable {
    git("branch " + branchName);
  }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Bagé</logradouro><bairro>Viamópolis</bairro><cidade>Viamão</cidade><uf>RS</uf><cep>94470230</cep></feed>

redpajama_set_name: RedPajamaGithub


text:
package org.jclouds.s3.functions;

import java.util.concurrent.ExecutionException;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;

import org.jclouds.logging.Logger;
import org.jclouds.s3.Bucket;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;

@Singleton
public class GetRegionForBucket implements Function<String, Optional<String>> {
   @Resource
   protected Logger logger = Logger.NULL;

   protected final LoadingCache<String, Optional<String>> bucketToRegion;

   @Inject
   public GetRegionForBucket(@Bucket LoadingCache<String, Optional<String>> bucketToRegion) {
      this.bucketToRegion = bucketToRegion;
   }

   @Override
   public Optional<String> apply(String bucket) {
      try {
         return bucketToRegion.get(bucket);
      } catch (ExecutionException e) {
         logger.debug("error looking up region for bucket %s: %s", bucket, e);
      } catch (UncheckedExecutionException e) {
         logger.debug("error looking up region for bucket %s: %s", bucket, e);
      } catch (InvalidCacheLoadException e) {
         logger.trace("bucket %s not found: %s", bucket, e);
      }
      return Optional.absent();
   }
}


text:
package javax.print.attribute.standard;

import javax.print.attribute.Attribute;
import javax.print.attribute.IntegerSyntax;
import javax.print.attribute.PrintJobAttribute;
import javax.print.attribute.PrintRequestAttribute;

public final class JobPriority extends IntegerSyntax implements PrintJobAttribute,
        PrintRequestAttribute {
    private static final long serialVersionUID = -4599900369040602769L;

    public JobPriority(int value) {
        super(value, 1, 100);
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof JobPriority)) {
            return false;
        }
        return super.equals(object);
    }

    public final Class<? extends Attribute> getCategory() {
        return JobPriority.class;
    }

    public final String getName() {
        return "job-priority";
    }
}


text:
require 'ext/boc'
#require 'ext/binding_of_caller'
require 'ara/simple_actor'

# Actor class
class Actor < SimpleActor
  def initialize #:nodoc:
    raise ActorInitializationError, "You can't initialize Actor directly, use Actors.actor_of" if self.class == ::Actor
    super
    @main = Queue.new
    @mutex = Mutex.new
  end

  # Send a synchronous message
  #
  #   myActor = Actors.actor_of(MyActor).start
  #   message = ...
  #   result = myActor << message
  #
  # All code after this call will be executed only when the actor has finished it's work
  def <<(message)
    if @thread.alive?
      @actorQueue << message
      @main.shift
    else
      raise DeadActor, "Actor is dead!"
    end
  end
  alias :sync_message :<<

  # Send an asynchronous message
  #
  #   myActor = Actors.actor_of(MyActor).start
  #   message = ...
  #   myActor < message
  #
  # The code after this call will be executed without waiting the actor. You must add a <tt>result</tt> method to get the actor' reponse.
  def <(message, response_method = nil)
     _actor = self
     if @thread.alive?
        @actorQueue << message

        BindingOfCaller.binding_of_caller do |bind|
           self_of_caller = eval("self", bind)
           Thread.new do
              _result = @main.shift
              begin
                 if block_given?
                    yield _result
                 elsif response_method != nil
                    self_of_caller.send( response_method.to_sym, _result )
                 elsif self_of_caller.respond_to? :actor_response_with_name
                    self_of_caller.send( :actor_response_with_name, _actor, _result )
                 else
                    self_of_caller.send( :actor_response, _result )
                 end
              rescue => e
                 Ara.fatal(e)
                 raise ActorResponseError, "Error while sending response : #{e}"
              end
           end
        end
     else
        raise DeadActor, "Actor is dead!"
     end
  end
  alias :async_message :<

  private
  # Method use by the actor to reply to his sender
  #
  #   class MyActor < Actor
  #     def receive(message)
  #       ...
  #       something = ...
  #       reply( something )
  #     end
  #   end
  def reply( r )
    @main << r
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Phonebook
{
    class Program
    {
        static void Main(string[] args)
        {
            bool endCommand = false;
            var contactList = new SortedDictionary<string, string>();

            while(endCommand == false)
            {
                var command = Console.ReadLine().Split(' ').ToList();

                if (command[0] == "END")
                    endCommand = true;

                else if (command[0] =="A")
                {
                    contactList[command[1]] = command[2];
                }
                else if (command[0] == "S")
                {
                    if (contactList.ContainsKey(command[1]))
                    {
                        var value = contactList[command[1]];
                        Console.WriteLine($"{command[1]} -> {value}");
                        value = String.Empty;
                    }

                    else
                        Console.WriteLine($"Contact {command[1]} does not exist.");
                }
                else if (command[0] == "ListAll")
                {

                    foreach (var contact in contactList)
                    {
                        Console.WriteLine($"{contact.Key} -> {contact.Value}");
                    }
                }

            }
        }
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fs_1 = require("../../util/fs");
const workspace_1 = tslib_1.__importDefault(require("../../workspace"));
const basic_1 = tslib_1.__importDefault(require("../basic"));
const vscode_uri_1 = require("vscode-uri");
const util_1 = require("../../util");
const path_1 = tslib_1.__importDefault(require("path"));
class FoldList extends basic_1.default {
    constructor(nvim) {
        super(nvim);
        this.defaultAction = 'edit';
        this.description = 'list of current workspace folders';
        this.name = 'folders';
        this.addAction('edit', async (item) => {
            let newPath = await nvim.call('input', ['Folder: ', item.label, 'file']);
            let stat = await fs_1.statAsync(newPath);
            if (!stat || !stat.isDirectory()) {
                await nvim.command(`echoerr "invalid path: ${newPath}"`);
                return;
            }
            workspace_1.default.renameWorkspaceFolder(item.label, newPath);
        }, { reload: true, persist: true });
        this.addAction('delete', async (item) => {
            workspace_1.default.removeWorkspaceFolder(item.label);
        }, { reload: true, persist: true });
        this.addAction('newfile', async (item) => {
            let file = await workspace_1.default.requestInput('File name', item.label + '/');
            let dir = path_1.default.dirname(file);
            let stat = await fs_1.statAsync(dir);
            if (!stat || !stat.isDirectory()) {
                let success = await util_1.mkdirp(dir);
                if (!success) {
                    util_1.echoErr(nvim, `Error creating new directory ${dir}`);
                    return;
                }
            }
            await workspace_1.default.createFile(file, { overwrite: false, ignoreIfExists: true });
            await this.jumpTo(vscode_uri_1.URI.file(file).toString());
        });
    }
    async loadItems(_context) {
        return workspace_1.default.folderPaths.map(p => {
            return { label: p };
        });
    }
}
exports.default = FoldList;
//# sourceMappingURL=folders.js.map


text:
package lombok.installer;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.TextAttribute;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;

import lombok.core.Version;
import lombok.installer.IdeFinder.OS;

/**
 * The lombok GUI installer.
 * Uses swing to show a simple GUI that can add and remove the java agent to IDE installations.
 * Also offers info on what this installer does in case people want to instrument their IDE manually.
 */
public class InstallerGUI {
	static final AtomicReference<Integer> exitMarker = new AtomicReference<Integer>();

	private JFrame appWindow;

	private JComponent loadingExpl;

	private Component javacArea;
	private Component ideArea;
	private Component uninstallArea;
	private Component howIWorkArea;

	private Box uninstallBox;
	private JHyperLink uninstallButton;
	private JLabel uninstallPlaceholder;
	private JButton installButton;

	private List<IdeLocation> toUninstall;
	private final Set<String> installSpecificMessages = new LinkedHashSet<String>();

	/**
	 * Creates a new installer that starts out invisible.
	 * Call the {@link #show()} method on a freshly created installer to render it.
	 */
	public InstallerGUI() {
		appWindow = new JFrame(String.format("Project Lombok v%s - Installer", Version.getVersion()));

		appWindow.setLocationByPlatform(true);
		appWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		appWindow.setResizable(false);
		appWindow.setIconImage(Toolkit.getDefaultToolkit().getImage(Installer.class.getResource("lombokIcon.png")));

		try {
			javacArea = buildJavacArea();
			ideArea = buildIdeArea();
			uninstallArea = buildUninstallArea();
			uninstallArea.setVisible(false);
			howIWorkArea = buildHowIWorkArea();
			howIWorkArea.setVisible(false);
			buildChrome(appWindow.getContentPane());
			appWindow.pack();
		} catch (Throwable t) {
			handleException(t);
		}
	}

	private void handleException(final Throwable t) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override public void run() {
				JOptionPane.showMessageDialog(appWindow, "There was a problem during the installation process:\n" + t, "Uh Oh!", JOptionPane.ERROR_MESSAGE);
				t.printStackTrace();
				System.exit(1);
			}
		});
	}

	private Component buildHowIWorkArea() {
		JPanel container = new JPanel();

		container.setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.anchor = GridBagConstraints.WEST;

		container.add(new JLabel(HOW_I_WORK_TITLE), constraints);

		constraints.gridy = 1;
		constraints.insets = new Insets(8, 0, 0, 16);
		container.add(new JLabel(String.format(HOW_I_WORK_EXPLANATION, File.separator)), constraints);

		Box buttonBar = Box.createHorizontalBox();
		JButton backButton = new JButton("Okay - Good to know!");
		buttonBar.add(Box.createHorizontalGlue());
		buttonBar.add(backButton);

		backButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				howIWorkArea.setVisible(false);
				javacArea.setVisible(true);
				ideArea.setVisible(true);
				appWindow.pack();
			}
		});

		constraints.gridy = 2;
		container.add(buttonBar, constraints);

		return container;
	}

	private Component buildUninstallArea() {
		JPanel container = new JPanel();

		container.setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.anchor = GridBagConstraints.WEST;

		container.add(new JLabel(UNINSTALL_TITLE), constraints);

		constraints.gridy = 1;
		constraints.insets = new Insets(8, 0, 0, 16);
		container.add(new JLabel(UNINSTALL_EXPLANATION), constraints);

		uninstallBox = Box.createVerticalBox();
		constraints.gridy = 2;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		container.add(uninstallBox, constraints);

		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridy = 3;
		container.add(new JLabel("Are you sure?"), constraints);

		Box buttonBar = Box.createHorizontalBox();
		JButton noButton = new JButton("No - Don't uninstall");
		buttonBar.add(noButton);
		buttonBar.add(Box.createHorizontalGlue());
		JButton yesButton = new JButton("Yes - uninstall Lombok");
		buttonBar.add(yesButton);

		noButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				uninstallArea.setVisible(false);
				javacArea.setVisible(true);
				ideArea.setVisible(true);
				appWindow.pack();
			}
		});

		yesButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				doUninstall();
			}
		});

		constraints.gridy = 4;
		container.add(buttonBar, constraints);

		return container;
	}

	private Component buildJavacArea() {
		JPanel container = new JPanel();

		container.setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.anchor = GridBagConstraints.WEST;
		constraints.insets = new Insets(8, 0, 0, 16);

		container.add(new JLabel(JAVAC_TITLE), constraints);

		constraints.gridy = 1;
		constraints.weightx = 1.0;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		container.add(new JLabel(JAVAC_EXPLANATION), constraints);

		JLabel example = new JLabel(JAVAC_EXAMPLE);

		constraints.gridy = 2;
		container.add(example, constraints);
		return container;
	}

	private Component buildIdeArea() {
		JPanel container = new JPanel();

		container.setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.anchor = GridBagConstraints.WEST;

		constraints.insets = new Insets(8, 0, 0, 16);
		container.add(new JLabel(IDE_TITLE), constraints);

		constraints.gridy = 1;
		container.add(new JLabel(IDE_EXPLANATION), constraints);

		constraints.gridy = 2;
		loadingExpl = Box.createHorizontalBox();
		loadingExpl.add(new JLabel(new ImageIcon(Installer.class.getResource("loading.gif"))));
		loadingExpl.add(new JLabel(IDE_LOADING_EXPLANATION));
		container.add(loadingExpl, constraints);

		constraints.weightx = 1.0;
		constraints.gridy = 3;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		idesList = new IdesList();

		JScrollPane idesListScroll = new JScrollPane(idesList);
		idesListScroll.setBackground(Color.WHITE);
		idesListScroll.getViewport().setBackground(Color.WHITE);
		container.add(idesListScroll, constraints);

		Thread findIdesThread = new Thread() {
			@Override public void run() {
				try {
					final List<IdeLocation> locations = new ArrayList<IdeLocation>();
					final List<CorruptedIdeLocationException> problems = new ArrayList<CorruptedIdeLocationException>();
					Installer.autoDiscover(locations, problems);

					SwingUtilities.invokeLater(new Runnable() {
						@Override public void run() {
							for (IdeLocation location : locations) {
								try {
									idesList.addLocation(location);
								} catch (Throwable t) {
									handleException(t);
								}
							}

							for (CorruptedIdeLocationException problem : problems) {
								problem.showDialog(appWindow);
							}

							loadingExpl.setVisible(false);

							if (locations.size() + problems.size() == 0) {
								JOptionPane.showMessageDialog(appWindow,
										"I can't find any IDEs on your computer.\n" +
										"If you have IDEs installed on this computer, please use the " +
										"'Specify Location...' button to manually point out the \n" +
										"location of your IDE installation to me. Thanks!",
										"Can't find IDE", JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
				} catch (Throwable t) {
					handleException(t);
				}
			}
		};

		findIdesThread.start();

		Box buttonBar = Box.createHorizontalBox();
		JButton specifyIdeLocationButton = new JButton("Specify location...");
		buttonBar.add(specifyIdeLocationButton);
		specifyIdeLocationButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent event) {
				final List<Pattern> exeNames = Installer.getIdeExecutableNames();
				String file = null;

				if (IdeFinder.getOS() == OS.MAC_OS_X) {
					FileDialog chooser = new FileDialog(appWindow);
					chooser.setMode(FileDialog.LOAD);

					chooser.setFilenameFilter(new FilenameFilter() {
						@Override public boolean accept(File dir, String fileName) {
							for (Pattern exeName : exeNames) if (exeName.matcher(fileName).matches()) return true;
							return false;
						}
					});

					chooser.setVisible(true);
					if (chooser.getDirectory() != null && chooser.getFile() != null) {
						file = new File(chooser.getDirectory(), chooser.getFile()).getAbsolutePath();
					}
				} else {
					JFileChooser chooser = new JFileChooser();

					chooser.setAcceptAllFileFilterUsed(false);
					chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
					chooser.setFileFilter(new FileFilter() {
						@Override public boolean accept(File f) {
							if (f.isDirectory()) return true;
							for (Pattern exeName : exeNames) if (exeName.matcher(f.getName()).matches()) return true;

							return false;
						}

						@Override public String getDescription() {
							return "IDE Installation";
						}
					});

					switch (chooser.showDialog(appWindow, "Select")) {
					case JFileChooser.APPROVE_OPTION:
						file = chooser.getSelectedFile().getAbsolutePath();
					}
				}

				if (file != null) {
					try {
						IdeLocation loc = Installer.tryAllProviders(file);
						if (loc != null) idesList.addLocation(loc);
						else JOptionPane.showMessageDialog(appWindow, "I can't find any IDE that lombok supports at location: " + file, "No IDE found", JOptionPane.WARNING_MESSAGE);
					} catch (CorruptedIdeLocationException e) {
						e.showDialog(appWindow);
					} catch (Throwable t) {
						handleException(t);
					}
				}
			}
		});

		buttonBar.add(Box.createHorizontalGlue());
		installButton = new JButton("Install / Update");
		buttonBar.add(installButton);

		installButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				List<IdeLocation> locationsToInstall = new ArrayList<IdeLocation>(idesList.getSelectedIdes());
				if (locationsToInstall.isEmpty()) {
					JOptionPane.showMessageDialog(appWindow, "You haven't selected any IDE installations!.", "No Selection", JOptionPane.WARNING_MESSAGE);
					return;
				}

				install(locationsToInstall);
			}
		});

		constraints.gridy = 4;
		constraints.weightx = 0;
		container.add(buttonBar, constraints);

		constraints.gridy = 5;
		constraints.fill = GridBagConstraints.NONE;
		JHyperLink showMe = new JHyperLink("Show me what this installer will do to my IDE installation.");
		container.add(showMe, constraints);
		showMe.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				showWhatIDo();
			}
		});

		constraints.gridy = 6;
		uninstallButton = new JHyperLink("Uninstall lombok from selected IDE installations.");
		uninstallPlaceholder = new JLabel(" ");
		uninstallButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				List<IdeLocation> locationsToUninstall = new ArrayList<IdeLocation>();
				for (IdeLocation location : idesList.getSelectedIdes()) {
					if (location.hasLombok()) locationsToUninstall.add(location);
				}

				if (locationsToUninstall.isEmpty()) {
					JOptionPane.showMessageDialog(appWindow, "You haven't selected any IDE installations that have been lombok-enabled.", "No Selection", JOptionPane.WARNING_MESSAGE);
					return;
				}

				uninstall(locationsToUninstall);
			}
		});
		container.add(uninstallButton, constraints);
		uninstallPlaceholder.setVisible(false);
		container.add(uninstallPlaceholder, constraints);

		return container;
	}

	private void showWhatIDo() {
		javacArea.setVisible(false);
		ideArea.setVisible(false);
		howIWorkArea.setVisible(true);
		appWindow.pack();
	}

	private void uninstall(List<IdeLocation> locations) {
		javacArea.setVisible(false);
		ideArea.setVisible(false);

		uninstallBox.removeAll();
		uninstallBox.add(Box.createRigidArea(new Dimension(1, 16)));
		for (IdeLocation location : locations) {
			JLabel label = new JLabel(location.getName());
			label.setFont(label.getFont().deriveFont(Font.BOLD));
			uninstallBox.add(label);
		}
		uninstallBox.add(Box.createRigidArea(new Dimension(1, 16)));

		toUninstall = locations;
		uninstallArea.setVisible(true);
		appWindow.pack();
	}

	private void install(final List<IdeLocation> toInstall) {
		JPanel spinner = new JPanel();
		spinner.setOpaque(true);
		spinner.setLayout(new FlowLayout());
		spinner.add(new JLabel(new ImageIcon(Installer.class.getResource("loading.gif"))));
		appWindow.setContentPane(spinner);

		final AtomicInteger successes = new AtomicInteger();
		final AtomicBoolean failure = new AtomicBoolean();

		new Thread() {
			@Override public void run() {
				for (IdeLocation loc : toInstall) {
					try {
						installSpecificMessages.add(loc.install());
						successes.incrementAndGet();
					} catch (final InstallException e) {
						if (e.isWarning()) {
							try {
								SwingUtilities.invokeAndWait(new Runnable() {
									@Override public void run() {
										JOptionPane.showMessageDialog(appWindow,
												e.getMessage(), "Install Problem", JOptionPane.WARNING_MESSAGE);
									}
								});
							} catch (Exception e2) {
								e2.printStackTrace();
								//Shouldn't happen.
								throw new RuntimeException(e2);
							}
						} else {
							failure.set(true);
							try {
								SwingUtilities.invokeAndWait(new Runnable() {
									@Override public void run() {
										JOptionPane.showMessageDialog(appWindow,
												e.getMessage(), "Install Problem", JOptionPane.ERROR_MESSAGE);
									}
								});
							} catch (Exception e2) {
								e2.printStackTrace();
								//Shouldn't happen.
								throw new RuntimeException(e2);
							}
						}
					}
				}

				if (successes.get() > 0) {
					try {
						SwingUtilities.invokeAndWait(new Runnable() {
							@Override public void run() {
								StringBuilder installSpecific = new StringBuilder();
								for (String installSpecificMessage : installSpecificMessages) {
									installSpecific.append("
").append(installSpecificMessage);
								}
								JOptionPane.showMessageDialog(appWindow,
										"Lombok has been installed on the selected IDE installations.
" +
										"Don't forget to add lombok.jar to your projects, and restart your IDE!" + installSpecific.toString() + "",
										"Install successful",
										JOptionPane.INFORMATION_MESSAGE);
								appWindow.setVisible(false);
								synchronized (exitMarker) {
									exitMarker.set(0);
									exitMarker.notifyAll();
								}
							}
						});
					} catch (Exception e) {
						// Shouldn't happen.
						throw new RuntimeException(e);
					}
				} else {
					SwingUtilities.invokeLater(new Runnable() {
						@Override public void run() {
							synchronized (exitMarker) {
								exitMarker.set(failure.get() ? 1 : 0);
								exitMarker.notifyAll();
							}
						}
					});
				}
			}
		}.start();
	}

	private void doUninstall() {
		JPanel spinner = new JPanel();
		spinner.setOpaque(true);
		spinner.setLayout(new FlowLayout());
		spinner.add(new JLabel(new ImageIcon(Installer.class.getResource("/lombok/installer/loading.gif"))));

		final Container originalContentPane = appWindow.getContentPane();
		appWindow.setContentPane(spinner);

		final AtomicInteger successes = new AtomicInteger();
		new Thread(new Runnable() {
			@Override public void run() {
				for (IdeLocation loc : toUninstall) {
					try {
						loc.uninstall();
						successes.incrementAndGet();
					} catch (final UninstallException e) {
						if (e.isWarning()) {
							try {
								SwingUtilities.invokeAndWait(new Runnable() {
									@Override public void run() {
										JOptionPane.showMessageDialog(appWindow,
												e.getMessage(), "Uninstall Problem", JOptionPane.WARNING_MESSAGE);
									}
								});
							} catch (Exception e2) {
								e2.printStackTrace();
								//Shouldn't happen.
								throw new RuntimeException(e2);
							}
						} else {
							try {
								SwingUtilities.invokeAndWait(new Runnable() {
									@Override public void run() {
										JOptionPane.showMessageDialog(appWindow,
												e.getMessage(), "Uninstall Problem", JOptionPane.ERROR_MESSAGE);
									}
								});
							} catch (Exception e2) {
								e2.printStackTrace();
								//Shouldn't happen.
								throw new RuntimeException(e2);
							}
						}
					}
				}

				SwingUtilities.invokeLater(new Runnable() {
					@Override public void run() {
						if (successes.get() > 0) {
							JOptionPane.showMessageDialog(appWindow, "Lombok has been removed from the selected IDE installations.", "Uninstall successful", JOptionPane.INFORMATION_MESSAGE);
							appWindow.setVisible(false);
							System.exit(0);
							return;
						}

						appWindow.setContentPane(originalContentPane);
					}
				});

			}
		}).start();
	}

	private IdesList idesList = new IdesList();

	void selectedLomboksChanged(List<IdeLocation> selectedIdes) {
		boolean uninstallAvailable = false;
		boolean installAvailable = false;
		for (IdeLocation loc : selectedIdes) {
			if (loc.hasLombok()) uninstallAvailable = true;
			installAvailable = true;
		}

		uninstallButton.setVisible(uninstallAvailable);
		uninstallPlaceholder.setVisible(!uninstallAvailable);
		installButton.setEnabled(installAvailable);
	}

	private class IdesList extends JPanel implements Scrollable {
		private static final long serialVersionUID = 1L;

		List<IdeLocation> locations = new ArrayList<IdeLocation>();

		IdesList() {
			setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
			setBackground(Color.WHITE);
		}

		List<IdeLocation> getSelectedIdes() {
			List<IdeLocation> list = new ArrayList<IdeLocation>();
			for (IdeLocation loc : locations) if (loc.selected) list.add(loc);
			return list;
		}

		void fireSelectionChange() {
			selectedLomboksChanged(getSelectedIdes());
		}

		void addLocation(final IdeLocation location) {
			if (locations.contains(location)) return;
			Box box = Box.createHorizontalBox();
			box.setBackground(Color.WHITE);
			final JCheckBox checkbox = new JCheckBox(location.getName());
			checkbox.setBackground(Color.WHITE);
			box.add(new JLabel(new ImageIcon(location.getIdeIcon())));
			box.add(checkbox);
			checkbox.setSelected(true);
			checkbox.addActionListener(new ActionListener() {
				@Override public void actionPerformed(ActionEvent e) {
					location.selected = checkbox.isSelected();
					fireSelectionChange();
				}
			});

			if (location.hasLombok()) {
				box.add(new JLabel(new ImageIcon(Installer.class.getResource("lombokIcon.png"))));
			}
			box.add(Box.createHorizontalGlue());
			locations.add(location);
			add(box);
			getParent().doLayout();
			fireSelectionChange();
		}

		@Override public Dimension getPreferredScrollableViewportSize() {
			return new Dimension(1, 100);
		}

		@Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
			return 12;
		}

		@Override public boolean getScrollableTracksViewportHeight() {
			return false;
		}

		@Override public boolean getScrollableTracksViewportWidth() {
			return true;
		}

		@Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
			return 1;
		}
	}

	private void buildChrome(Container appWindowContainer) {
		JLabel leftGraphic = new JLabel(new ImageIcon(Installer.class.getResource("lombok.png")));

		GridBagConstraints constraints = new GridBagConstraints();

		appWindowContainer.setLayout(new GridBagLayout());

		constraints.gridheight = 3;
		constraints.gridwidth = 1;
		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.insets = new Insets(8, 8, 8, 8);
		appWindowContainer.add(leftGraphic, constraints);
		constraints.insets = new Insets(0, 0, 0, 0);

		constraints.gridx++;
		constraints.gridy++;
		constraints.gridheight = 1;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.ipadx = 16;
		constraints.ipady = 14;
		appWindowContainer.add(javacArea, constraints);

		constraints.gridy++;
		appWindowContainer.add(ideArea, constraints);

		appWindowContainer.add(uninstallArea, constraints);

		appWindowContainer.add(howIWorkArea, constraints);

		constraints.gridy++;
		constraints.gridwidth = 2;
		constraints.gridx = 0;
		constraints.weightx = 0;
		constraints.weighty = 0;
		constraints.ipadx = 0;
		constraints.ipady = 0;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.anchor = GridBagConstraints.SOUTHEAST;
		constraints.insets = new Insets(0, 16, 8, 8);
		Box buttonBar = Box.createHorizontalBox();
		JButton quitButton = new JButton("Quit Installer");
		quitButton.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				appWindow.setVisible(false);
				System.exit(0);
			}
		});
		final JHyperLink hyperlink = new JHyperLink(Installer.ABOUT_LOMBOK_URL.toString());
		hyperlink.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent event) {
				hyperlink.setForeground(new Color(85, 145, 90));
				try {
					//java.awt.Desktop doesn't exist in 1.5.
					Object desktop = Class.forName("java.awt.Desktop").getMethod("getDesktop").invoke(null);
					Class.forName("java.awt.Desktop").getMethod("browse", URI.class).invoke(desktop, Installer.ABOUT_LOMBOK_URL);
				} catch (Exception e) {
					Runtime rt = Runtime.getRuntime();
					try {
						switch (IdeFinder.getOS()) {
						case WINDOWS:
							String[] cmd = new String[4];
							cmd[0] = "cmd.exe";
							cmd[1] = "/C";
							cmd[2] = "start";
							cmd[3] = Installer.ABOUT_LOMBOK_URL.toString();
							rt.exec(cmd);
							break;
						case MAC_OS_X:
							rt.exec("open " + Installer.ABOUT_LOMBOK_URL.toString());
							break;
						default:
						case UNIX:
							rt.exec("firefox " + Installer.ABOUT_LOMBOK_URL.toString());
							break;
						}
					} catch (Exception e2) {
						JOptionPane.showMessageDialog(appWindow,
								"Well, this is embarrassing. I don't know how to open a webbrowser.\n" +
								"I guess you'll have to open it. Browse to:\n" + Installer.ABOUT_LOMBOK_URL +
								" for more information about Lombok.",
								"I'm embarrassed", JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}
		});
		buttonBar.add(hyperlink);
		buttonBar.add(Box.createRigidArea(new Dimension(16, 1)));
		buttonBar.add(new JLabel("v" + Version.getVersion() + ""));

		buttonBar.add(Box.createHorizontalGlue());
		buttonBar.add(quitButton);
		appWindow.add(buttonBar, constraints);
	}

	/**
	 * Makes the installer window visible.
	 */
	public void show() {
		appWindow.setVisible(true);
		if (IdeFinder.getOS() == OS.MAC_OS_X) {
			try {
				AppleNativeLook.go();
			} catch (Throwable ignore) {
				//We're just prettying up the app. If it fails, meh.
			}
		}
	}

	private static final String IDE_TITLE =
		"IDEs";

	private static final String IDE_EXPLANATION =
		"Lombok can update your Eclipse or eclipse-based IDE to fully support all Lombok features.
" +
		"Select IDE installations below and hit 'Install/Update'.";

	private static final String IDE_LOADING_EXPLANATION =
		"Scanning your drives for IDE installations...";

	private static final String JAVAC_TITLE =
		"Javac       (and tools that invoke javac such as ant and maven)";

	private static final String JAVAC_EXPLANATION =
		"Lombok works 'out of the box' with javac.
Just make sure the lombok.jar is in your classpath when you compile.";

	private static final String JAVAC_EXAMPLE =
		"Example: javac -cp lombok.jar MyCode.java";

	private static final String UNINSTALL_TITLE =
		"Uninstall";

	private static final String UNINSTALL_EXPLANATION =
		"Uninstall Lombok from the following IDE Installations?";

	private static final String HOW_I_WORK_TITLE =
		"What this installer does";

	private static final String HOW_I_WORK_EXPLANATION =
		"
Eclipse

" +
		"
First, I copy myself (lombok.jar) to your Eclipse install directory.
" +
		"
Then, I edit the eclipse.ini file to add the following entry:
" +
		"
-javaagent:lombok.jar

" +
		"On Mac OS X, eclipse.ini is hidden in
" +
		"Eclipse.app/Contents/MacOS so that's where I place the jar files.";

	private static class JHyperLink extends JButton {
		private static final long serialVersionUID = 1L;

		public JHyperLink(String text) {
			super();
			setFont(getFont().deriveFont(Collections.singletonMap(TextAttribute.UNDERLINE, 1)));
			setText(text);
			setBorder(null);
			setContentAreaFilled(false);
			setForeground(Color.BLUE);
			setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			setMargin(new Insets(0, 0, 0, 0));
		}
	}
}


text:
package cucumber.contrib.formatter.renderer;

/**
* @author @aloyer
*/
public enum ChartType {
    Pie,
    XY,
    Histogram;

    public static ChartType fromString(String value) {
        for (ChartType type : values())
            if (type.name().equalsIgnoreCase(value))
                return type;
        throw new IllegalArgumentException("Unsupported type '" + value + "'");
    }
}


text:
`DropdownField` is similar to `SelectField`, but more normal. It uses a `<select>` component and has an onChange/onBlur/etc that use DOM events.

When `value` prop is truthy, the "blank" option isn't shown:

```js
const [state, setState] = React.useState({ selectedValue: 'rna' })
;<DropdownField
  onChange={e => setState({ selectedValue: e.target.value })}
  value={state.selectedValue}
  options={[
    { name: 'DNA', value: 'dna' },
    { name: 'RNA', value: 'rna' },
    { name: 'Protein', value: 'protein' },
  ]}
/>
```

When `value` is falsey, the "blank" option appears and is selected. You can't get back to blank state once you're selected something without external state manipulation. This is similar to how `RadioGroup` works.

```js
import { FlatButton } from '@opentrons/components'
const [state, setState] = React.useState({ selectedValue: null })
;<div>
  <DropdownField
    onChange={e => setState({ selectedValue: e.target.value })}
    value={state.selectedValue}
    options={[
      { name: 'DNA', value: 'dna' },
      { name: 'RNA', value: 'rna' },
      { name: 'Protein', value: 'protein' },
    ]}
  />
  <FlatButton onClick={e => setState({ selectedValue: null })}>
    Click to Reset
  </FlatButton>
</div>
```

To make a `DropdownField` always allow the user to select a blank value, add an option object to the `options` prop with a blank (empty string) value:

```js
const [state, setState] = React.useState({ selectedValue: '' })
;<DropdownField
  onChange={e => setState({ selectedValue: e.target.value })}
  value={state.selectedValue}
  options={[
    { name: '', value: '' },
    { name: 'DNA', value: 'dna' },
    { name: 'RNA', value: 'rna' },
    { name: 'Protein', value: 'protein' },
  ]}
/>
```


text:
using System;

using Ghul.Collections;

namespace Ghul.Ecs
{
	/// <summary>
	/// (A handle to) An entity composed of components.
	/// </summary>
	internal class Entity : IInternalEntity
	{
		/// <summary>
		/// Indicates if the entity still exists, i.e. was not removed yet.
		/// </summary>
		public bool Exists { get; private set; } = true;

		/// <summary>
		/// The backing engine, null if it does not exist anymore.
		/// </summary>
		internal IInternalEngine Engine { get; private set; }

		/// <summary>
		/// The positive index of this entity, -1 if it does not exist anymore.
		/// </summary>
		internal int Index { get; private set; }

		/// <summary>
		/// The component bit mask of the entity, null if it does not exist anymore.
		/// </summary>
		internal BitBag ComponentBitMask =>
			Exists ? Engine.ComponentStore.GetComponentBitMask(this) : null;

		/// <summary>
		/// The tag bit mask of the entity, null if it does not exist anymore.
		/// </summary>
		internal BitBag TagBitMask => Exists ? Engine.TagStore.GetTagBitMask(this) : null;

		// Explicit implementations to keep internal
		IInternalEngine IInternalEntity.Engine => Engine;

		int IInternalEntity.Index => Index;

		BitBag IInternalEntity.ComponentBitMask => ComponentBitMask;

		BitBag IInternalEntity.TagBitMask => TagBitMask;

		/// <summary>
		/// Creates a new (handle to an) entity composed of components.
		/// </summary>
		/// <param name="index">The positive index of this entity.</param>
		/// <param name="engine">The backing engine.</param>
		/// <exception cref="ArgumentNullException">If engine is null.</exception>
		/// <exception cref="ArgumentOutOfRangeException">If id is not positive.</exception>
		public Entity(int index, IInternalEngine engine)
		{
			Ensure.IsNotLessThan(index, 0, nameof(index));
			Ensure.IsNotNull(engine, nameof(engine));

			Index = index;
			Engine = engine;
		}

		/// <summary>
		/// Checks if the entity has a component of a certain type.
		/// </summary>
		/// <typeparam name="T">The type of the component.</typeparam>
		/// <returns>True if the entity has a component of type <see cref="T"/>, false otherwise.</returns>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public bool HasComponent<T>() => Exists
			? Engine.ComponentStore.HasComponent<T>(this)
			: throw new InvalidOperationException("The entity no longer exists");

		/// <summary>
		/// Checks if the entity has any components.
		/// </summary>
		/// <returns>True if the entity has any components, false otherwise.</returns>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public bool HasAnyComponents() => Exists
			? Engine.ComponentStore.HasAnyComponents(this)
			: throw new InvalidOperationException("The entity no longer exists");

		/// <summary>
		/// Retrieves a component from the entity by type.
		/// </summary>
		/// <typeparam name="T">The type of the component.</typeparam>
		/// <returns>
		/// The component if one of type <see cref="T"/> was added, the default value of T
		/// otherwise.
		/// </returns>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public T GetComponent<T>() => Exists
			? Engine.ComponentStore.GetComponent<T>(this)
			: throw new InvalidOperationException("The entity no longer exists");

		/// <summary>
		/// Tries to retrieve a component from the entity by type.
		/// </summary>
		/// <typeparam name="T">The type of the component.</typeparam>
		/// <param name="component">
		/// Will contain the component if one of type <see cref="T"/> was added, the default value of T
		/// otherwise.
		/// </param>
		/// <returns>True if the entity has a component of type <see cref="T"/>, false otherwise.</returns>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public bool TryGetComponent<T>(out T component) => Exists
			? Engine.ComponentStore.TryGetComponent(this, out component)
			: throw new InvalidOperationException("The entity no longer exists");

		/// <summary>
		/// Adds a component to the entity, replacing any existing component of the same type.
		/// </summary>
		/// <typeparam name="T">The type of the component.</typeparam>
		/// <param name="component">The component to add.</param>
		/// <exception cref="ArgumentNullException">If component is null.</exception>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void AddComponent<T>(T component)
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.ComponentStore.AddComponent(this, component);
		}

		/// <summary>
		/// Adds a component from a registered pool to the entity, replacing any existing component
		/// of the same type.
		/// </summary>
		/// <typeparam name="T">The type of the component.</typeparam>
		/// <exception cref="ArgumentException">
		/// If no component pool was registered for
		/// <see cref="T"/>.
		/// </exception>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void AddPoolComponent<T>()
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.ComponentStore.AddPoolComponent<T>(this);
		}

		/// <summary>
		/// Removes a component of a certain type from the entity if one was added.
		/// </summary>
		/// <typeparam name="T">The type of the component.</typeparam>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void RemoveComponent<T>()
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.ComponentStore.RemoveComponent<T>(this);
		}

		/// <summary>
		/// Removes all added components from the entity.
		/// </summary>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void ClearComponents()
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.ComponentStore.ClearComponents(this);
		}

		/// <summary>
		/// Checks if the entity has a tag.
		/// </summary>
		/// <param name="tag">The tag to check.</param>
		/// <returns>True if the entity has the tag, false otherwise.</returns>
		/// <exception cref="ArgumentNullException">If tag is null.</exception>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public bool HasTag(string tag) => Exists
			? Engine.TagStore.HasTag(this, tag)
			: throw new InvalidOperationException("The entity no longer exists");

		/// <summary>
		/// Checks if the entity has any tags.
		/// </summary>
		/// <returns>True if the entity has any tags, false otherwise.</returns>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public bool HasAnyTags() => Exists
			? Engine.TagStore.HasAnyTags(this)
			: throw new InvalidOperationException("The entity no longer exists");

		/// <summary>
		/// Adds a tag to the entity if it was not added.
		/// </summary>
		/// <param name="tag">The tag to add.</param>
		/// <exception cref="ArgumentNullException">If tag is null.</exception>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void AddTag(string tag)
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.TagStore.AddTag(this, tag);
		}

		/// <summary>
		/// Removes a tag from the entity if it was added.
		/// </summary>
		/// <param name="tag">The tag to remove.</param>
		/// <exception cref="ArgumentNullException">If tag is null.</exception>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void RemoveTag(string tag)
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.TagStore.RemoveTag(this, tag);
		}

		/// <summary>
		/// Removes all added tags from the entity.
		/// </summary>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void ClearTags()
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.TagStore.ClearTags(this);
		}

		/// <summary>
		/// Removes the entity from its engine.
		/// </summary>
		/// <exception cref="InvalidOperationException">If the entity no longer exists.</exception>
		public void Remove()
		{
			if(!Exists)
			{
				throw new InvalidOperationException("The entity no longer exists");
			}

			Engine.EntityStore.RemoveEntity(this);

			Exists = false;
			Index = -1;
			// Also prevent dangling reference from this to the engine
			Engine = null;
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Net;

namespace Octokit
{
    public interface IResponse<T> : IResponse
    {
        new T BodyAsObject { get; set; }
    }

    public interface IResponse
    {
        object BodyAsObject { get; set; }
        string Body { get; set; }
        Dictionary<string, string> Headers { get; }
        Uri ResponseUri { get; set; }
        ApiInfo ApiInfo { get; set; }
        HttpStatusCode StatusCode { get; set; }
        string ContentType { get; set; }
    }
}


text:
package org.apache.usergrid.corepersistence.index;

import org.safehaus.guicyfig.Default;
import org.safehaus.guicyfig.FigSingleton;
import org.safehaus.guicyfig.GuicyFig;
import org.safehaus.guicyfig.Key;

/**
 * Collection settings cache config
 */
@FigSingleton
public interface CollectionSettingsCacheFig extends GuicyFig {

    @Key( "usergrid.collection_settings_cache_size" )
    @Default( "5000" )
    int getCacheSize();

    @Key( "usergrid.collection_settings_cache_timeout_ms" )
    @Default( "15000" )
    int getCacheTimeout();

}


text:
package com.bumptech.glide.load.resource.gif;

import android.content.Context;
import android.graphics.Bitmap;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import com.bumptech.glide.util.Preconditions;
import java.security.MessageDigest;

/**
 * An {@link com.bumptech.glide.load.Transformation} that wraps a transformation for a
 * {@link Bitmap} and can apply it to every frame of any
 * {@link com.bumptech.glide.load.resource.gif.GifDrawable}.
 */
public class GifDrawableTransformation implements Transformation<GifDrawable> {
  private final Transformation<Bitmap> wrapped;

  public GifDrawableTransformation(Transformation<Bitmap> wrapped) {
    this.wrapped = Preconditions.checkNotNull(wrapped);
  }

  /**
   * @deprecated Use {@link #GifDrawableTransformation(Transformation)}.
   */
  @Deprecated
  public GifDrawableTransformation(
      @SuppressWarnings("unused") Context context, Transformation<Bitmap> wrapped) {
    this(wrapped);
  }

  /**
   * @deprecated Use {@link #GifDrawableTransformation(Transformation)}
   */
  @Deprecated
  public GifDrawableTransformation(
      Transformation<Bitmap> wrapped, @SuppressWarnings("unused") BitmapPool bitmapPool) {
    this(wrapped);
  }

  @Override
  public Resource<GifDrawable> transform(
      Context context, Resource<GifDrawable> resource, int outWidth, int outHeight) {
    GifDrawable drawable = resource.get();

    // The drawable needs to be initialized with the correct width and height in order for a view
    // displaying it to end up with the right dimensions. Since our transformations may arbitrarily
    // modify the dimensions of our GIF, here we create a stand in for a frame and pass it to the
    // transformation to see what the final transformed dimensions will be so that our drawable can
    // report the correct intrinsic width and height.
    BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
    Bitmap firstFrame = drawable.getFirstFrame();
    Resource<Bitmap> bitmapResource = new BitmapResource(firstFrame, bitmapPool);
    Resource<Bitmap> transformed = wrapped.transform(context, bitmapResource, outWidth, outHeight);
    if (!bitmapResource.equals(transformed)) {
      bitmapResource.recycle();
    }
    Bitmap transformedFrame = transformed.get();

    drawable.setFrameTransformation(wrapped, transformedFrame);
    return resource;
  }

  @Override
  public boolean equals(Object o) {
    if (o instanceof GifDrawableTransformation) {
      GifDrawableTransformation other = (GifDrawableTransformation) o;
      return wrapped.equals(other.wrapped);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return wrapped.hashCode();
  }

  @Override
  public void updateDiskCacheKey(MessageDigest messageDigest) {
    wrapped.updateDiskCacheKey(messageDigest);
  }
}


text:
FROM ubuntu:17.10

RUN apt-get update && apt-get install -y --no-install-recommends \
        gcc libc6-dev qemu-user ca-certificates \
        gcc-s390x-linux-gnu libc6-dev-s390x-cross

ENV CARGO_TARGET_S390X_UNKNOWN_LINUX_GNU_LINKER=s390x-linux-gnu-gcc \
    CC_s390x_unknown_linux_gnu=s390x-linux-gnu-gcc \
    PATH=$PATH:/rust/bin


text:
@implementation V2BaseModel

- (instancetype)initWithDictionary:(NSDictionary *)dict {
    if (self = [super init]) {
        ;
    }

    return self;
}

@end


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

<title>HierarchyWizardPageOrder (ARX GUI Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.gui.view.impl.wizard

Class HierarchyWizardPageOrder<T>

java.lang.Object

org.eclipse.jface.dialogs.DialogPage

org.eclipse.jface.wizard.WizardPage

org.deidentifier.arx.gui.view.impl.wizard.HierarchyWizardPageBuilder<T>

org.deidentifier.arx.gui.view.impl.wizard.HierarchyWizardPageOrder<T>

Type Parameters:

T -

All Implemented Interfaces:

HierarchyWizard.HierarchyWizardView, org.eclipse.jface.dialogs.IDialogPage, org.eclipse.jface.dialogs.IMessageProvider, org.eclipse.jface.wizard.IWizardPage

public class HierarchyWizardPageOrder<T>
extends HierarchyWizardPageBuilder<T>

A page for configuring the order-based builder.

Field Summary

Fields inherited from interface org.eclipse.jface.dialogs.IMessageProvider

ERROR, INFORMATION, NONE, WARNING

Constructor Summary

Constructors

Constructor and Description

HierarchyWizardPageOrder(Controller controller,
                        HierarchyWizard<T> wizard,
                        HierarchyWizardModel<T> model,
                        HierarchyWizardPageFinal<T> finalPage)

Creates a new instance.

Method Summary

Methods

Modifier and Type
Method and Description

void
createControl(org.eclipse.swt.widgets.Composite parent)

void
updatePage()

Update the page when the model has changed.

Methods inherited from class org.deidentifier.arx.gui.view.impl.wizard.HierarchyWizardPageBuilder

canFlipToNextPage, getNextPage, setVisible, update

Methods inherited from class org.eclipse.jface.wizard.WizardPage

getContainer, getDialogSettings, getImage, getName, getPreviousPage, getShell, getWizard, isCurrentPage, isPageComplete, setDescription, setErrorMessage, setImageDescriptor, setMessage, setPageComplete, setPreviousPage, setTitle, setWizard, toString

Methods inherited from class org.eclipse.jface.dialogs.DialogPage

convertHeightInCharsToPixels, convertHorizontalDLUsToPixels, convertVerticalDLUsToPixels, convertWidthInCharsToPixels, dispose, getControl, getDescription, getDialogFontName, getErrorMessage, getFont, getMessage, getMessageType, getTitle, getToolTipText, initializeDialogUnits, isControlCreated, performHelp, setButtonLayoutData, setControl, setMessage

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface org.eclipse.jface.dialogs.IDialogPage

dispose, getControl, getDescription, getErrorMessage, getMessage, getTitle, performHelp

Constructor Detail

HierarchyWizardPageOrder

public HierarchyWizardPageOrder(Controller controller,
                        HierarchyWizard<T> wizard,
                        HierarchyWizardModel<T> model,
                        HierarchyWizardPageFinal<T> finalPage)

Creates a new instance.

Parameters:

controller -

wizard -

model -

finalPage -

Method Detail

createControl

public void createControl(org.eclipse.swt.widgets.Composite parent)

updatePage

public void updatePage()

Description copied from class: HierarchyWizardPageBuilder

Update the page when the model has changed.

Specified by:

updatePage in class HierarchyWizardPageBuilder<T>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BALANCESVIEW_H
#define BALANCESVIEW_H

#include "guiutil.h"

#include <QWidget>

class TransactionFilterProxy;
class WalletModel;

QT_BEGIN_NAMESPACE
class QComboBox;
class QDateTimeEdit;
class QFrame;
class QLineEdit;
class QMenu;
class QModelIndex;
class QSignalMapper;
class QTableView;
QT_END_NAMESPACE

/** Widget showing the transaction list for a wallet, including a filter row.
    Using the filter row, the user can view or export a subset of the transactions.
  */
class BalancesView : public QWidget
{
    Q_OBJECT

public:
    explicit BalancesView(QWidget *parent = 0);

    void setModel(WalletModel *model);

    // Date ranges for filter
    enum DateEnum
    {
        All,
        Today,
        ThisWeek,
        ThisMonth,
        LastMonth,
        ThisYear,
        Range
    };

    enum ColumnWidths {
        STATUS_COLUMN_WIDTH = 23,
        DATE_COLUMN_WIDTH = 120,
        TYPE_COLUMN_WIDTH = 120,
        AMOUNT_MINIMUM_COLUMN_WIDTH = 120,
        MINIMUM_COLUMN_WIDTH = 23
    };

private:
    WalletModel *model;
    TransactionFilterProxy *transactionProxyModel;
    QTableView *balancesView;
    QTableView *view;

    QLabel *propSelLabel;
    QComboBox *propSelectorWidget;
    QComboBox *typeWidget;
    QLineEdit *addressWidget;
    QLineEdit *amountWidget;

    QMenu *contextMenu;
    QSignalMapper *mapperThirdPartyTxUrls;

    QFrame *dateRangeWidget;
    QDateTimeEdit *dateFrom;
    QDateTimeEdit *dateTo;

    QWidget *createDateRangeWidget();

    GUIUtil::TableViewLastColumnResizingFixer *columnResizingFixer;

    virtual void resizeEvent(QResizeEvent* event);

private slots:
    void contextualMenu(const QPoint &);
    //void dateRangeChanged();
    //void showDetails();
    //void copyAddress();
    //void editLabel();
    //void copyLabel();
    //void copyAmount();
    //void copyTxID();
    //void openThirdPartyTxUrl(QString url);

signals:
    void doubleClicked(const QModelIndex&);

    /**  Fired when a message should be reported to the user */
    void message(const QString &title, const QString &message, unsigned int style);

public slots:
    void propSelectorChanged(int idx);
    void balancesCopyAddress();
    void balancesCopyLabel();
    void balancesCopyAmount();
};

#endif // BALANCESVIEW_H


text:
<?php

namespace Application\Model\Entity;

/**
 * Define el objeto ClienteProveedor y el intercambio de información con el hydrator.
 */
class ClienteProveedor
{

    private $cli_pro_ruc;

    private $cli_pro_razon_social;

    private $cli_pro_nombre_comercial;

    private $cli_pro_direccion_matriz;

    private $cli_pro_telefono;

    private $cli_pro_proveedor;

    private $cli_pro_cliente;

    function __construct()
    {}

    /**
     *
     * @return the $cli_pro_ruc
     */
    public function getCli_pro_ruc()
    {
        return $this->cli_pro_ruc;
    }

    /**
     *
     * @return the $cli_pro_razon_social
     */
    public function getCli_pro_razon_social()
    {
        return $this->cli_pro_razon_social;
    }

    /**
     *
     * @return the $cli_pro_nombre_comercial
     */
    public function getCli_pro_nombre_comercial()
    {
        return $this->cli_pro_nombre_comercial;
    }

    /**
     *
     * @return the $cli_pro_direccion_matriz
     */
    public function getCli_pro_direccion_matriz()
    {
        return $this->cli_pro_direccion_matriz;
    }

    /**
     *
     * @return the $cli_pro_telefono
     */
    public function getCli_pro_telefono()
    {
        return $this->cli_pro_telefono;
    }

    /**
     *
     * @return the $cli_pro_proveedor
     */
    public function getCli_pro_proveedor()
    {
        return $this->cli_pro_proveedor;
    }

    /**
     *
     * @return the $cli_pro_cliente
     */
    public function getCli_pro_cliente()
    {
        return $this->cli_pro_cliente;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_ruc
     */
    public function setCli_pro_ruc($cli_pro_ruc)
    {
        $this->cli_pro_ruc = $cli_pro_ruc;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_razon_social
     */
    public function setCli_pro_razon_social($cli_pro_razon_social)
    {
        $this->cli_pro_razon_social = $cli_pro_razon_social;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_nombre_comercial
     */
    public function setCli_pro_nombre_comercial($cli_pro_nombre_comercial)
    {
        $this->cli_pro_nombre_comercial = $cli_pro_nombre_comercial;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_direccion_matriz
     */
    public function setCli_pro_direccion_matriz($cli_pro_direccion_matriz)
    {
        $this->cli_pro_direccion_matriz = $cli_pro_direccion_matriz;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_telefono
     */
    public function setCli_pro_telefono($cli_pro_telefono)
    {
        $this->cli_pro_telefono = $cli_pro_telefono;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_proveedor
     */
    public function setCli_pro_proveedor($cli_pro_proveedor)
    {
        $this->cli_pro_proveedor = $cli_pro_proveedor;
    }

    /**
     *
     * @param
     *            Ambigous <NULL, array> $cli_pro_cliente
     */
    public function setCli_pro_cliente($cli_pro_cliente)
    {
        $this->cli_pro_cliente = $cli_pro_cliente;
    }

    /**
     * Registra los atributos de clase mediante post o base de datos.
     *
     * @param array $data
     * @return void
     */
    public function exchangeArray($data)
    {
        $this->cli_pro_ruc = (isset($data['cli_pro_ruc'])) ? $data['cli_pro_ruc'] : null;
        $this->cli_pro_razon_social = (isset($data['cli_pro_razon_social'])) ? $data['cli_pro_razon_social'] : null;
        $this->cli_pro_nombre_comercial = (isset($data['cli_pro_nombre_comercial'])) ? $data['cli_pro_nombre_comercial'] : null;
        $this->cli_pro_direccion_matriz = (isset($data['cli_pro_direccion_matriz'])) ? $data['cli_pro_direccion_matriz'] : null;
        $this->cli_pro_telefono = (isset($data['cli_pro_telefono'])) ? $data['cli_pro_telefono'] : null;
        $this->cli_pro_proveedor = (isset($data['cli_pro_proveedor'])) ? $data['cli_pro_proveedor'] : null;
        $this->cli_pro_cliente = (isset($data['cli_pro_cliente'])) ? $data['cli_pro_cliente'] : null;
    }

    /**
     * Obtiene los valores de los atributos de clase para poblar el hydrator.
     *
     * @return array
     */
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }
}


text:
package com.agon.core.versioning;

import com.sun.jersey.spi.container.ContainerRequest;

public class DefaultApiVersionMatcher implements ApiVersionMatcher {
    private final String versionHeaderName;

    public DefaultApiVersionMatcher(String versionHeaderName) {
        this.versionHeaderName = versionHeaderName;
    }

    @Override
    public boolean supportsRequestedVersion(boolean headerRequired, float minVersion, float maxVersion, ContainerRequest request) {
        boolean isSupported = true;
        String versionHeader = request.getHeaderValue(versionHeaderName);
        if (headerRequiredButNotPresent(headerRequired, versionHeader) || headerPresentButNotSupported(minVersion, maxVersion, versionHeader)) {
            isSupported = false;
        }
        return isSupported;
    }

    private boolean headerIsPresent(String versionHeader) {
        return versionHeader != null && !versionHeader.isEmpty();
    }

    private boolean headerIsNotPresent(String versionHeader) {
        return !headerIsPresent(versionHeader);
    }

    private boolean headerRequiredButNotPresent(boolean headerRequired, String versionHeader) {
        return headerRequired && headerIsNotPresent(versionHeader);
    }

    private boolean headerPresentButNotSupported(float minVersion, float maxVersion, String versionHeader) {
        return headerIsPresent(versionHeader) && isInvalidOrNotSupported(minVersion, maxVersion, versionHeader);
    }

    private boolean isInvalidOrNotSupported(float minVersion, float maxVersion, String versionHeader) {
        return versionHeaderIsInvalidNumber(versionHeader) || !versionIsSupported(minVersion, maxVersion, Float.valueOf(versionHeader));
    }

    private boolean versionHeaderIsInvalidNumber(String versionHeader) {
        boolean invalid = false;
        try {
            Float.valueOf(versionHeader);
        } catch (NumberFormatException e) {
            invalid = true;
        }
        return invalid;
    }

    private boolean versionIsSupported(float minVersion, float maxVersion, float requestVersion) {
        return versionIsWithinMinLimit(minVersion, requestVersion) && versionIsWithinMaxLimit(maxVersion, requestVersion);
    }

    private boolean versionIsWithinMaxLimit(float maxVersion, float requestVersion) {
        return requestVersion <= maxVersion || maxVersion == ApiVersion.ALL_VERSION_SUPPORTED;
    }

    private boolean versionIsWithinMinLimit(float minVersion, float requestVersion) {
        return requestVersion >= minVersion || minVersion == ApiVersion.ALL_VERSION_SUPPORTED;
    }
}


text:
class BoolValue : public ShaderNode
{
	public:
		BoolValue(ShaderGraph& graph);
		~BoolValue() = default;

		nzsl::Ast::NodePtr BuildNode(nzsl::Ast::ExpressionPtr* expressions, std::size_t count, std::size_t outputIndex) const override;
		void BuildNodeEdition(QFormLayout* layout) override;

		QString caption() const override;
		QString name() const override;

		QtNodes::NodeDataType dataType(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const override;

		unsigned int nPorts(QtNodes::PortType portType) const override;

		std::shared_ptr<QtNodes::NodeData> outData(QtNodes::PortIndex port) override;

		QString portCaption(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const override;
		bool portCaptionVisible(QtNodes::PortType portType, QtNodes::PortIndex portIndex) const override;

	private:
		bool ComputePreview(QPixmap& pixmap) override;
		QColor ToColor() const;

		void restore(const QJsonObject& data) override;
		QJsonObject save() const override;

		bool m_value;
};

#include <ShaderNode/DataModels/BoolValue.inl>

#endif


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

/**
 * Creates an instance template that uses a provided subnet.
 *
 * @param {string} projectId - Project ID or project number of the Cloud project you use.
 * @param {string} network - The network to be used in the new template. This value uses
 *    the following format: "projects/{project}/global/networks/{network}"
 * @param {string} subnetwork - The subnetwork to be used in the new template. This value
 *    uses the following format: "projects/{project}/regions/{region}/subnetworks/{subnetwork}"
 * @param {string} templateName - Name of the new template to create.
 */
function main(projectId, network, subnetwork, templateName) {
  // [START compute_template_create_with_subnet]
  /**
   * TODO(developer): Uncomment and replace these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const network = 'projects/project/global/networks/network';
  // const subnetwork = 'projects/project/regions/region/subnetworks/subnetwork';
  // const templateName = 'your_template_name';

  const compute = require('@google-cloud/compute');

  // Create an instance template that uses a provided subnet.
  async function createTemplateWithSubnet() {
    const instanceTemplatesClient = new compute.InstanceTemplatesClient();

    const [response] = await instanceTemplatesClient.insert({
      project: projectId,
      instanceTemplateResource: {
        name: templateName,
        properties: {
          // The template describes the size and source image of the boot disk
          // to attach to the instance.
          disks: [
            {
              // The template describes the size and source image of the boot disk
              // to attach to the instance.
              initializeParams: {
                diskSizeGb: '250',
                sourceImage:
                  'projects/debian-cloud/global/images/family/debian-11',
              },
              autoDelete: true,
              boot: true,
            },
          ],
          machineType: 'e2-standard-4',
          // The template connects the instance to the specified network and subnetwork.
          networkInterfaces: [
            {
              network,
              subnetwork,
            },
          ],
        },
      },
    });
    let operation = response.latestResponse;
    const operationsClient = new compute.GlobalOperationsClient();

    // Wait for the create operation to complete.
    while (operation.status !== 'DONE') {
      [operation] = await operationsClient.wait({
        operation: operation.name,
        project: projectId,
      });
    }

    console.log('Instance template created.');
  }

  createTemplateWithSubnet();
  // [END compute_template_create_with_subnet]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

main(...process.argv.slice(2));


text:
package com.babylove.www.spring.ioc.demo1.dao;

public class InjectionDaoImpl implements InjectionDao{

	public void save(String args) {
		//模拟数据库保存操作
		System.out.println("保存数据:" + args);
	}

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class net.sourceforge.pmd.lang.dfa.report.AbstractReportNode (PMD 5.0.4 API)</title>
<meta name="date" content="2013-05-01">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.sourceforge.pmd.lang.dfa.report.AbstractReportNode

Packages that use AbstractReportNode

Package
Description

net.sourceforge.pmd.lang.dfa.report

Uses of AbstractReportNode in net.sourceforge.pmd.lang.dfa.report

Subclasses of AbstractReportNode in net.sourceforge.pmd.lang.dfa.report

Modifier and Type
Class and Description

class
ClassNode

class
PackageNode

class
ViolationNode

Methods in net.sourceforge.pmd.lang.dfa.report that return AbstractReportNode

Modifier and Type
Method and Description

AbstractReportNode
AbstractReportNode.getChildAt(int arg0)

AbstractReportNode
AbstractReportNode.getFirstChild()

AbstractReportNode
AbstractReportNode.getNextSibling()

AbstractReportNode
AbstractReportNode.getParent()

AbstractReportNode
ReportTree.getRootNode()

Methods in net.sourceforge.pmd.lang.dfa.report with parameters of type AbstractReportNode

Modifier and Type
Method and Description

void
AbstractReportNode.add(AbstractReportNode child)

Adds the child at the end.

void
AbstractReportNode.addFirst(AbstractReportNode child)

Adds the child in front of any other childs.

boolean
ViolationNode.equalsNode(AbstractReportNode arg0)

boolean
PackageNode.equalsNode(AbstractReportNode arg0)

boolean
ClassNode.equalsNode(AbstractReportNode arg0)

abstract boolean
AbstractReportNode.equalsNode(AbstractReportNode arg0)

Should compare to nodes of the tree.

void
ReportVisitor.visit(AbstractReportNode node)

void
ReportHTMLPrintVisitor.visit(AbstractReportNode node)

The visit method (Visitor Pattern).

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002-2013 InfoEther. All Rights Reserved.


text:
templateKey: 'programming'
date: '2018-10-09'
title: 'Clustering'
description: 'The basic of clustering algorithms'
image: '/img/programming/clustering/clustering.008.jpeg'
keywords: 'clustering,k-means,hierarchical agglomerative'
---

## Definition of clustering

Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar to each other than to those in other clusters.

Let's look at two basic and widely used clustering algorithms. hierarchical and k-means clusterings.

## The hierarchical clustering

Initially, each point is a cluster. Repeatedly combined the two nearest cluster into one.

![/img/programming/clustering/clustering.013.jpeg](/img/programming/clustering/clustering.013.jpeg "/img/programming/clustering/clustering.013.jpeg")

It's called Hierarchical agglomerative clustering.

The main output of Hierarchical Clustering is a dendrogram, which shows the hierarchical relationship between the clusters.

![/img/programming/clustering/clustering.014.jpeg](/img/programming/clustering/clustering.014.jpeg "/img/programming/clustering/clustering.014.jpeg")

## 3 Essential questions of HAC(Hierarchical agglomerative clustering)

Q 1 ) How should we represent cluster of more than one point?

- Euclidean space → Centroid = The average of its points.
- Non-Euclidean space → There is no "average". using clustroid(closet all other points in the cluster) not centroid.

Q 2 ) How should we determine the 'nearness' of clusters

- Euclidean space → Distances by distances of centroids.
- Non-Euclidean space → Distances by distances of clustroid.

Q 3 ) When should we stop combining clusters?

- If pick a number k upfront, We want data to falls into k classes.
- Before merging low cohesion clustering. Don't make bad clusters. The way to measure cohesion
    - Diameters: maximum distance in points
    - Radius: maximum distances from centroid(or clustroid)
    - Density: points per volumes(derived from diameters, radius)

## HAC Complexity

It's too slow. The standard algorithm for hierarchical agglomerative clustering (HAC) has a time complexity of O(n^3) and requires O(n^2)memory, which makes it too slow for even medium data sets.

## K-means clustering

1. Assuming Euclidean space/distance, start by picking **k**(number of clusters) clusters.
2. Assign points in the nearest cluster
3. After all points are assigned, update location of centroid of the **k** clusters**.**
4. Reassign all points to their closet centroid.  Sometimes moves points between clusters.
5. Repeat 3,4 util convergence. points and centroid don't move any further.

## How to select the right k clustering

- As the number of clustering increases. Average distance to centroid goes down.

![/img/programming/clustering/clustering.010.jpeg](/img/programming/clustering/clustering.010.jpeg "/img/programming/clustering/clustering.010.jpeg")

![/img/programming/clustering/clustering.011.jpeg](/img/programming/clustering/clustering.011.jpeg "/img/programming/clustering/clustering.011.jpeg")

![/img/programming/clustering/clustering.012.jpeg](/img/programming/clustering/clustering.012.jpeg "/img/programming/clustering/clustering.012.jpeg")

## How to pick initial centroids of clusters

1. Sampling then using hierarchical clustering to obtains k clusters.
2. Pick "dispersed" set of points.pick randomly first. then pick the next point which is as far as possible.

## K-means Complexity

O(kn) for N points, k clusters. linear goods. But the number of rounds to convergence can be  very large.

## Closing

Two alogrithms are basic and essential. There are many optimization techniques in dealing with data in the real world. However, many optimization techniques have often drived from these two basic algorithms. Therefore, these two concepts can be important as a foundation.

## reference

- [https://en.wikipedia.org/wiki/Cluster_analysis](https://en.wikipedia.org/wiki/Cluster_analysis)
- [https://en.wikipedia.org/wiki/Hierarchical_clustering](https://en.wikipedia.org/wiki/Hierarchical_clustering)
- [https://en.wikipedia.org/wiki/K-means_clustering](https://en.wikipedia.org/wiki/K-means_clustering)
- [https://www.displayr.com/what-is-hierarchical-clustering/](https://www.displayr.com/what-is-hierarchical-clustering/)
- [https://www.youtube.com/watch?v=rg2cjfMsCk4](https://www.youtube.com/watch?v=rg2cjfMsCk4)
- [https://www.youtube.com/watch?v=RD0nNK51Fp8](https://www.youtube.com/watch?v=RD0nNK51Fp8)


text:
package com.vaadin.navigator;

import java.io.Serializable;

import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Component;

/**
 * Interface for all views controlled by the navigator.
 *
 * Each view added to the navigator must implement this interface. Typically, a
 * view is a {@link Component}.
 *
 * @author Vaadin Ltd
 * @since 7.0
 */
public interface View extends Serializable {

    /**
     * This view is navigated to.
     *
     * This method is always called before the view is shown on screen.
     * {@link ViewChangeEvent#getParameters() event.getParameters()} may contain
     * extra parameters relevant to the view.
     *
     * @param event
     *            ViewChangeEvent representing the view change that is
     *            occurring. {@link ViewChangeEvent#getNewView()
     *            event.getNewView()} returns this.
     *
     */
    public void enter(ViewChangeEvent event);
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

 Copyright 2003 - 2016 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

-->
<ui-table xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>123b3e36-4535-4bc2-a64f-b87d2ecbe0dd</uuid>
    <file-application>eFapsApp-Accounting</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Accounting_PeriodIncomingExchangeTable</name>
        <field name="type">
            <property name="Attribute">Type</property>
            <property name="HRef">TREE</property>
            <property name="Label">Sales_Exchange/Type.Label</property>
            <property name="ShowTypeIcon">true</property>
        </field>
        <field name="name">
            <property name="Attribute">Name</property>
            <property name="Label">Sales_DocumentAbstract/Name.Label</property>
        </field>
        <field name="contact">
            <property name="SelectAlternateOID">linkto[Contact].oid</property>
            <property name="HRef">TREE</property>
            <property name="Select">linkto[Contact].attribute[Name]</property>
            <property name="Label">Sales_DocumentAbstract/Contact.Label</property>
            <property name="FilterType">PICKLIST</property>
        </field>
        <field name="date">
            <property name="FilterType">FREETEXT</property>
            <property name="FilterRequired">TRUE</property>
            <property name="FilterBase">DATABASE</property>
            <property name="FilterDefault">MONTH</property>
            <property name="Attribute">Date</property>
            <property name="Label">Sales_Exchange/Date.Label</property>
        </field>
        <field name="dueDate">
            <property name="Attribute">DueDate</property>
            <property name="Label">Sales_Exchange/DueDate.Label</property>
        </field>
        <field name="crosstotal">
            <property name="MsgPhrase">Accounting_CrossTotalMsgPhrase</property>
            <property name="UIProvider">org.efaps.admin.datamodel.ui.StringUI</property>
            <property name="Label">Sales_Exchange/CrossTotal.Label</property>
            <property name="SortSelect">attribute[CrossTotal]</property>
            <property name="Align">right</property>
        </field>
        <field name="rateCrosstotal">
            <property name="MsgPhrase">Accounting_RateCrossTotalMsgPhrase</property>
            <property name="UIProvider">org.efaps.admin.datamodel.ui.StringUI</property>
            <property name="Label">Sales_Exchange/RateCrossTotal.Label</property>
            <property name="SortSelect">attribute[RateCrossTotal]</property>
            <property name="Align">right</property>
        </field>
        <field name="status">
            <property name="Attribute">StatusAbstract</property>
            <property name="Label">Sales_DocumentAbstract/Status.Label</property>
            <property name="FilterType">PICKLIST</property>
        </field>
        <field name="action4View">
            <property name="SelectAlternateOID">linkfrom[Sales_ActionDefinitionIncomingExchange2Document#ToLinkAbstract].linkto[FromLinkAbstract].oid</property>
            <property name="Select">linkfrom[Sales_ActionDefinitionIncomingExchange2Document#ToLinkAbstract].linkto[FromLinkAbstract].attribute[Name]</property>
            <property name="HRef">TREE</property>
            <property name="Label">Sales_IncomingExchange_AssignActionForm.action.Label</property>
            <property name="UIProvider">org.efaps.admin.datamodel.ui.StringUI</property>
            <property name="FilterType">PICKLIST</property>
            <trigger event="UI_ACCESSCHECK" method="accessCheck4Action"
                name="Sales_IncomingInvoiceForm.action4View.UI_ACCESSCHECK"
                program="org.efaps.esjp.sales.document.IncomingExchange">
                <property name="Key">Sales_IncomingExchange</property>
                <property name="Access">!NONE</property>
            </trigger>
        </field>
        <field name="actionDate4View">
            <property name="Select">linkfrom[Sales_ActionDefinitionIncomingExchange2Document#ToLinkAbstract].attribute[Date]</property>
            <property name="Label">Sales_IncomingExchange_AssignActionForm.date.Label</property>
            <trigger event="UI_ACCESSCHECK" method="accessCheck4Action"
                name="Sales_InvoiceForm.action4View.UI_ACCESSCHECK"
                program="org.efaps.esjp.sales.document.IncomingExchange">
                <property name="Key">Sales_IncomingExchange</property>
                <property name="Access">!NONE</property>
            </trigger>
        </field>
        <field name="creator">
            <property name="FilterType">PICKLIST</property>
            <property name="Attribute">Creator</property>
            <property name="Label">Sales_IncomingExchange/Creator.Label</property>
        </field>
        <field name="bin">
            <property name="Label">Sales_BinIncomingExchange.Label</property>
            <property name="SelectAlternateOID">linkfrom[Sales_BinIncomingExchange2IncomingExchange#ToLink].linkto[FromLink].oid</property>
            <property name="Select">linkfrom[Sales_BinIncomingExchange2IncomingExchange#ToLink].linkto[FromLink].attribute[Name]</property>
            <property name="HRef">TREE</property>
            <property name="FilterType">PICKLIST</property>
            <trigger program="org.efaps.esjp.admin.access.AccessCheck4UI"
                method="configCheck"
                name="Accounting_PeriodIncomingExchangeTable.bin.UI_ACCESSCHECK"
                event="UI_ACCESSCHECK">
                <!-- Sales-Config -->
                <property name="SystemConfig">c9a1cbc3-fd35-4463-80d2-412422a3802f</property>
                <property name="Attribute">org.efaps.sales.BinIncomingExchange.Activate</property>
            </trigger>
        </field>
    </definition>
</ui-table>


text:
package util

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/containers/podman/v3/pkg/timetype"
	"github.com/pkg/errors"
)

// ComputeUntilTimestamp extracts until timestamp from filters
func ComputeUntilTimestamp(filterValues []string) (time.Time, error) {
	invalid := time.Time{}
	if len(filterValues) != 1 {
		return invalid, errors.Errorf("specify exactly one timestamp for until")
	}
	ts, err := timetype.GetTimestamp(filterValues[0], time.Now())
	if err != nil {
		return invalid, err
	}
	seconds, nanoseconds, err := timetype.ParseTimestamps(ts, 0)
	if err != nil {
		return invalid, err
	}
	return time.Unix(seconds, nanoseconds), nil
}

// filtersFromRequests extracts the "filters" parameter from the specified
// http.Request.  The parameter can either be a `map[string][]string` as done
// in new versions of Docker and libpod, or a `map[string]map[string]bool` as
// done in older versions of Docker.  We have to do a bit of Yoga to support
// both - just as Docker does as well.
//
// Please refer to https://github.com/containers/podman/issues/6899 for some
// background.
func FiltersFromRequest(r *http.Request) ([]string, error) {
	var (
		compatFilters map[string]map[string]bool
		filters       map[string][]string
		libpodFilters []string
		raw           []byte
	)

	if _, found := r.URL.Query()["filters"]; found {
		raw = []byte(r.Form.Get("filters"))
	} else if _, found := r.URL.Query()["Filters"]; found {
		raw = []byte(r.Form.Get("Filters"))
	} else {
		return []string{}, nil
	}

	// Backwards compat with older versions of Docker.
	if err := json.Unmarshal(raw, &compatFilters); err == nil {
		for filterKey, filterMap := range compatFilters {
			for filterValue, toAdd := range filterMap {
				if toAdd {
					libpodFilters = append(libpodFilters, fmt.Sprintf("%s=%s", filterKey, filterValue))
				}
			}
		}
		return libpodFilters, nil
	}

	if err := json.Unmarshal(raw, &filters); err != nil {
		return nil, err
	}

	for filterKey, filterSlice := range filters {
		for _, filterValue := range filterSlice {
			libpodFilters = append(libpodFilters, fmt.Sprintf("%s=%s", filterKey, filterValue))
		}
	}

	return libpodFilters, nil
}

// PrepareFilters prepares a *map[string][]string of filters to be later searched
// in lipod and compat API to get desired filters
func PrepareFilters(r *http.Request) (*map[string][]string, error) {
	filtersList, err := FiltersFromRequest(r)
	if err != nil {
		return nil, err
	}
	filterMap := map[string][]string{}
	for _, filter := range filtersList {
		split := strings.SplitN(filter, "=", 2)
		if len(split) > 1 {
			filterMap[split[0]] = append(filterMap[split[0]], split[1])
		}
	}
	return &filterMap, nil
}

// MatchLabelFilters matches labels and returns true if they are valid
func MatchLabelFilters(filterValues []string, labels map[string]string) bool {
outer:
	for _, filterValue := range filterValues {
		filterArray := strings.SplitN(filterValue, "=", 2)
		filterKey := filterArray[0]
		if len(filterArray) > 1 {
			filterValue = filterArray[1]
		} else {
			filterValue = ""
		}
		for labelKey, labelValue := range labels {
			if labelKey == filterKey && (filterValue == "" || labelValue == filterValue) {
				continue outer
			}
		}
		return false
	}
	return true
}


text:
---
layout: post
comments: true
title: java.nio.files.Files.lines에 대한 탐구
tags: [java, nio, file]
---

### OOM이 터질수 있는 File read 인가

File에 존재하는 line count 를 구하기 위해 아래 메서드를 사용해 보았습니다.

```java
try(Stream<String> lines = Files.lines(path))
{
  count = lines.count();
}
```

위 코드를 PR올린 후 팀원분께서 '혹시 사이즈가 큰 파일을 받게되면 OOM이 터지지 수 있을까요?' 라는 리뷰를 남겨주셨습니다.

---

### 관련문서

> Read all lines from a file as a Stream. Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.
>
> Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by readAllLines are supported.
>
> The returned stream contains a reference to an open file. The file is closed by closing the stream.
>
> The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
>
> After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the Stream method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException.

본문 : https://docs.oracle.com/javase/9/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-

해당 메서드를 설명하는 문서상으로는 `Files.readAllLines()`과는 다르게 모든 행을 List로 읽는 대신 `Lazy production Stream`을 통해 전체 파일을 읽는다고 명확하게 설명이 나와있습니다.

---

### 실제 테스트

```java
public int totalProductCount()
{
    initializeCheck();

    int rowCount;
    try (Stream<String> fileStream = Files.lines(this.filePath))
    {
        rowCount = (int) fileStream.count() - 1;
    }
    catch (Exception e)
    {
        throw new EpException(ErrorCodes.EP_FILE_ERROR, e);
    }

    return rowCount;
}
```

위 의 코드를 통해 실제 메모리 사용량을 테스트 해보았습니다.

#### Test 1 → 500만건 (File 용량 : 3.82GB)
![1]({{ site.images | relative_url }}/posts/2020-12-01-java-nio-files-lines/1.png)

- (테스트 과정중 파일 다운로드가 포함되어 있음)
- 메모리 사용량 100MB 이하로 빠르게 수행됨

#### Test 2 → 5000만건 (File 용량 : 24.42GB)
![2]({{ site.images | relative_url }}/posts/2020-12-01-java-nio-files-lines/2.png)

- (테스트 과정중 파일 다운로드가 포함되어 있음)
- 메모리 사용량 100MB 이하로 빠르게 수행됨

#### 결론

- File stream 으로 제공되어 OOM에서 안전하게 File read 가능함
- 내부적으로 BufferReader를 통해 reader stream 열어서 제공됨

---

### 내부 코드 분석

위 제공받는 `Stream`은 실제로 비동기 로직에서 `Stream`을 제공받듯이 file을 read 하고 있습니다.
순수 자바코드로 어떻게 File을 `Stream`으로 제공 할 수 있는지 내부 코드를 분석해보도록 하겠습니다.

```java
// java.nio.files.Files

public static Stream<String> lines(Path path, Charset cs) throws IOException {
    BufferedReader br = Files.newBufferedReader(path, cs);
    try {
        return br.lines().onClose(asUncheckedRunnable(br));
    } catch (Error|RuntimeException e) {
        try {
            br.close();
        } catch (IOException ex) {
            try {
                e.addSuppressed(ex);
            } catch (Throwable ignore) {}
        }
        throw e;
    }
}
```

```java
// java.io.BufferedReader

public Stream<String> lines() {
    Iterator<String> iter = new Iterator<String>() {
        String nextLine = null;

        @Override
        public boolean hasNext() {
            if (nextLine != null) {
                return true;
            } else {
                try {
                    nextLine = readLine();
                    return (nextLine != null);
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }
        }

        @Override
        public String next() {
            if (nextLine != null || hasNext()) {
                String line = nextLine;
                nextLine = null;
                return line;
            } else {
                throw new NoSuchElementException();
            }
        }
    };
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}
```

```java
// java.util.stream

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) {
    Objects.requireNonNull(spliterator);
    return new ReferencePipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator),  parallel);
}

```

```java
// Java.util.Spliterators

public static <T> Spliterator<T> spliteratorUnknownSize(Iterator<? extends T> iterator,
                                                        int characteristics) {
    return new IteratorSpliterator<>(Objects.requireNonNull(iterator), characteristics);
}

```

```java
/**
 * Source stage of a ReferencePipeline.
 *
 * @param <E_IN> type of elements in the upstream source
 * @param <E_OUT> type of elements in produced by this stage
 * @since 1.8
 */
static class Head<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> {
...
}

abstract class ReferencePipeline<P_IN, P_OUT>
        extends AbstractPipeline<P_IN, P_OUT, Stream<P_OUT>>
        implements Stream<P_OUT> {
...
}
```


text:
<?php

namespace Panel\CtrlwBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * Usuarios
 *
 * @ORM\Table(name="usuarios")
 * @ORM\Entity
 */
class Usuarios extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }

}


text:
package com.milleapplis.ovh.api.sms.enums;

import com.fasterxml.jackson.annotation.JsonValue;

public enum SMSWayTypeEnum {
	INCOMING("incoming"),
	OUTGOING("outgoing");

	private String priority;

	private SMSWayTypeEnum(String priority) {
		this.priority = priority;
	}

	@JsonValue
	public String toString() {
		return priority;
	}

	@JsonValue
	public SMSWayTypeEnum fromString(String value) {
		if (value == null) {
			return null;
		}
		for (SMSWayTypeEnum currentPriority : SMSWayTypeEnum.values()) {
			if (value.equals(currentPriority.toString())) {
				return currentPriority;
			}
		}
		return null;
	}
}