text:
package edu.wpi.first.wpilib.plugins.cpp.launching;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Vector;

import org.eclipse.core.internal.resources.Resource;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;

import edu.wpi.first.wpilib.plugins.core.launching.AntLauncher;
import edu.wpi.first.wpilib.plugins.core.launching.SimulationNotification;
import edu.wpi.first.wpilib.plugins.cpp.WPILibCPPPlugin;

/**
 * Launch shortcut base functionality, common for deploying to the robot.
 * Retrieves the project the operation is being called on, and runs the correct
 * ant targets based on polymorphically determined data values
 *
 * @author Ryan O'Meara
 * @author Alex Henning
 */
@SuppressWarnings("restriction")
public class SimulateLaunchShortcut implements ILaunchShortcut {
	//Class constants - used to delineate types for launch shortcuts
	public static final String DEPLOY_TYPE = "edu.wpi.first.wpilib.plugins.core.deploy";
	private static final String ANT_SERVER_THREAD_NAME = "Ant Build Server Connection";

	private static ILaunch lastDeploy = null;

	/**
	 * Returns the launch type of the shortcut that was used, one of the constants
	 * defined in BaseLaunchShortcut
	 * @return Launch shortcut type
	 */
	public String getLaunchType() {return DEPLOY_TYPE;}

	@Override
	public void launch(ISelection selection, String mode) {
		//Extract resource from selection
		StructuredSelection sel = (StructuredSelection)selection;
		IProject activeProject = null;
		if (sel.getFirstElement() instanceof IProject) {
			activeProject = (IProject) sel.getFirstElement();
		} else {
			return;
		}

        //Run config using project found in extracted resource, with indicated mode
        runConfig(activeProject, mode);
	}

	@Override
	public void launch(IEditorPart editor, String mode) {
		//Extract resource from editor
		if(editor  != null){
		    IFileEditorInput input = (IFileEditorInput)editor.getEditorInput();
		    IFile file = input.getFile();
		    IProject activeProject = file.getProject();

		    //If editor existed, run config using extracted resource in indicated mode
		    runConfig(activeProject, mode);
		}else{
			System.err.println("editor was null");
		}

	}

	/**
	 * Runs the ant script using the correct target for the indicated mode (deploy to cRIO or just compile)
	 * @param activeProj The project that the script will be run on/from
	 * @param mode The mode it will be run in (ILaunchManager.RUN_MODE or ILaunchManager.DEBUG_MODE)
	 */
	public void runConfig(IProject activeProj, String mode) {
		if (!SimulationNotification.supportsSimulation()) {
			SimulationNotification.showUnsupported();
		}

		String targets = "simulate";

		if(mode.equals(ILaunchManager.RUN_MODE)){
			if(getLaunchType().equals(DEPLOY_TYPE)){
				targets = "simulate";
			}
		} else if ((mode.equals(ILaunchManager.DEBUG_MODE))&&(getLaunchType().equals(DEPLOY_TYPE))) {
			targets = "debug-simulate";
			try{
				PlatformUI.getWorkbench().showPerspective(IDebugUIConstants.ID_DEBUG_PERSPECTIVE,
					PlatformUI.getWorkbench().getActiveWorkbenchWindow());

			}catch(Exception e){}
		}

		if((lastDeploy != null)&&(!lastDeploy.isTerminated())){
			WPILibCPPPlugin.logInfo("Last deploy running");
			// Find the server connection thread and kill it
			Vector<ThreadGroup> threadGroups = new Vector<ThreadGroup>();
	        ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
	        while (root.getParent() != null) {root = root.getParent();}
	        threadGroups.add(root);
	        ThreadGroup threadGroup = threadGroups.remove(0);
	        int numThreads = threadGroup.activeCount();
	        Thread[] threads = new Thread[numThreads*100];
            numThreads = threadGroup.enumerate(threads, true);

            for(Thread current: threads){
            	if(current != null){
            		if(current.getName().equals(ANT_SERVER_THREAD_NAME)){
            			try {
            				// Manually end thread and then try terminating launch
            				Method stopMethod = current.getClass().getMethod("stop");
            				stopMethod.invoke(current);
            				lastDeploy.terminate();
            				break;
            			} catch(Exception e){
                          WPILibCPPPlugin.logError("Error killing ant thread.", e);
                        }
            		}
            	}
            }

            WPILibCPPPlugin.logInfo("Waiting");
            try{wait(1000);}catch(Exception e){}
		}

		WPILibCPPPlugin.logInfo("Running ant file: " + activeProj.getLocation().toOSString() + File.separator + "build.xml");
		WPILibCPPPlugin.logInfo("Targets: " + targets + ", Mode: " + mode);
		lastDeploy = AntLauncher.runAntFile(new File (activeProj.getLocation().toOSString() + File.separator + "build.xml"), targets, null, mode);

		try {
			activeProj.refreshLocal(Resource.DEPTH_INFINITE, null);
		} catch (Exception e) {}
	}
}


text:
package com.nabijaczleweli.minecrasmer.compat

import com.nabijaczleweli.minecrasmer.reference.Reference
import net.minecraft.nbt.NBTTagCompound
import net.minecraftforge.fluids.FluidRegistry
import net.minecraftforge.fml.common.event.FMLInterModComms
import net.minecraftforge.fml.relauncher.Side

class Vanilla extends ICompat {
	override def getModIDs =
		Nil

	override def preLoad(side: Side) =
		Empty

	override def load(side: Side) = {
		val nbt = new NBTTagCompound

		nbt.setString("fluid_name", FluidRegistry.LAVA.getName)
		nbt.setInteger("color", 0xEC0808)
		FMLInterModComms.sendMessage(Reference.MOD_ID, "register-scoop", nbt.copy.asInstanceOf[NBTTagCompound])

		nbt.setString("fluid_name", FluidRegistry.WATER.getName)
		nbt.setInteger("color", 0x344DF4)
		FMLInterModComms.sendMessage(Reference.MOD_ID, "register-scoop", nbt.copy.asInstanceOf[NBTTagCompound])

		Successful
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace history {

namespace {

// Fields used by FillInStarredEntry.
#define STAR_FIELDS \
    " starred.id, starred.type, starred.title, starred.date_added, " \
    "starred.visual_order, starred.parent_id, urls.url, urls.id, " \
    "starred.group_id, starred.date_modified "
const char kHistoryStarFields[] = STAR_FIELDS;

void FillInStarredEntry(const sql::Statement& s, StarredEntry* entry) {
  DCHECK(entry);
  entry->id = s.ColumnInt64(0);
  switch (s.ColumnInt(1)) {
    case 0:
      entry->type = history::StarredEntry::URL;
      entry->url = GURL(s.ColumnString(6));
      break;
    case 1:
      entry->type = history::StarredEntry::BOOKMARK_BAR;
      break;
    case 2:
      entry->type = history::StarredEntry::USER_FOLDER;
      break;
    case 3:
      entry->type = history::StarredEntry::OTHER;
      break;
    default:
      NOTREACHED();
      break;
  }
  entry->title = s.ColumnString16(2);
  entry->date_added = base::Time::FromInternalValue(s.ColumnInt64(3));
  entry->visual_order = s.ColumnInt(4);
  entry->parent_folder_id = s.ColumnInt64(5);
  entry->url_id = s.ColumnInt64(7);
  entry->folder_id = s.ColumnInt64(8);
  entry->date_folder_modified = base::Time::FromInternalValue(s.ColumnInt64(9));
}

}  // namespace

StarredURLDatabase::StarredURLDatabase() {
}

StarredURLDatabase::~StarredURLDatabase() {
}

bool StarredURLDatabase::MigrateBookmarksToFile(const FilePath& path) {
  if (!GetDB().DoesTableExist("starred"))
    return true;

  if (EnsureStarredIntegrity() && !MigrateBookmarksToFileImpl(path)) {
    NOTREACHED() << " Bookmarks migration failed";
    return false;
  }

  if (!GetDB().Execute("DROP TABLE starred")) {
    NOTREACHED() << "Unable to drop starred table";
    return false;
  }
  return true;
}

bool StarredURLDatabase::GetAllStarredEntries(
    std::vector<StarredEntry>* entries) {
  DCHECK(entries);
  std::string sql = "SELECT ";
  sql.append(kHistoryStarFields);
  sql.append("FROM starred LEFT JOIN urls ON starred.url_id = urls.id ");
  sql += "ORDER BY parent_id, visual_order";

  sql::Statement s(GetDB().GetUniqueStatement(sql.c_str()));
  if (!s) {
    NOTREACHED() << "Statement prepare failed";
    return false;
  }

  history::StarredEntry entry;
  while (s.Step()) {
    FillInStarredEntry(s, &entry);
    // Reset the url for non-url types. This is needed as we're reusing the
    // same entry for the loop.
    if (entry.type != history::StarredEntry::URL)
      entry.url = GURL();
    entries->push_back(entry);
  }
  return true;
}

bool StarredURLDatabase::EnsureStarredIntegrity() {
  std::set<StarredNode*> roots;
  std::set<StarID> folders_with_duplicate_ids;
  std::set<StarredNode*> unparented_urls;
  std::set<StarID> empty_url_ids;

  if (!BuildStarNodes(&roots, &folders_with_duplicate_ids, &unparented_urls,
                      &empty_url_ids)) {
    return false;
  }

  bool valid = EnsureStarredIntegrityImpl(&roots, folders_with_duplicate_ids,
                                          &unparented_urls, empty_url_ids);

  STLDeleteElements(&roots);
  STLDeleteElements(&unparented_urls);
  return valid;
}

bool StarredURLDatabase::UpdateStarredEntryRow(StarID star_id,
                                               const string16& title,
                                               UIStarID parent_folder_id,
                                               int visual_order,
                                               base::Time date_modified) {
  DCHECK(star_id && visual_order >= 0);
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "UPDATE starred SET title=?, parent_id=?, visual_order=?, "
      "date_modified=? WHERE id=?"));
  if (!statement)
    return 0;

  statement.BindString16(0, title);
  statement.BindInt64(1, parent_folder_id);
  statement.BindInt(2, visual_order);
  statement.BindInt64(3, date_modified.ToInternalValue());
  statement.BindInt64(4, star_id);
  return statement.Run();
}

bool StarredURLDatabase::AdjustStarredVisualOrder(UIStarID parent_folder_id,
                                                  int start_visual_order,
                                                  int delta) {
  DCHECK(parent_folder_id && start_visual_order >= 0);
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "UPDATE starred SET visual_order=visual_order+? "
      "WHERE parent_id=? AND visual_order >= ?"));
  if (!statement)
    return false;

  statement.BindInt(0, delta);
  statement.BindInt64(1, parent_folder_id);
  statement.BindInt(2, start_visual_order);
  return statement.Run();
}

StarID StarredURLDatabase::CreateStarredEntryRow(URLID url_id,
                                                 UIStarID folder_id,
                                                 UIStarID parent_folder_id,
                                                 const string16& title,
                                                 const base::Time& date_added,
                                                 int visual_order,
                                                 StarredEntry::Type type) {
  DCHECK(visual_order >= 0 &&
         (type != history::StarredEntry::URL || url_id));
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "INSERT INTO starred "
      "(type, url_id, group_id, title, date_added, visual_order, parent_id, "
      "date_modified) VALUES (?,?,?,?,?,?,?,?)"));
  if (!statement)
    return 0;

  switch (type) {
    case history::StarredEntry::URL:
      statement.BindInt(0, 0);
      break;
    case history::StarredEntry::BOOKMARK_BAR:
      statement.BindInt(0, 1);
      break;
    case history::StarredEntry::USER_FOLDER:
      statement.BindInt(0, 2);
      break;
    case history::StarredEntry::OTHER:
      statement.BindInt(0, 3);
      break;
    default:
      NOTREACHED();
  }
  statement.BindInt64(1, url_id);
  statement.BindInt64(2, folder_id);
  statement.BindString16(3, title);
  statement.BindInt64(4, date_added.ToInternalValue());
  statement.BindInt(5, visual_order);
  statement.BindInt64(6, parent_folder_id);
  statement.BindInt64(7, base::Time().ToInternalValue());
  if (statement.Run())
    return GetDB().GetLastInsertRowId();
  return 0;
}

bool StarredURLDatabase::DeleteStarredEntryRow(StarID star_id) {
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "DELETE FROM starred WHERE id=?"));
  if (!statement)
    return false;

  statement.BindInt64(0, star_id);
  return statement.Run();
}

bool StarredURLDatabase::GetStarredEntry(StarID star_id, StarredEntry* entry) {
  DCHECK(entry && star_id);
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" STAR_FIELDS "FROM starred LEFT JOIN urls ON "
      "starred.url_id = urls.id WHERE starred.id=?"));
  if (!statement)
    return false;

  statement.BindInt64(0, star_id);

  if (statement.Step()) {
    FillInStarredEntry(statement, entry);
    return true;
  }
  return false;
}

StarID StarredURLDatabase::CreateStarredEntry(StarredEntry* entry) {
  entry->id = 0;  // Ensure 0 for failure case.

  // Adjust the visual order when we are inserting it somewhere.
  if (entry->parent_folder_id)
    AdjustStarredVisualOrder(entry->parent_folder_id, entry->visual_order, 1);

  // Insert the new entry.
  switch (entry->type) {
    case StarredEntry::USER_FOLDER:
      entry->id = CreateStarredEntryRow(0, entry->folder_id,
          entry->parent_folder_id, entry->title, entry->date_added,
          entry->visual_order, entry->type);
      break;

    case StarredEntry::URL: {
      // Get the row for this URL.
      URLRow url_row;
      if (!GetRowForURL(entry->url, &url_row)) {
        // Create a new URL row for this entry.
        url_row = URLRow(entry->url);
        url_row.set_title(entry->title);
        url_row.set_hidden(false);
        entry->url_id = this->AddURL(url_row);
      } else {
        entry->url_id = url_row.id();  // The caller doesn't have to set this.
      }

      // Create the star entry referring to the URL row.
      entry->id = CreateStarredEntryRow(entry->url_id, entry->folder_id,
          entry->parent_folder_id, entry->title, entry->date_added,
          entry->visual_order, entry->type);

      // Update the URL row to refer to this new starred entry.
      UpdateURLRow(entry->url_id, url_row);
      break;
    }

    default:
      NOTREACHED();
      break;
  }
  return entry->id;
}

UIStarID StarredURLDatabase::GetMaxFolderID() {
  sql::Statement max_folder_id_statement(GetDB().GetUniqueStatement(
      "SELECT MAX(group_id) FROM starred"));
  if (!max_folder_id_statement) {
    NOTREACHED() << GetDB().GetErrorMessage();
    return 0;
  }
  if (!max_folder_id_statement.Step()) {
    NOTREACHED() << GetDB().GetErrorMessage();
    return 0;
  }
  return max_folder_id_statement.ColumnInt64(0);
}

bool StarredURLDatabase::BuildStarNodes(
    std::set<StarredURLDatabase::StarredNode*>* roots,
    std::set<StarID>* folders_with_duplicate_ids,
    std::set<StarredNode*>* unparented_urls,
    std::set<StarID>* empty_url_ids) {
  std::vector<StarredEntry> star_entries;
  if (!GetAllStarredEntries(&star_entries)) {
    NOTREACHED() << "Unable to get bookmarks from database";
    return false;
  }

  // Create the folder/bookmark-bar/other nodes.
  std::map<UIStarID, StarredNode*> folder_id_to_node_map;
  for (size_t i = 0; i < star_entries.size(); ++i) {
    if (star_entries[i].type != StarredEntry::URL) {
      if (folder_id_to_node_map.find(star_entries[i].folder_id) !=
          folder_id_to_node_map.end()) {
        // There's already a folder with this ID.
        folders_with_duplicate_ids->insert(star_entries[i].id);
      } else {
        // Create the node and update the mapping.
        StarredNode* node = new StarredNode(star_entries[i]);
        folder_id_to_node_map[star_entries[i].folder_id] = node;
      }
    }
  }

  // Iterate again, creating nodes for URL bookmarks and parenting all
  // bookmarks/folders. In addition populate the empty_url_ids with all entries
  // of type URL that have an empty URL.
  std::map<StarID, StarredNode*> id_to_node_map;
  for (size_t i = 0; i < star_entries.size(); ++i) {
    if (star_entries[i].type == StarredEntry::URL) {
      if (star_entries[i].url.is_empty()) {
        empty_url_ids->insert(star_entries[i].id);
      } else if (!star_entries[i].parent_folder_id ||
          folder_id_to_node_map.find(star_entries[i].parent_folder_id) ==
          folder_id_to_node_map.end()) {
        // This entry has no parent, or we couldn't find the parent.
        StarredNode* node = new StarredNode(star_entries[i]);
        unparented_urls->insert(node);
      } else {
        // Add the node to its parent.
        StarredNode* parent =
            folder_id_to_node_map[star_entries[i].parent_folder_id];
        StarredNode* node = new StarredNode(star_entries[i]);
        parent->Add(node, parent->child_count());
      }
    } else if (folders_with_duplicate_ids->find(star_entries[i].id) ==
               folders_with_duplicate_ids->end()) {
      // The entry is a folder (or bookmark bar/other node) that isn't
      // marked as a duplicate.
      if (!star_entries[i].parent_folder_id ||
          folder_id_to_node_map.find(star_entries[i].parent_folder_id) ==
          folder_id_to_node_map.end()) {
        // Entry has no parent, or the parent wasn't found.
        roots->insert(folder_id_to_node_map[star_entries[i].folder_id]);
      } else {
        // Parent the folder node.
        StarredNode* parent =
            folder_id_to_node_map[star_entries[i].parent_folder_id];
        StarredNode* node = folder_id_to_node_map[star_entries[i].folder_id];
        if (!node->HasAncestor(parent) && !parent->HasAncestor(node)) {
          parent->Add(node, parent->child_count());
        } else {
          // The node has a cycle. Add it to the list of roots so the cycle is
          // broken.
          roots->insert(node);
        }
      }
    }
  }
  return true;
}

StarredURLDatabase::StarredNode* StarredURLDatabase::GetNodeByType(
    const std::set<StarredURLDatabase::StarredNode*>& nodes,
    StarredEntry::Type type) {
  for (std::set<StarredNode*>::const_iterator i = nodes.begin();
       i != nodes.end(); ++i) {
    if ((*i)->value.type == type)
      return *i;
  }
  return NULL;
}

bool StarredURLDatabase::EnsureVisualOrder(
    StarredURLDatabase::StarredNode* node) {
  for (int i = 0; i < node->child_count(); ++i) {
    if (node->GetChild(i)->value.visual_order != i) {
      StarredEntry& entry = node->GetChild(i)->value;
      entry.visual_order = i;
      LOG(WARNING) << "Bookmark visual order is wrong";
      if (!UpdateStarredEntryRow(entry.id, entry.title, entry.parent_folder_id,
                                 i, entry.date_folder_modified)) {
        NOTREACHED() << "Unable to update visual order";
        return false;
      }
    }
    if (!EnsureVisualOrder(node->GetChild(i)))
      return false;
  }
  return true;
}

bool StarredURLDatabase::EnsureStarredIntegrityImpl(
    std::set<StarredURLDatabase::StarredNode*>* roots,
    const std::set<StarID>& folders_with_duplicate_ids,
    std::set<StarredNode*>* unparented_urls,
    const std::set<StarID>& empty_url_ids) {
  // Make sure the bookmark bar entry exists.
  StarredNode* bookmark_node =
      GetNodeByType(*roots, StarredEntry::BOOKMARK_BAR);
  if (!bookmark_node) {
    LOG(WARNING) << "No bookmark bar folder in database";
    // If there is no bookmark bar entry in the db things are really
    // screwed. Return false, which won't trigger migration and we'll just
    // drop the tables.
    return false;
  }

  // Make sure the other node exists.
  StarredNode* other_node = GetNodeByType(*roots, StarredEntry::OTHER);
  if (!other_node) {
    LOG(WARNING) << "No bookmark other folder in database";
    StarredEntry entry;
    entry.folder_id = GetMaxFolderID() + 1;
    if (entry.folder_id == 1) {
      NOTREACHED() << "Unable to get new id for other bookmarks folder";
      return false;
    }
    entry.id = CreateStarredEntryRow(
        0, entry.folder_id, 0, UTF8ToUTF16("other"), base::Time::Now(), 0,
        history::StarredEntry::OTHER);
    if (!entry.id) {
      NOTREACHED() << "Unable to create other bookmarks folder";
      return false;
    }
    entry.type = StarredEntry::OTHER;
    StarredNode* other_node = new StarredNode(entry);
    roots->insert(other_node);
  }

  // We could potentially make sure only one folder with type
  // BOOKMARK_BAR/OTHER, but history backend enforces this.

  // Nuke any entries with no url.
  for (std::set<StarID>::const_iterator i = empty_url_ids.begin();
       i != empty_url_ids.end(); ++i) {
    LOG(WARNING) << "Bookmark exists with no URL";
    if (!DeleteStarredEntryRow(*i)) {
      NOTREACHED() << "Unable to delete bookmark";
      return false;
    }
  }

  // Make sure the visual order of the nodes is correct.
  for (std::set<StarredNode*>::const_iterator i = roots->begin();
       i != roots->end(); ++i) {
    if (!EnsureVisualOrder(*i))
      return false;
  }

  // Move any unparented bookmarks to the bookmark bar.
  {
    std::set<StarredNode*>::iterator i = unparented_urls->begin();
    while (i != unparented_urls->end()) {
      LOG(WARNING) << "Bookmark not in a bookmark folder found";
      if (!Move(*i, bookmark_node))
        return false;
      unparented_urls->erase(i++);
    }
  }

  // Nuke any folders with duplicate ids. A duplicate id means there are two
  // folders in the starred table with the same folder_id. We only keep the
  // first folder, all other folders are removed.
  for (std::set<StarID>::const_iterator i = folders_with_duplicate_ids.begin();
       i != folders_with_duplicate_ids.end(); ++i) {
    LOG(WARNING) << "Duplicate folder id in bookmark database";
    if (!DeleteStarredEntryRow(*i)) {
      NOTREACHED() << "Unable to delete folder";
      return false;
    }
  }

  // Move unparented user folders back to the bookmark bar.
  {
    std::set<StarredNode*>::iterator i = roots->begin();
    while (i != roots->end()) {
      if ((*i)->value.type == StarredEntry::USER_FOLDER) {
        LOG(WARNING) << "Bookmark folder not on bookmark bar found";
        if (!Move(*i, bookmark_node))
          return false;
        roots->erase(i++);
      } else {
        ++i;
      }
    }
  }

  return true;
}

bool StarredURLDatabase::Move(StarredNode* source, StarredNode* new_parent) {
  history::StarredEntry& entry = source->value;
  entry.visual_order = new_parent->child_count();
  entry.parent_folder_id = new_parent->value.folder_id;
  if (!UpdateStarredEntryRow(entry.id, entry.title,
                             entry.parent_folder_id, entry.visual_order,
                             entry.date_folder_modified)) {
    NOTREACHED() << "Unable to move folder";
    return false;
  }
  new_parent->Add(source, new_parent->child_count());
  return true;
}

bool StarredURLDatabase::MigrateBookmarksToFileImpl(const FilePath& path) {
  std::vector<history::StarredEntry> entries;
  if (!GetAllStarredEntries(&entries))
    return false;

  // Create the bookmark bar and other folder nodes.
  history::StarredEntry entry;
  entry.type = history::StarredEntry::BOOKMARK_BAR;
  BookmarkNode bookmark_bar_node(0, GURL());
  bookmark_bar_node.Reset(entry);
  entry.type = history::StarredEntry::OTHER;
  BookmarkNode other_node(0, GURL());
  other_node.Reset(entry);

  std::map<history::UIStarID, history::StarID> folder_id_to_id_map;
  typedef std::map<history::StarID, BookmarkNode*> IDToNodeMap;
  IDToNodeMap id_to_node_map;

  history::UIStarID other_folder_folder_id = 0;
  history::StarID other_folder_id = 0;

  // Iterate through the entries building a mapping between folder_id and id.
  for (std::vector<history::StarredEntry>::const_iterator i = entries.begin();
       i != entries.end(); ++i) {
    if (i->type != history::StarredEntry::URL) {
      folder_id_to_id_map[i->folder_id] = i->id;
      if (i->type == history::StarredEntry::OTHER) {
        other_folder_id = i->id;
        other_folder_folder_id = i->folder_id;
      }
    }
  }

  // Register the bookmark bar and other folder nodes in the maps.
  id_to_node_map[HistoryService::kBookmarkBarID] = &bookmark_bar_node;
  folder_id_to_id_map[HistoryService::kBookmarkBarID] =
      HistoryService::kBookmarkBarID;
  if (other_folder_folder_id) {
    id_to_node_map[other_folder_id] = &other_node;
    folder_id_to_id_map[other_folder_folder_id] = other_folder_id;
  }

  // Iterate through the entries again creating the nodes.
  for (std::vector<history::StarredEntry>::iterator i = entries.begin();
       i != entries.end(); ++i) {
    if (!i->parent_folder_id) {
      DCHECK(i->type == history::StarredEntry::BOOKMARK_BAR ||
             i->type == history::StarredEntry::OTHER);
      // Only entries with no parent should be the bookmark bar and other
      // bookmarks folders.
      continue;
    }

    BookmarkNode* node = id_to_node_map[i->id];
    if (!node) {
      // Creating a node results in creating the parent. As such, it is
      // possible for the node representing a folder to have been created before
      // encountering the details.

      // The created nodes are owned by the root node.
      node = new BookmarkNode(0, i->url);
      id_to_node_map[i->id] = node;
    }
    node->Reset(*i);

    DCHECK(folder_id_to_id_map.find(i->parent_folder_id) !=
           folder_id_to_id_map.end());
    history::StarID parent_id = folder_id_to_id_map[i->parent_folder_id];
    BookmarkNode* parent = id_to_node_map[parent_id];
    if (!parent) {
      // Haven't encountered the parent yet, create it now.
      parent = new BookmarkNode(0, GURL());
      id_to_node_map[parent_id] = parent;
    }

    // Add the node to its parent. |entries| is ordered by parent then
    // visual order so that we know we maintain visual order by always adding
    // to the end.
    parent->Add(node, parent->child_count());
  }

  // Save to file.
  BookmarkCodec encoder;
  scoped_ptr<Value> encoded_bookmarks(
      encoder.Encode(&bookmark_bar_node, &other_node));
  std::string content;
  base::JSONWriter::Write(encoded_bookmarks.get(), true, &content);

  return (file_util::WriteFile(path, content.c_str(),
                               static_cast<int>(content.length())) != -1);
}

}  // namespace history


text:
var tree = require("../tree"),
    Visitor = require("./visitor");

var CSSVisitorUtils = function(context) {
    this._visitor = new Visitor(this);
    this._context = context;
};

CSSVisitorUtils.prototype = {
    containsSilentNonBlockedChild: function(bodyRules) {
        var rule;
        if (bodyRules == null) {
            return false;
        }
        for (var r = 0; r < bodyRules.length; r++) {
            rule = bodyRules[r];
            if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
                //the directive contains something that was referenced (likely by extend)
                //therefore it needs to be shown in output too
                return true;
            }
        }
        return false;
    },

    keepOnlyVisibleChilds: function(owner) {
        if (owner == null || owner.rules == null) {
            return ;
        }

        owner.rules = owner.rules.filter(function(thing) {
                return thing.isVisible();
            }
        );
    },

    isEmpty: function(owner) {
        if (owner == null || owner.rules == null) {
            return true;
        }
        return owner.rules.length === 0;
    },

    hasVisibleSelector: function(rulesetNode) {
        if (rulesetNode == null || rulesetNode.paths == null) {
            return false;
        }
        return rulesetNode.paths.length > 0;
    },

    resolveVisibility: function (node, originalRules) {
        if (!node.blocksVisibility()) {
            if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
                return ;
            }

            return node;
        }

        var compiledRulesBody = node.rules[0];
        this.keepOnlyVisibleChilds(compiledRulesBody);

        if (this.isEmpty(compiledRulesBody)) {
            return ;
        }

        node.ensureVisibility();
        node.removeVisibilityBlock();

        return node;
    },

    isVisibleRuleset: function(rulesetNode) {
        if (rulesetNode.firstRoot) {
            return true;
        }

        if (this.isEmpty(rulesetNode)) {
            return false;
        }

        if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
            return false;
        }

        return true;
    }

};

var ToCSSVisitor = function(context) {
    this._visitor = new Visitor(this);
    this._context = context;
    this.utils = new CSSVisitorUtils(context);
};

ToCSSVisitor.prototype = {
    isReplacing: true,
    run: function (root) {
        return this._visitor.visit(root);
    },

    visitRule: function (ruleNode, visitArgs) {
        if (ruleNode.blocksVisibility() || ruleNode.variable) {
            return;
        }
        return ruleNode;
    },

    visitMixinDefinition: function (mixinNode, visitArgs) {
        // mixin definitions do not get eval'd - this means they keep state
        // so we have to clear that state here so it isn't used if toCSS is called twice
        mixinNode.frames = [];
    },

    visitExtend: function (extendNode, visitArgs) {
    },

    visitComment: function (commentNode, visitArgs) {
        if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
            return;
        }
        return commentNode;
    },

    visitMedia: function(mediaNode, visitArgs) {
        var originalRules = mediaNode.rules[0].rules;
        mediaNode.accept(this._visitor);
        visitArgs.visitDeeper = false;

        return this.utils.resolveVisibility(mediaNode, originalRules);
    },

    visitImport: function (importNode, visitArgs) {
        if (importNode.blocksVisibility()) {
            return ;
        }
        return importNode;
    },

    visitDirective: function(directiveNode, visitArgs) {
        if (directiveNode.rules && directiveNode.rules.length) {
            return this.visitDirectiveWithBody(directiveNode, visitArgs);
        } else {
            return this.visitDirectiveWithoutBody(directiveNode, visitArgs);
        }
        return directiveNode;
    },

    visitDirectiveWithBody: function(directiveNode, visitArgs) {
        //if there is only one nested ruleset and that one has no path, then it is
        //just fake ruleset
        function hasFakeRuleset(directiveNode) {
            var bodyRules = directiveNode.rules;
            return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
        }
        function getBodyRules(directiveNode) {
            var nodeRules = directiveNode.rules;
            if (hasFakeRuleset(directiveNode)) {
                return nodeRules[0].rules;
            }

            return nodeRules;
        }
        //it is still true that it is only one ruleset in array
        //this is last such moment
        //process childs
        var originalRules = getBodyRules(directiveNode);
        directiveNode.accept(this._visitor);
        visitArgs.visitDeeper = false;

        if (!this.utils.isEmpty(directiveNode)) {
            this._mergeRules(directiveNode.rules[0].rules);
        }

        return this.utils.resolveVisibility(directiveNode, originalRules);
    },

    visitDirectiveWithoutBody: function(directiveNode, visitArgs) {
        if (directiveNode.blocksVisibility()) {
            return;
        }

        if (directiveNode.name === "@charset") {
            // Only output the debug info together with subsequent @charset definitions
            // a comment (or @media statement) before the actual @charset directive would
            // be considered illegal css as it has to be on the first line
            if (this.charset) {
                if (directiveNode.debugInfo) {
                    var comment = new tree.Comment("/* " + directiveNode.toCSS(this._context).replace(/\n/g, "") + " */\n");
                    comment.debugInfo = directiveNode.debugInfo;
                    return this._visitor.visit(comment);
                }
                return;
            }
            this.charset = true;
        }

        return directiveNode;
    },

    checkPropertiesInRoot: function(rules) {
        var ruleNode;
        for (var i = 0; i < rules.length; i++) {
            ruleNode = rules[i];
            if (ruleNode instanceof tree.Rule && !ruleNode.variable) {
                throw { message: "properties must be inside selector blocks, they cannot be in the root.",
                    index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null};
            }
        }
    },

    visitRuleset: function (rulesetNode, visitArgs) {
        //at this point rulesets are nested into each other
        var rule, rulesets = [];
        if (rulesetNode.firstRoot) {
            this.checkPropertiesInRoot(rulesetNode.rules);
        }
        if (! rulesetNode.root) {
            //remove invisible paths
            this._compileRulesetPaths(rulesetNode);

            // remove rulesets from this ruleset body and compile them separately
            var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0;
            for (var i = 0; i < nodeRuleCnt; ) {
                rule = nodeRules[i];
                if (rule && rule.rules) {
                    // visit because we are moving them out from being a child
                    rulesets.push(this._visitor.visit(rule));
                    nodeRules.splice(i, 1);
                    nodeRuleCnt--;
                    continue;
                }
                i++;
            }
            // accept the visitor to remove rules and refactor itself
            // then we can decide nogw whether we want it or not
            // compile body
            if (nodeRuleCnt > 0) {
                rulesetNode.accept(this._visitor);
            } else {
                rulesetNode.rules = null;
            }
            visitArgs.visitDeeper = false;

        } else { //if (! rulesetNode.root) {
            rulesetNode.accept(this._visitor);
            visitArgs.visitDeeper = false;
        }

        if (rulesetNode.rules) {
            this._mergeRules(rulesetNode.rules);
            this._removeDuplicateRules(rulesetNode.rules);
        }

        //now decide whether we keep the ruleset
        if (this.utils.isVisibleRuleset(rulesetNode)) {
            rulesetNode.ensureVisibility();
            rulesets.splice(0, 0, rulesetNode);
        }

        if (rulesets.length === 1) {
            return rulesets[0];
        }
        return rulesets;
    },

    _compileRulesetPaths: function(rulesetNode) {
        if (rulesetNode.paths) {
            rulesetNode.paths = rulesetNode.paths
                .filter(function(p) {
                    var i;
                    if (p[0].elements[0].combinator.value === ' ') {
                        p[0].elements[0].combinator = new(tree.Combinator)('');
                    }
                    for (i = 0; i < p.length; i++) {
                        if (p[i].isVisible() && p[i].getIsOutput()) {
                            return true;
                        }
                    }
                    return false;
                });
        }
    },

    _removeDuplicateRules: function(rules) {
        if (!rules) { return; }

        // remove duplicates
        var ruleCache = {},
            ruleList, rule, i;

        for (i = rules.length - 1; i >= 0 ; i--) {
            rule = rules[i];
            if (rule instanceof tree.Rule) {
                if (!ruleCache[rule.name]) {
                    ruleCache[rule.name] = rule;
                } else {
                    ruleList = ruleCache[rule.name];
                    if (ruleList instanceof tree.Rule) {
                        ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
                    }
                    var ruleCSS = rule.toCSS(this._context);
                    if (ruleList.indexOf(ruleCSS) !== -1) {
                        rules.splice(i, 1);
                    } else {
                        ruleList.push(ruleCSS);
                    }
                }
            }
        }
    },

    _mergeRules: function (rules) {
        if (!rules) { return; }

        var groups = {},
            parts,
            rule,
            key;

        for (var i = 0; i < rules.length; i++) {
            rule = rules[i];

            if ((rule instanceof tree.Rule) && rule.merge) {
                key = [rule.name,
                    rule.important ? "!" : ""].join(",");

                if (!groups[key]) {
                    groups[key] = [];
                } else {
                    rules.splice(i--, 1);
                }

                groups[key].push(rule);
            }
        }

        Object.keys(groups).map(function (k) {

            function toExpression(values) {
                return new (tree.Expression)(values.map(function (p) {
                    return p.value;
                }));
            }

            function toValue(values) {
                return new (tree.Value)(values.map(function (p) {
                    return p;
                }));
            }

            parts = groups[k];

            if (parts.length > 1) {
                rule = parts[0];
                var spacedGroups = [];
                var lastSpacedGroup = [];
                parts.map(function (p) {
                    if (p.merge === "+") {
                        if (lastSpacedGroup.length > 0) {
                            spacedGroups.push(toExpression(lastSpacedGroup));
                        }
                        lastSpacedGroup = [];
                    }
                    lastSpacedGroup.push(p);
                });
                spacedGroups.push(toExpression(lastSpacedGroup));
                rule.value = toValue(spacedGroups);
            }
        });
    },

    visitAnonymous: function(anonymousNode, visitArgs) {
        if (anonymousNode.blocksVisibility()) {
            return ;
        }
        anonymousNode.accept(this._visitor);
        return anonymousNode;
    }
};

module.exports = ToCSSVisitor;


text:
package controllers

import org.jsoup.Jsoup
import org.scalatestplus.play.OneServerPerSuite
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.play.audit.model.Audit

class QuestionnaireControllerSpec extends test.BaseSpec with OneServerPerSuite {

  object TestQuestionnaireController extends QuestionnaireController {
    override val audit: Audit = ???
    override val appName: String = "Test"
  }

  "Calling QuestionnaireController.showQuestionnaire" should {

    "not respond with NOT_FOUND" in {
      val request = FakeRequest(GET, "/paac/feedback")
      val result = QuestionnaireController.showQuestionnaire.apply(request)

      status(result) should not be NOT_FOUND
    }

    "show the questionnaire view" in {
      val request = FakeRequest(GET, "/paac/feedback")
      val result = QuestionnaireController.showQuestionnaire.apply(request)
      val document = Jsoup.parse(contentAsString(result))

      status(result) should be(OK)

      document.title should be("Give feedback - GOV.UK")
      document.getElementById("page-title").text should be("Give feedback")
      document.getElementsByClass("question1-legend").text should be ("When you used this service, was it:")
      document.getElementsByAttributeValue("for", "user-1").text should be ("for yourself")
      document.getElementsByAttributeValue("for", "user-0").text should be ("on behalf of someone else")
      document.getElementById("question2-legend")
        .text should be ("What will you be using the results of the calculator for?")
      document.getElementById("question3-legend").text should be ("How could we improve the service?")
      document.getElementsByClass("question4-legend")
        .text should be ("Would you like to take part in any future research to help us improve the service?")
      document.getElementsByAttributeValue("for", "participate-1").text should be ("Yes")
      document.getElementsByAttributeValue("for", "participate-0").text should be ("No")
      document.getElementById("submit").text should be("Send feedback")
    }
  }

  "Calling QuestionnaireController.submitQuestionnaire" should {

    "not respond with NOT_FOUND" in {
      val request = FakeRequest(POST, "/paac/feedback")
      val result = QuestionnaireController.submitQuestionnaire.apply(request)

      status(result) should not be NOT_FOUND
    }

    "submit a valid questionnaire" in {
      val formData =
        s"""{"user": "1",
           |"use": "I want to know how much money I owe HMRC.",
           |"improve": "I don't think this service can get much better.",
           |"participate": "1",
           |"email": "tax.payer@email.co.uk"}""".stripMargin
      val request = FakeRequest(POST, "/paac/feedback").withJsonBody(Json.parse(formData))
      val result = QuestionnaireController.submitQuestionnaire.apply(request)

      status(result) should be(SEE_OTHER)

      redirectLocation(result) should be(Some("/paac/feedbackThankYou"))
    }

    "not submit an invalid questionnaire" in {
      val formData =
        s"""{"user": "1",
           |"use": "I want to know how much money I owe HMRC.",
           |"improve": "I don't think this service can get much better.",
           |"participate": "1",
           |"email": " "}""".stripMargin
      val request = FakeRequest(POST, "/paac/feedback").withJsonBody(Json.parse(formData))
      val result = QuestionnaireController.submitQuestionnaire.apply(request)
      val document = Jsoup.parse(contentAsString(result))

      status(await(result)) should be(BAD_REQUEST)

      document.title should be("Give feedback - GOV.UK")
      document.getElementById("error-summary-heading").text should be("There's a problem")
      document.getElementById("email-error-link")
        .text should be("You must enter an email address")
    }
  }

  "Calling QuestionnaireController.feedbackThankYou" should {

    "not respond with NOT_FOUND" in {

      val request = FakeRequest(GET, "/paac/feedbackThankYou")
      val result = QuestionnaireController.feedbackThankYou.apply(request)

      status(result) should not be NOT_FOUND
    }

    "show the questionnaire thank you view" in {

      val request = FakeRequest(GET, "/paac/feedbackThankYou")
      val result = QuestionnaireController.feedbackThankYou.apply(request)
      val document = Jsoup.parse(contentAsString(result))

      status(result) should be(OK)

      document.title should be("Thanks for your feedback - GOV.UK")
      document.getElementById("page-title").text should be("Thanks for your feedback")
      document.getElementById("start").text should be("Start again")
    }
  }
}


text:
'use strict';

var crypto = require('crypto');

/**
 * Create a random hex string of specific length and
 * @todo consider taking out to a common unit testing javascript helper
 * @return string
 */
function getRandomString(len) {
    if (!len)
        len = 16;

    return crypto.randomBytes(Math.ceil(len / 2)).toString('hex');
}

/**
 * Module dependencies.
 */
var should = require('should'),
    mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Todo = mongoose.model('Todo');

/**
 * Globals
 */
var user1, user2, todo1, todo2, user1email;

/**
 * Test Suites
 */
describe('<Unit Test>', function () {
    describe('Model Todo:', function () {

        before(function (done) {
            user1email = 'test' + getRandomString() + '@test.com';
            user1 = new User({
                name: 'User 1',
                email: user1email,
                username: getRandomString(),
                password: 'password',
                provider: 'local'
            });

            user2 = new User({
                name: 'User 2',
                email: 'test' + getRandomString() + '@test.com',
                username: getRandomString(),
                password: 'password',
                provider: 'local'
            });

            todo1 = {
                title: getRandomString(30),
                content: getRandomString(100)
            };

            todo2 = {
                title: getRandomString(30),
                content: getRandomString(100)
            };

            user1.save(function (err) {
                should.not.exist(err);
                user2.save(function (err) {
                    should.not.exist(err);
                    done();
                });
            });
        });

        describe('Method Save', function () {
            it('should begin without the 2 test todo', function (done) {
                Todo.find({
                    title: todo1.title
                }, function (err, todos) {
                    todos.should.have.length(0);

                    Todo.find({
                        title: todo2.title
                    }, function (err, todos) {
                        todos.should.have.length(0);
                        done();
                    });

                });
            });

            it('should be able to save without problems', function (done) {

                var _todo = new Todo(todo1);
                _todo.save(function (err) {
                    should.not.exist(err);
                    _todo.remove();
                    done();
                });

            });

it('should check that default values are assigned and todo is created properly', function (done) {
    var _todo = new Todo(todo1);
    _todo.save(function (err) {
        should.not.exist(err);

        _todo.title.should.have.length(30);
        _todo.content.should.have.length(100);
        _todo.priority.should.equal(3);
        _todo.done.should.equal(false);
        _todo.remove(function (err) {
            should.not.exist(err);
            done();
        });
    });
});

            it('should be able to change property', function (done) {

                var _todo = new Todo(todo1);
                _todo.priority.should.equal(3);

                _todo.priority = 2;

                _todo.save(function (err) {
                    should.not.exist(err);
                    _todo.priority.should.equal(2);

                    _todo.priority = 4;
                    _todo.save(function (err) {
                        should.not.exist(err);
                        _todo.priority.should.equal(4);
                        _todo.remove(function () {
                            done();
                        });
                    });
                });
            });

            it('should be able to associate a user to a todo', function (done) {

                var _todo = new Todo(todo1);
                _todo.user = user1;
                _todo.save(function (err) {
                    should.not.exist(err);

                    Todo.findOne({_id: _todo._id}).populate('user').exec(function(err, _todo2){
                        should.not.exist(err);

                        should(_todo2.user.email).equal(user1email);
                        _todo2.remove(function (err) {
                            should.not.exist(err);
                            done();
                        });
                    });
                });
            });
        });

        after(function (done) {
            done();
        });
    });
});


text:
title: Exploring Javascript SVG Animation
date: 11:01 05/22/2016
highlight:
    theme: monokai
taxonomy:
    category: blog
    tag: [SVG, Snap, Tutorial, Animation, Javascript]
---

Click the image to animate! And no, that's not a GIF either. It's an SVG drawing being animated and manipulated with Javascript and the Snap SVG library. Read more to learn how I did this.

<svg preserveAspectRatio="xMinYMin meet" class="svg-content" viewBox="0 0 620 300" id="snap_demo"></svg>

===

### What is SVG?

If you've been browsing my website of late, you might have noticed that I've chosen to replace all my thumbnails with SVG images. Since most of my illustrations are done inside Illustrator anyway, it only makes sense to export them in their highest quality.

But what is SVG and why is it best for website design? SVGs or _Scalable Vector Graphics_ are first and foremost much more flexible and interactive than regular old PNGs and JPEGs. Any web developer understands the downsides to having high quality images on their site and the issues with compression and image serving based on device resolutions.

!!!! On a related note, any images inside a `<img>` tag require a browser HTTP request of course. And any such request necessitates precious bandwidth and download time. SVGs on the other hand, simply being a set of DOM nodes require no such thing.

But what if you could have sharp, crisp and pixel perfect images that look identical across platforms as well as being responsive out of the box? Sounds like a dream but SVGs are the answer. What's more is that SVGs are an XML-based file format meaning your images are rendered as code, and any code is able to be manipulated. In this case with Javascript.

!!!! Since SVGs is text-based XML you can do regular GZIP compression as you normally would. Actually _SVGZ_ is the term for a gzipped SVG. An SVGZ file is often 20 to 50 percent of the original size. You can also do this dynamically inside your _.htaccess_ file of your website.

In fact, you can do a lot with Javascript and SVGs. Since the SVG DOM (node-based) API is so much easier to get into than the client-side only Canvas API, there are distinct advantages.

One of the most important points being the ability to manipulate SVG styles, shapes, positions .etc with Javascript as well as the ability for SVG client-side generation. On top of all this, you can you also use typical Javascript event handlers such as click or hover, just as you would with any other HTML element.

### Taking a closer look

I've rambled long enough about SVG being an _XML-based file format_ but what exactly does it look like? SVGs for a start have their own tag: `<svg></svg>` which contains the contents of your SVG, be it shapes, paths or whatever else.

Below, I've created an illustration in Adobe Illustrator and exported it as an SVG. Besides some clean-up it's exactly how it's exported. It's fairly intuitive and isn't far off vanilla HTML.

```HTML
<svg id="back" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 300">
	<defs>
		<style>
			.cls-1{fill:#ffe780;}
			.cls-2{fill:#e25139;}
			.cls-3{fill:#c161d1;}
			.cls-4{fill:#64ddda;}
		</style>
	</defs>
	<title>first_example</title>
	<rect class="cls-1" width="620" height="300"/>
	<circle class="cls-2" cx="310.25" cy="152.5" r="57.5"/>
	<polygon class="cls-3" points="76,210 191,210 134,95"/>
	<rect class="cls-4" x="429.5" y="95" width="115" height="115"/>
</svg>
```

![first_example](first_example.svg)

You can see I've given my SVG an `id="back"`. This is important later when we want to reference an external SVG file with JQuery.

Also note the `viewBox="0 0 620 300"`. While this might look relatively straightforward it's a fundamental in understanding the SVG coordinate system. Trust me, knowing how positioning and transformations work makes working with SVGs that much easier.

Without digressing too much, I'm just going to run through the two most important aspects: `viewPort` and `viewBox`.

### The ViewPort

The viewPort as the name suggests is the _portal_ or viewing area where the SVG is visible. The size of the viewPort is the `width` & `height` of the outermost `<svg>` element.

```
<!-- viewPort is 300px by 300px -->
<svg width="300" height="300">
    <!-- SVG content -->
</svg>
```

Not too hard then. Remember that values in SVG don't necessarily require given unit identifiers. This mightn't be new to you, but just realise I didn't specify values using units in the above example but they're interpreted as pixels.

Now, how to position things inside the viewPort then? Well for starters, it doesn't look like I set an **initial viewPort coordinate system**.

Luckily, SVG did. The initial viewPort coordinate system is established when the viewPort is declared. It's probably a little different to the regular cartesian coordinates you learnt in school but not too alien.

The origin is in the upper left of the viewPort at (0,0) with the positive x-axis pointing to the right and the y-axis pointing straight down. One unit on the x/y axes represents one pixel in the viewPort.

![second_example](second_example.svg)

So if the viewPort coordinate system is the coordinate system established by the viewPort then it stands to reason that as users we should also be able to declare our own, right?

### The ViewBox

Enter the `viewBox` attribute! This allows us to set our own **user coordinate system** based on our own custom coordinates. Intially the user coordinate system is set to the initial viewPort coordinate system as default.

!!! The viewBox is the coordinate system that you'll really be using 90% of the time. Just remember that the viewPort coordinate system can still be there and the viewBox can also be bigger or smaller than the viewPort if you intend.

Now, let's understand the syntax. The viewBox attribute requires four parameters:

```
viewBox = <min-x> <min-y> <width> <height>
```

The `<min-x>` and `<min-y>` values determine the origin of the viewBox, and the width and height determine the width and height of that viewBox.

!!! Note that if the viewBox has a different aspect ratio (ratio of height to width) to the viewPort, then you can use the `preserveAspectRatio` to choose whether or not to apply uniform scaling.

In our first example you can see I haven't set the viewPort but I have specified the viewBox as `viewBox="0 0 620 300"`.

That's as much as I'll go into coordinate systems. If you want to understand it a bit better then I highly recommend reading this [article](https://sarasoueidan.com/blog/svg-coordinate-systems/) I found.

### Drawing shapes

Returning to the first example, I've deliberately drawn three different shapes to highlight the various ways you can create SVG elements.

```HTML
	<rect class="cls-1" width="620" height="300"/>
	<circle class="cls-2" cx="310.25" cy="152.5" r="57.5"/>
	<polygon class="cls-3" points="76,210 191,210 134,95"/>
	<rect class="cls-4" x="429.5" y="95" width="115" height="115"/>
```

Firstly, note they all have different classes which are predefined inside `<style>` tag of the `<defs>` tag. The `<defs>` tag is used to embed definitions that can later be reused within the image, such as the colour classes used in this example.

```HTML
<defs>
	<style>
		.cls-1{fill:#ffe780;}
		.cls-2{fill:#e25139;}
		.cls-3{fill:#c161d1;}
		.cls-4{fill:#64ddda;}
	</style>
</defs>
```

Anyways, drawing elements is straightforward. I'll pass over the _easily understood_ `<rect/>` tag and look at the `<circle/>`. The `cx` and `cy` define the centre x and y coordinates of the circle, with `r` standing for the radius.

The `<polygon/>` tag is used to create elements with at least three sides, which of course makes it perfect for three sided shapes such as... um, triangles! Polygons are made of straight lines, and the shape must always be closed.

```HTML
<polygon class="cls-3" points="76,210 191,210 134,95"/>
```

Our triangle has three points: `76,210` for the bottom left corner, `191,210` for the bottom right corner and `134,95` for the apex. Notice how the points correspond to the viewBox described earlier.

### Animation

Finally, the time has come! Before I dive in though I should introduce the Javascript library I intend on demonstrating - [Snap Svg](http://snapsvg.io/).

![snap_logo](snap_logo.svg)

Snap SVG is a free open-source library (supported by Adobe, yes the people that made Flash) that's quick becoming the de facto standard for serious SVG animation. Designed specifically for modern browsers, it supports all the cutting edge features available like masking, clipping, patterns, full gradients, groups, and more.

With it's simple API, it's a great place to get started with SVG animation.

By hovering below you can see that I've animated the example using the Snap SVG library.

<svg preserveAspectRatio="xMinYMin meet" class="svg-content" viewBox="0 0 620 300" id="anim_example"></svg>

Snap SVG as I've learnt is best suited to this kind of brief animation. Typically you'll see animation like this employed on icons or buttons for user interaction purposes.

I misunderstood this fundamental property when I began animating my SVG image. I was intending for a running animation being played on a continuous loop but Snap SVG isn't exactly performant for those kinds of applications.

Looking at the CPU usage below, you can see that Chrome Helper is hogging things at over 100%. It's a little better on Safari but neither is good.

Besides CPU usage, complex graphics and animations are just going to lag and misbehave, especially on smaller devices. Hence why I've disabled my animated SVG at the top of this article simply because it's so taxing on the browser.

![cpu_snap](cpu_snap.png)

Anyways, how do you go about animating with Snap SVG? Firstly, setup is always where you should start. Since SVG is just XML you can slot it inside your HTML no bother, but it isn't very pretty and get quite clumbersome when files get bigger.

```Bash
snap_example/
├── first_example.svg
├── index.html
├── js/
│   ├── main.js
│   └── snap.svg-min.js
```

That's why I like to create my directory as you see above. Have my SVGs external to the my `index.html` and load in my Javascript animations as well as the Snap SVG library.

!!!! You can download the Snap SVG library from [here](http://snapsvg.io) or choose to use this [CDN](https://cdnjs.com/libraries/snap.svg/) instead.

Below I've set up a simple HTML page with the necessary `<script>` tags and an `<SVG>` placed in the body. I've also give an `id="anim_example"` to the `<SVG>`.

```HTML
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Snap Example</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
	<script src="/js/snap.svg-min.js"></script>
	<script src="/js/main.js"></script>
</head>
<body>
	<svg width=620 height=300 id="anim_example"></svg> // Note that user coordinate system will default to viewPort
</body>
<!-- Alternative CDN -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.4.1/snap.svg-min.js"></script> -->
</html>
```
Inside my main.js file I've added a common load function to insert the external SVG. The `Snap.load()` takes in the URL of the SVG file as its parameter and then calls a function to append said file to the page.

```js
'use strict'

var s = Snap("#anim_example");
var main = Snap.load("/first_example.svg", function (loadedFragment) {
	s.append(loadedFragment);
});
```

Although, that didn't seem to work... Opening the Chrome Inspector, you can see there's an error: _uncaught TypeError cannot read property 'append' of null_.

![append_null_error](append_null_error.png)

The way to get round this is to enclose the code with JQuery's **$(document).ready()**.

 This simply says that the code inside will only run once the DOM is ready for Javascript code to execute. It's one of those common errors that you come across quite regularly - so remember it!

```js
'use strict'

$(document).ready(function() {
	var s = Snap("#anim_example");
	var main = Snap.load("/first_example.svg", function (loadedFragment) {
		s.append(loadedFragment);
	});
});
```

Now, since we've 'linked' up our SVG image, we should be able to reference it in a simple manner. Remembering that SVG is just XML we can find the shapes by just referencing their classes. You can do so by using `Snap.select()` just as you would with JQuery using the CSS selector syntax.

```JS
'use strict'

$(document).ready(function() {
	var s = Snap("#anim_example");
	var main = Snap.load("/first_example.svg", function (loadedFragment) {
		s.append(loadedFragment);

		var circle = Snap.select('.cls-2');
		var triangle = Snap.select('.cls-3');
		var square = Snap.select('.cls-4');

		var sqr_bbox = square.getBBox();
		var tri_bbox = triangle.getBBox();
	});
});
```

For our square and triangle animations, we'd like to be able to get the centre coordinates. Hence why I'm using `.getBBox`, which stands for _Bounding Box_. This returns the bounding box descriptor for the given element which provides the `cx` and `cy` coordinates.

```
function circ_jump () {
	circle.stop().animate({transform: 't0,-50'}, 500, mina.backout, function () {
		circle.animate({transform: 't0,0'}, 500, mina.backin);
	});
}
```

For animating the circle, I've created a `circ_jump` function which moves the circle element up 50 pixels with a `mina.backout` ease and then moves back down to its original position with another `mina.backin` ease.

Breaking this down a little further and taking it line by line...

```
circle.stop().animate({transform: 't0,-50'}, 500, mina.backout, function () { ... });}
```

The above line takes the circle we defined earlier, stops any previous animation with `.stop()` and then moves to `.animate` where we specify the animatons we want to carry out.

The `.animate` method syntax looks something like this:

```
Snap.animate(attrs,duration,[easing],[callback])
```

So in this instance our `attrs` is to translate or move `'t0,-50'` or in other words, move `0` on the x-axis and move `-50` (up 50) on the y-axis: `{transform: 't0,-50'}`.

Duration is for `500` or half a second, followed by an easing function `mina.backout` and then a callback function which is called once the animation is finished.

The callback function is similar again:

```
circle.animate({transform: 't0,0'}, 500, mina.backin);
```

Again, animate the circle by returning it to `'t0,0'` in `500` milliseconds followed by another `mina.backin` easing function.

So that's the circle animated then. Let's animate the square next and get a better look at the `getBBox` method.

```
function sqr_rotate(){
	square.transform('');
	square.animate({ transform: "r180," + sqr_bbox.cx + ',' + sqr_bbox.cy}, 1500, mina.bounce);
}
```

The first line `square.transform('');` is a simple line that tells the element to return to its starting position. Nothing tricky but very useful.

```
square.animate({ transform: "r180," + sqr_bbox.cx + ',' + sqr_bbox.cy}, 1500, mina.bounce);
```

Inside the next line, we have another `.animate` but this time we're doing a rotation of 180 degrees `r180` around the centre of the square which is being determined by `sqr_bbox.cx` and `sqr_bbox.cy`. This is being done for `1500` seconds with a `mina.bounce` ease.

!!! Notice that there's no callback within this function. Callbacks are optional and not always necessary.

Finally, we can move onto the triangle which introduces scaling.

```
function tri_scale () {
	triangle.transform('');
	triangle.stop().animate({transform: 's.5,.5'}, 300, mina.easeout, function() {
		triangle.stop().animate({transform: 's1,1'}, 700, mina.elastic);
	});
}
```

Notice that inside the `.animate`, there's `{transform: 's.5,.5'}` which scales the element down to half before the callback scales the element back up: `{transform: 's1,1'}`.

Lastly, down at the very bottom of our file, we can call our Javascript methods by creating JQuery `.mouseover` events for each.

```
circle.mouseover(circ_jump);
square.mouseover(sqr_rotate);
triangle.mouseover(tri_scale);
```

Our final Javascript animation file looks like this then:

```
'use strict'

$(document).ready(function() {
	var s = Snap("#anim_example");
	var main = Snap.load("/first_example.svg", function (loadedFragment) {
		s.append(loadedFragment);

		var circle = Snap.select('.cls-2');
		var triangle = Snap.select('.cls-3');
		var square = Snap.select('.cls-4');

		var sqr_bbox = square.getBBox();
		var tri_bbox = triangle.getBBox();

		function circ_jump () {
			circle.stop().animate({transform: 't0,-50'}, 500, mina.backout, function () {
				circle.animate({transform: 't0,0'}, 500, mina.backin);
			});
		}

		function sqr_rotate(){
			square.transform('');
			square.animate({ transform: "r180," + sqr_bbox.cx + ',' + sqr_bbox.cy}, 1500, mina.bounce);
		}

		function tri_scale () {
			triangle.transform('');
			triangle.stop().animate({transform: 's.5,.5'}, 300, mina.easeout, function() {
				triangle.stop().animate({transform: 's1,1'}, 700, mina.elastic);
			});
		}

		circle.mouseover(circ_jump);
		square.mouseover(sqr_rotate);
		triangle.mouseover(tri_scale);

	});
});
```

That brief demo covers the basics of Snap SVG animation. Rest assured it can be more or less complicated depending on how ambitious you are. I haven't even covered features such as clipping, masking, patterns or gradients. Just some of the things that make Snap SVG so great.

To conclude, I'd like to mention that I'll most likely expand on this article in due time, detailing a bit more on how I created the header SVG image, since that incorporates masking which is especially useful to learn about. Until then, thanks for reading!

P.S. You can find the repository for the header SVG image [here](https://github.com/gregorykelleher/computer_snap_svg) on my Github Profile.


text:
package org.apache.poi.hslf.record;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hslf.exceptions.HSLFException;
import org.apache.poi.hslf.model.textproperties.TextPropCollection;
import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType;
import org.apache.poi.util.HexDump;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.POILogger;

/**
 * A StyleTextPropAtom (type 4001). Holds basic character properties
 *  (bold, italic, underline, font size etc) and paragraph properties
 *  (alignment, line spacing etc) for the block of text (TextBytesAtom
 *  or TextCharsAtom) that this record follows.
 * You will find two lists within this class.
 *  1 - Paragraph style list (paragraphStyles)
 *  2 - Character style list (charStyles)
 * Both are lists of TextPropCollections. These define how many characters
 *  the style applies to, and what style elements make up the style (another
 *  list, this time of TextProps). Each TextProp has a value, which somehow
 *  encapsulates a property of the style
 */

public final class StyleTextPropAtom extends RecordAtom {
    public static final long _type = RecordTypes.StyleTextPropAtom.typeID;
    private byte[] _header;
    private byte[] reserved;

    private byte[] rawContents; // Holds the contents between write-outs

    /**
     * Only set to true once setParentTextSize(int) is called.
     * Until then, no stylings will have been decoded
     */
    private boolean initialised = false;

    /**
     * The list of all the different paragraph stylings we code for.
     * Each entry is a TextPropCollection, which tells you how many
     *  Characters the paragraph covers, and also contains the TextProps
     *  that actually define the styling of the paragraph.
     */
    private List<TextPropCollection> paragraphStyles;
    public List<TextPropCollection> getParagraphStyles() { return paragraphStyles; }
    /**
     * Updates the link list of TextPropCollections which make up the
     *  paragraph stylings
     */
    public void setParagraphStyles(List<TextPropCollection> ps) { paragraphStyles = ps; }
    /**
     * The list of all the different character stylings we code for.
     * Each entry is a TextPropCollection, which tells you how many
     *  Characters the character styling covers, and also contains the
     *  TextProps that actually define the styling of the characters.
     */
    private List<TextPropCollection> charStyles;
    public List<TextPropCollection> getCharacterStyles() { return charStyles; }
    /**
     * Updates the link list of TextPropCollections which make up the
     *  character stylings
     */
    public void setCharacterStyles(List<TextPropCollection> cs) { charStyles = cs; }

    /**
     * Returns how many characters the paragraph's
     *  TextPropCollections cover.
     * (May be one or two more than the underlying text does,
     *  due to having extra characters meaning something
     *  special to powerpoint)
     */
    public int getParagraphTextLengthCovered() {
        return getCharactersCovered(paragraphStyles);
    }
    /**
     * Returns how many characters the character's
     *  TextPropCollections cover.
     * (May be one or two more than the underlying text does,
     *  due to having extra characters meaning something
     *  special to powerpoint)
     */
    public int getCharacterTextLengthCovered() {
        return getCharactersCovered(charStyles);
    }
    private int getCharactersCovered(List<TextPropCollection> styles) {
        int length = 0;
        for(TextPropCollection tpc : styles) {
            length += tpc.getCharactersCovered();
        }
        return length;
    }

    /* *************** record code follows ********************** */

    /**
     * For the Text Style Properties (StyleTextProp) Atom
     */
    public StyleTextPropAtom(byte[] source, int start, int len) {
        // Sanity Checking - we're always at least 8+10 bytes long
        if(len < 18) {
            len = 18;
            if(source.length - start < 18) {
                throw new HSLFException("Not enough data to form a StyleTextPropAtom (min size 18 bytes long) - found " + (source.length - start));
            }
        }

        // Get the header
        _header = new byte[8];
        System.arraycopy(source,start,_header,0,8);

        // Save the contents of the atom, until we're asked to go and
        //  decode them (via a call to setParentTextSize(int)
        rawContents = new byte[len-8];
        System.arraycopy(source,start+8,rawContents,0,rawContents.length);
        reserved = new byte[0];

        // Set empty lists, ready for when they call setParentTextSize
        paragraphStyles = new ArrayList<TextPropCollection>();
        charStyles = new ArrayList<TextPropCollection>();
    }

    /**
     * A new set of text style properties for some text without any.
     */
    public StyleTextPropAtom(int parentTextSize) {
        _header = new byte[8];
        rawContents = new byte[0];
        reserved = new byte[0];

        // Set our type
        LittleEndian.putInt(_header,2,(short)_type);
        // Our initial size is 10
        LittleEndian.putInt(_header,4,10);

        // Set empty paragraph and character styles
        paragraphStyles = new ArrayList<TextPropCollection>();
        charStyles = new ArrayList<TextPropCollection>();

        addParagraphTextPropCollection(parentTextSize);
        addCharacterTextPropCollection(parentTextSize);

        // Set us as now initialised
        initialised = true;

        try {
            updateRawContents();
        } catch (IOException e) {
            throw new HSLFException(e);
        }
    }

    /**
     * We are of type 4001
     */
    @Override
    public long getRecordType() { return _type; }

    /**
     * Write the contents of the record back, so it can be written
     *  to disk
     */
    @Override
    public void writeOut(OutputStream out) throws IOException {
        // First thing to do is update the raw bytes of the contents, based
        //  on the properties
        updateRawContents();

        // Write out the (new) header
        out.write(_header);

        // Write out the styles
        out.write(rawContents);

        // Write out any extra bits
        out.write(reserved);
    }

    /**
     * Tell us how much text the parent TextCharsAtom or TextBytesAtom
     *  contains, so we can go ahead and initialise ourselves.
     */
    public void setParentTextSize(int size) {
        if (initialised) {
            return;
        }

        int pos = 0;
        int textHandled = 0;

        paragraphStyles.clear();
        charStyles.clear();

        // While we have text in need of paragraph stylings, go ahead and
        // grok the contents as paragraph formatting data
        int prsize = size;
        while(pos < rawContents.length && textHandled < prsize) {
            // First up, fetch the number of characters this applies to
            int textLen = LittleEndian.getInt(rawContents,pos);
            textLen = checkTextLength(textLen, textHandled, size);
            textHandled += textLen;
            pos += 4;

            short indent = LittleEndian.getShort(rawContents,pos);
            pos += 2;

            // Grab the 4 byte value that tells us what properties follow
            int paraFlags = LittleEndian.getInt(rawContents,pos);
            pos += 4;

            // Now make sense of those properties
            TextPropCollection thisCollection = new TextPropCollection(textLen, TextPropType.paragraph);
            thisCollection.setIndentLevel(indent);
            int plSize = thisCollection.buildTextPropList(paraFlags, rawContents, pos);
            pos += plSize;

            // Save this properties set
            paragraphStyles.add(thisCollection);

            // Handle extra 1 paragraph styles at the end
            if(pos < rawContents.length && textHandled == size) {
                prsize++;
            }

        }
        if (rawContents.length > 0 && textHandled != (size+1)){
            logger.log(POILogger.WARN, "Problem reading paragraph style runs: textHandled = " + textHandled + ", text.size+1 = " + (size+1));
        }

        // Now do the character stylings
        textHandled = 0;
        int chsize = size;
        while(pos < rawContents.length && textHandled < chsize) {
            // First up, fetch the number of characters this applies to
            int textLen = LittleEndian.getInt(rawContents,pos);
            textLen = checkTextLength(textLen, textHandled, size);
            textHandled += textLen;
            pos += 4;

            // Grab the 4 byte value that tells us what properties follow
            int charFlags = LittleEndian.getInt(rawContents,pos);
            pos += 4;

            // Now make sense of those properties
            // (Assuming we actually have some)
            TextPropCollection thisCollection = new TextPropCollection(textLen, TextPropType.character);
            int chSize = thisCollection.buildTextPropList(charFlags, rawContents, pos);
            pos += chSize;

            // Save this properties set
            charStyles.add(thisCollection);

            // Handle extra 1 char styles at the end
            if(pos < rawContents.length && textHandled == size) {
                chsize++;
            }
        }
        if (rawContents.length > 0 && textHandled != (size+1)){
            logger.log(POILogger.WARN, "Problem reading character style runs: textHandled = " + textHandled + ", text.size+1 = " + (size+1));
        }

        // Handle anything left over
        if(pos < rawContents.length) {
            reserved = new byte[rawContents.length-pos];
            System.arraycopy(rawContents,pos,reserved,0,reserved.length);
        }

        initialised = true;
    }

    private int checkTextLength(int readLength, int handledSoFar, int overallSize) {
        if (readLength + handledSoFar > overallSize + 1) {
            logger.log(POILogger.WARN, "Style length of " + readLength + " at " + handledSoFar +
                    " larger than stated size of " + overallSize + ", truncating");
            return overallSize + 1 - handledSoFar;
        }
        return readLength;
    }

    /**
     * Updates the cache of the raw contents. Serialised the styles out.
     */
    private void updateRawContents() throws IOException {
        if (initialised) {
            // Only update the style bytes, if the styles have been potentially
            // changed

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            // First up, we need to serialise the paragraph properties
            for(TextPropCollection tpc : paragraphStyles) {
                tpc.writeOut(baos);
            }

            // Now, we do the character ones
            for(TextPropCollection tpc : charStyles) {
                tpc.writeOut(baos);
            }

            rawContents = baos.toByteArray();
        }

        // Now ensure that the header size is correct
        int newSize = rawContents.length + reserved.length;
        LittleEndian.putInt(_header,4,newSize);
    }

    /**
     * Clear styles, so new collections can be added
     */
    public void clearStyles() {
        paragraphStyles.clear();
        charStyles.clear();
        reserved = new byte[0];
        initialised = true;
    }

    /**
     * Create a new Paragraph TextPropCollection, and add it to the list
     * @param charactersCovered The number of characters this TextPropCollection will cover
     * @return the new TextPropCollection, which will then be in the list
     */
    public TextPropCollection addParagraphTextPropCollection(int charactersCovered) {
        TextPropCollection tpc = new TextPropCollection(charactersCovered, TextPropType.paragraph);
        paragraphStyles.add(tpc);
        return tpc;
    }
    /**
     * Create a new Character TextPropCollection, and add it to the list
     * @param charactersCovered The number of characters this TextPropCollection will cover
     * @return the new TextPropCollection, which will then be in the list
     */
    public TextPropCollection addCharacterTextPropCollection(int charactersCovered) {
        TextPropCollection tpc = new TextPropCollection(charactersCovered, TextPropType.character);
        charStyles.add(tpc);
        return tpc;
    }

    /* ************************************************************************ */

    /**
     * Dump the record content into StringBuffer
     *
     * @return the string representation of the record data
     */
    @Override
    public String toString(){
        StringBuffer out = new StringBuffer();

        out.append("StyleTextPropAtom:\n");
        if (!initialised) {
            out.append("Uninitialised, dumping Raw Style Data\n");
        } else {

            out.append("Paragraph properties\n");
            for(TextPropCollection pr : getParagraphStyles()) {
                out.append(pr);
            }

            out.append("Character properties\n");
            for(TextPropCollection pr : getCharacterStyles()) {
                out.append(pr);
            }

            out.append("Reserved bytes\n");
            out.append( HexDump.dump(reserved, 0, 0) );
        }

        out.append("  original byte stream \n");

        byte buf[] = new byte[rawContents.length+reserved.length];
        System.arraycopy(rawContents, 0, buf, 0, rawContents.length);
        System.arraycopy(reserved, 0, buf, rawContents.length, reserved.length);
        out.append( HexDump.dump(buf, 0, 0) );

        return out.toString();
    }
}


text:
var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: {
    'index': './example/main.js',
    'vue-recyclist': './src/index.js',
    'vue-recyclist.min': './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, './example'),
    publicPath: process.env.NODE_ENV === 'production' ? './example/' : 'example/',
    filename: '[name].js',
    library: 'VueRecyclist',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: 'img/[name].[hash:7].[ext]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.' + (process.env.NODE_ENV === 'production' ? 'min' : 'common') + '.js'
    }
  },
  devtool: 'source-map',
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    host: '0.0.0.0'
  },
  performance: {
    hints: false
  }
}

if (process.env.NODE_ENV === 'production') {
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}


text:
using System;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable enable
namespace Orleans.Runtime
{
    /// <summary>
    /// Identifies a grain.
    /// </summary>
    [Immutable]
    [Serializable]
    [JsonConverter(typeof(GrainIdJsonConverter))]
    [StructLayout(LayoutKind.Auto)]
    [GenerateSerializer]
    public readonly struct GrainId : IEquatable<GrainId>, IComparable<GrainId>, ISerializable, ISpanFormattable
    {
        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        public GrainId(GrainType type, IdSpan key)
        {
            Type = type;
            Key = key;
        }

        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        private GrainId(SerializationInfo info, StreamingContext context)
        {
            Type = new GrainType(IdSpan.UnsafeCreate((byte[]?)info.GetValue("tv", typeof(byte[])), info.GetInt32("th")));
            Key = IdSpan.UnsafeCreate((byte[]?)info.GetValue("kv", typeof(byte[])), info.GetInt32("kh"));
        }

        /// <summary>
        /// Gets the grain type.
        /// </summary>
        [Id(1)]
        public GrainType Type { get; }

        /// <summary>
        /// Gets the grain key.
        /// </summary>
        [Id(2)]
        public IdSpan Key { get; }

        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        public static GrainId Create(string type, string key) => Create(GrainType.Create(type), key);

        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        public static GrainId Create(GrainType type, string key) => new GrainId(type, IdSpan.Create(key));

        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        public static GrainId Create(GrainType type, IdSpan key) => new GrainId(type, key);

        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        public static GrainId Parse(string value)
        {
            if (!TryParse(value, out var result))
            {
                ThrowInvalidGrainId(value);

                static void ThrowInvalidGrainId(string value) => throw new ArgumentException($"Unable to parse \"{value}\" as a grain id");
            }

            return result;
        }

        /// <summary>
        /// Creates a new <see cref="GrainType"/> instance.
        /// </summary>
        public static bool TryParse(string? value, out GrainId grainId)
        {
            int i;
            if (value is null || (i = value.IndexOf('/')) < 0)
            {
                grainId = default;
                return false;
            }

            grainId = new(new GrainType(Encoding.UTF8.GetBytes(value, 0, i)), new IdSpan(Encoding.UTF8.GetBytes(value, i + 1, value.Length - i - 1)));
            return true;
        }

        /// <summary>
        /// <see langword="true"/> if this instance is the default value, <see langword="false"/> if it is not.
        /// </summary>
        public bool IsDefault => Type.IsDefault && Key.IsDefault;

        /// <inheritdoc/>
        public override bool Equals(object? obj) => obj is GrainId id && Equals(id);

        /// <inheritdoc/>
        public bool Equals(GrainId other) => Type.Equals(other.Type) && Key.Equals(other.Key);

        /// <inheritdoc/>
        public override int GetHashCode() => HashCode.Combine(Type, Key);

        /// <summary>
        /// Generates a uniform, stable hash code for a grain id.
        /// </summary>
        public uint GetUniformHashCode()
        {
            // This value must be stable for a given id and equal for all nodes in a cluster.
            // HashCode.Combine does not currently offer stability with respect to its inputs.
            unchecked
            {
                var hash = 17u;
                hash = hash * 31 + Type.GetUniformHashCode();
                hash = hash * 31 + Key.GetUniformHashCode();
                return hash;
            }
        }

        /// <inheritdoc/>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("tv", GrainType.UnsafeGetArray(Type));
            info.AddValue("th", Type.GetHashCode());
            info.AddValue("kv", IdSpan.UnsafeGetArray(Key));
            info.AddValue("kh", Key.GetHashCode());
        }

        /// <inheritdoc/>
        public int CompareTo(GrainId other)
        {
            var typeComparison = Type.CompareTo(other.Type);
            if (typeComparison != 0) return typeComparison;

            return Key.CompareTo(other.Key);
        }

        /// <summary>
        /// Compares the provided operands for equality.
        /// </summary>
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        /// <returns><see langword="true"/> if the provided values are equal, otherwise <see langword="false"/>.</returns>
        public static bool operator ==(GrainId left, GrainId right) => left.Equals(right);

        /// <summary>
        /// Compares the provided operands for inequality.
        /// </summary>
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        /// <returns><see langword="true"/> if the provided values are not equal, otherwise <see langword="false"/>.</returns>
        public static bool operator !=(GrainId left, GrainId right) => !left.Equals(right);

        /// <inheritdoc/>
        public override string ToString() => $"{Type}/{Key}";

        string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ToString();

        bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
            => destination.TryWrite($"{Type}/{Key}", out charsWritten);
    }

    /// <summary>
    /// Functionality for converting a <see cref="GrainId"/> to and from a JSON string.
    /// </summary>
    public sealed class GrainIdJsonConverter : JsonConverter<GrainId>
    {
        /// <inheritdoc />
        public override GrainId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => GrainId.Parse(reader.GetString()!);

        /// <inheritdoc />
        public override void Write(Utf8JsonWriter writer, GrainId value, JsonSerializerOptions options)
        {
            var type = value.Type.AsSpan();
            var key = value.Key.AsSpan();
            Span<byte> buf = stackalloc byte[type.Length + key.Length + 1];

            type.CopyTo(buf);
            buf[type.Length] = (byte)'/';
            key.CopyTo(buf[(type.Length + 1)..]);

            writer.WriteStringValue(buf);
        }
    }
}


text:
package project.test.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import project.test.domain.City;

public interface CityRepository extends JpaRepository<City, Long> {

//	@Query("select c from City c where UPPER(c.name) like UPPER(?1) or UPPER(c.state) like UPPER(?1) or UPPER(c.country) like UPPER(?1)")
//	Page<City> search(String value, Pageable page);
	@Query("select c from City c where c.name = ?1")
	City findByName(String name);

}


text:
.class final Lcom/meizu/util/Connectivity$1;
.super Ljava/lang/Object;
.source "Connectivity.java"

# interfaces
.implements Ljavax/net/ssl/X509TrustManager;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/meizu/util/Connectivity;->createInvalidCertificationAcceptingSSLSocketFactory()Lorg/apache/http/conn/ssl/SSLSocketFactory;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 27
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public checkClientTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;)V
    .locals 0
    .param p1, "xcs"    # [Ljava/security/cert/X509Certificate;
    .param p2, "string"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/cert/CertificateException;
        }
    .end annotation

    .prologue
    .line 28
    return-void
.end method

.method public checkServerTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;)V
    .locals 0
    .param p1, "xcs"    # [Ljava/security/cert/X509Certificate;
    .param p2, "string"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/cert/CertificateException;
        }
    .end annotation

    .prologue
    .line 29
    return-void
.end method

.method public getAcceptedIssuers()[Ljava/security/cert/X509Certificate;
    .locals 1

    .prologue
    .line 30
    const/4 v0, 0x0

    return-object v0
.end method


text:
//define(function() {
var pd = pd || {},
    getMissingValue = function (valueId, elm) {
        var missingValueFunctions = {
                "id" : getIdFromDom,
                "initial": pd.getInitialFromDom
            },
            opt = pd.options[valueId];
        pd.options[valueId] = (opt === undefined) ? missingValueFunctions[valueId](elm) : opt;
    },
    getIdFromDom = function (elm) {
        return elm.attr("id");
    };
//move to new file

    pd.options = {};
    pd.vmObjects = [];
    pd.createObject = function () {
        var elm = $(this);
        pd.options = {};
        pd.options = pd.parseDataVm(elm.attr("data-vm"));
        elm.data("options", pd.options);
        getMissingValue("id", elm);
        getMissingValue("initial", elm);
        pd.setDataBind(elm);
        pd.vmObjects.push(elm);
    };

    pd.parseDom = function () {
        var elms = $("[data-vm]");
        elms.each(pd.createObject);
        return elms;
    };

//    return pd;
//})


text:
'use strict';

// MODULES //

var dmap = require( '@stdlib/strided/base/dmap' ).ndarray;
var deg2rad = require( '@stdlib/math/base/special/deg2rad' );

// MAIN //

/**
* Converts each element in a double-precision floating-point strided array `x` from degrees to radians and assigns the results to elements in a double-precision floating-point strided array `y`.
*
* @param {NonNegativeInteger} N - number of indexed elements
* @param {Float64Array} x - input array
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {Float64Array} y - destination array
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @returns {Float64Array} `y`
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 0.0, 30.0, 45.0, 60.0, 90.0 ] );
* var y = new Float64Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* ddeg2rad( x.length, x, 1, 0, y, 1, 0 );
* // y => <Float64Array>[ 0.0, ~0.524, ~0.785, ~1.047, ~1.571 ]
*/
function ddeg2rad( N, x, strideX, offsetX, y, strideY, offsetY ) {
	return dmap( N, x, strideX, offsetX, y, strideY, offsetY, deg2rad );
}

// EXPORTS //

module.exports = ddeg2rad;


text:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
	<render-kit>
		<renderer>
			<component-family>javax.faces.Output</component-family>
			<renderer-type>com.gregorbyte.TextDiff</renderer-type>
			<renderer-class>com.gregorbyte.xsp.renderkit.TextDiffRenderer</renderer-class>
		</renderer>
	</render-kit>
</faces-config>


text:
"""
=========
Streaming
=========
"""

# Order matters here!
import streaming._iterator
import streaming.itertools
import streaming.operators
import streaming.abstractstream
import streaming.stream
import streaming.signal

from streaming.stream import Stream, BlockStream
from streaming.signal import constant, sine


text:
export HOME=/Volumes/StorageDrive/jmthompson
export TARGET=${HOME}/git/lotr-card-game/src
export FORMAT="--format amd"

madge ${FORMAT} --circular ${TARGET}


text:
var UIPageViewEditorTest = UIBaseLayer.extend({
    ctor: function () {
        this._super();
        var root = this._parseUIFile("res/cocosui/CCS/PageView/pageview_1.json");
        this._mainNode.addChild(root);

        var back_label =ccui.helper.seekWidgetByName(root, "back");
        back_label.addTouchEventListener(this.backEvent,this);

        var pageView =ccui.helper.seekWidgetByName(root, "PageView_1269");
        pageView.addEventListener(this.pageViewEvent, this);
    },

    pageViewEvent: function (sender, type) {
        switch (type) {
            case ccui.PageView.EVENT_TURNING:
                var pageView = sender;
                this._topDisplayText.setString("page = " + (pageView.getCurPageIndex() + 1));
                break;
            default:
                break;
        }
    }
});


text:
"""External function interface to MPS libraroes."""
from __future__ import absolute_import as _abs

from .. import api as _api
from .. import intrin as _intrin

def matmul(lhs, rhs, transa=False, transb=False):
    """Create an extern op that compute matrix mult of A and rhs with CrhsLAS

    This function serves as an example on how to calle external libraries.

    Parameters
    ----------
    lhs : Tensor
        The left matrix operand
    rhs : Tensor
        The right matrix operand
    transa : bool
        Whether transpose lhs
    transb : bool
        Whether transpose rhs

    Returns
    -------
    C : Tensor
        The result tensor.
    """
    m = lhs.shape[0]
    n = rhs.shape[1]
    return _api.extern(
        (n, m), [lhs, rhs],
        lambda ins, outs: _intrin.call_packed(
            "tvm.contrib.mps.matmul", ins[0], ins[1], outs[0], transa, transb),
        name="C")


text:
import { FormatterCallback } from '../formatter'

const jsonFormatter: FormatterCallback = function (formatter) {
  formatter.on('end', (event) => {
    console.log(JSON.stringify(event.arrAllMessages))
  })
}

module.exports = jsonFormatter


text:
declare function ParseTorrentFile(torrent: Buffer | ParseTorrentFile.Torrent): ParseTorrentFile.Instance;

declare namespace ParseTorrentFile {
    function decode(torrent: Buffer | Torrent): Instance;
    function encode(parsed: Instance): Buffer;

    interface TorrentInfo {
        'name.utf-8'?: string;
        name?: string;
        files?: File[];
        'piece length'?: number;
        pieces?: number;
        private?: boolean;
    }

    interface Torrent {
        info?: TorrentInfo;
        'creation date'?: number;
        'created by'?: string;
        comment?: Buffer;
        'announce-list'?: string[][];
        announce?: string;
        'url-list'?: Buffer;
    }

    interface ParsedFile {
        path: string;
        name: string;
        length: number;
        offset: number;
    }

    interface Instance extends Object {
        info?: TorrentInfo;
        infoBuffer?: Buffer;
        infoHash?: string;
        infoHashBuffer?: Buffer;
        name?: string;
        private?: boolean;
        created?: Date;
        createdBy?: string;
        announce?: string[];
        urlList?: string[];
        pieceLength?: number;
        lastPieceLength?: number;
        pieces?: string[];
        length?: number;
        files?: ParsedFile[];
    }
}

export = ParseTorrentFile;