text:
package org.arong.axmlswing;

import java.awt.Container;
import java.awt.Rectangle;
import java.awt.Window;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JRootPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.JToolTip;
import javax.swing.JTree;
import javax.swing.JViewport;
import javax.swing.JWindow;
import javax.swing.table.JTableHeader;

import org.arong.axmlswing.attribute.AttributeModel;
import org.arong.axmlswing.attribute.AttributeTransfer;
import org.arong.axmlswing.attribute.AttributeValidator;
import org.arong.axmlswing.event.AbstractListener;
import org.arong.axmlswing.manager.ComponentManager;
import org.arong.axmlswing.manager.ListenerManager;
import org.arong.axmlswing.manager.VarsManager;
import org.arong.axmlswing.util.BeanUtil;
import org.arong.axmlswing.util.Dom4jUtil;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 布局文件加载器
 * @author dipoo
 * @since 2015-01-28
 */
public class GuiXmlLoader {

	public final static String LAYOUT_WINDOW_PREFFIX = "window:";

	private static Boolean log = true;

	public static void load(String path) throws Exception{
		Document doc = null;
		try {
			doc = Dom4jUtil.getDOM(URLDecoder.decode(path, "UTF-8"));
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "exception with loading the file:" + path);
			e.printStackTrace();
		}
		AttributeModel attr;
		Element e = doc.getRootElement();

		//检测是否已存在
		if(ComponentManager.getComponent(LAYOUT_WINDOW_PREFFIX + path) != null){
			ComponentManager.getComponent(LAYOUT_WINDOW_PREFFIX + path).setVisible(true);
			return;
		}
		try {
			attr = parseAttribute(e);
			Window window;
			if("jframe".equals(e.getName().toLowerCase())){
				window = new JFrame();
			}else if("jdialog".equals(e.getName().toLowerCase())){
				window = new JDialog();
			}else if("jwindow".equals(e.getName().toLowerCase())){
				window = new JWindow();
			}else{
				JOptionPane.showMessageDialog(null, "只能使用JFrame/JWindow/JDialog作为根元素!");
				return;
			}
			if(attr.getId() != null){
				ComponentManager.putComponent(attr.getId(), window);
			}
			if(ComponentManager.getMainWindow() == null){
				ComponentManager.setMainWindow(window);
			}
			BeanUtil.apply(attr, window);
			ComponentManager.setCommonAttribute(window, attr);
			if(window instanceof JFrame){
				if(AttributeValidator.bounds(attr.getMaximizedBounds())){
					int[] arr = AttributeTransfer.bounds(attr.getMaximizedBounds());
					((JFrame)window).setMaximizedBounds(new Rectangle(arr[0], arr[1], arr[2], arr[3]));
				}
			}
			if(!AttributeValidator.isBlank(attr.getIconImage())){
				window.setIconImage(((ImageIcon)AttributeTransfer.icon(attr.getIconImage())).getImage());
			}
			if(!AttributeValidator.isBlank(attr.getLocationRelativeTo())){
				window.setLocationRelativeTo(ComponentManager.getComponent(attr.getLocationRelativeTo()));
			}
			parse(window, e, attr);
			EventListener l = ListenerManager.getListener(attr.getId());
			if(l != null){
				//设置监听器
				ListenerManager.setComponentListeners(window, l);
				//执行初始化
				((AbstractListener)l).init(window);
			}
			//实例化监听器类
			if(attr.getListener() != null){
				try {
					Class.forName(attr.getListener()).newInstance();
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				} catch (InstantiationException e1) {
					e1.printStackTrace();
				}
			}
			window.setVisible(true);
			//将此布局文件放入组件管理器
			ComponentManager.putComponent(LAYOUT_WINDOW_PREFFIX + path, window);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} finally{
		}
	}

	/**
	 * 解析xml文档
	 */
	@SuppressWarnings("unchecked")
	public static void parse(Container container, Element e, AttributeModel attr){
		try {
			Iterator<Element> it = e.elementIterator();
			String id;
			String tagName;
			while(it.hasNext()){
				e = it.next();
				attr = parseAttribute(e);
				id = attr.getId();
				tagName = e.getName().toLowerCase();
				EventListener l = ListenerManager.getListener(id);
				/**
				 * 元素的属性可以对应一个组件的javabean,使用反射一一对应
				 */
				if("jframe".equals(tagName)){
					JFrame comp = new JFrame();
					common(id, comp, attr, l, null, e);
				}else if("jwindow".equals(tagName)){
					JWindow comp = new JWindow();
					common(id, comp, attr, l, null, e);
				}else if("jdialog".equals(tagName)){
					JDialog comp = new JDialog();
					common(id, comp, attr, l, null, e);
				}else if("jtextfield".equals(tagName)){
					JTextField comp = new JTextField();
					common(id, comp, attr, l, container, e);
				}else if("jtextarea".equals(tagName)){
					JTextArea comp = new JTextArea();
					common(id, comp, attr, l, container, e);
				}else if("jlabel".equals(tagName)){
					JLabel comp = new JLabel();
					common(id, comp, attr, l, container, e);
				}else if("jbutton".equals(tagName)){
					JButton comp = new JButton();
					common(id, comp, attr, l, container, e);
				}else if("jtogglebutton".equals(tagName)){
					JToggleButton comp = new JToggleButton();
					common(id, comp, attr, l, container, e);
				}else if("jcombobox".equals(tagName)){
					JComboBox comp;
					if(!AttributeValidator.isBlank(attr.getItems())){
						comp = new JComboBox(attr.getItems().split(","));
					}else{
						comp = new JComboBox();
					}
					common(id, comp, attr, l, container, e);
				}else if("jcheckbox".equals(tagName)){
					JCheckBox comp = new JCheckBox();
					common(id, comp, attr, l, container, e);
				}else if("jradiobutton".equals(tagName)){
					JRadioButton comp = new JRadioButton();
					common(id, comp, attr, l, container, e);
				}else if("jmenuitem".equals(tagName)){
					JMenuItem comp = new JMenuItem();
					common(id, comp, attr, l, container, e);
				}else if("jmenu".equals(tagName)){
					JMenu comp = new JMenu();
					common(id, comp, attr, l, container, e);
				}else if("jcheckboxmenuitem".equals(tagName)){
					JCheckBoxMenuItem comp = new JCheckBoxMenuItem();
					common(id, comp, attr, l, container, e);
				}else if("jradiobuttonmenuitem".equals(tagName)){
					JRadioButtonMenuItem comp = new JRadioButtonMenuItem();
					common(id, comp, attr, l, container, e);
				}else if("jmenubar".equals(tagName)){
					JMenuBar comp = new JMenuBar();
					common(id, comp, attr, l, container, e);
				}else if("jpanel".equals(tagName)){
					JPanel comp = new JPanel();
					common(id, comp, attr, l, container, e);
				}else if("jrootpane".equals(tagName)){
					JRootPane comp = new JRootPane();
					common(id, comp, attr, l, container, e);
				}else if("jscrollpane".equals(tagName)){
					JScrollPane comp = new JScrollPane();
					common(id, comp, attr, l, container, e);
				}else if("jscrollbar".equals(tagName)){
					JScrollBar comp = new JScrollBar();
					common(id, comp, attr, l, container, e);
				}else if("jcolorchooser".equals(tagName)){
					JColorChooser comp = new JColorChooser();
					common(id, comp, attr, l, container, e);
				}else if("jinternalframe".equals(tagName)){
					JInternalFrame comp = new JInternalFrame();
					common(id, comp, attr, l, container, e);
				}else if("jlayeredpane".equals(tagName)){
					JLayeredPane comp = new JLayeredPane();
					common(id, comp, attr, l, container, e);
				}else if("jlist".equals(tagName)){
					JList comp = new JList();
					if(!AttributeValidator.isBlank(attr.getItems())){
						comp = new JList(attr.getItems().split(","));
					}else{
						comp = new JList();
					}
					common(id, comp, attr, l, container, e);
				}else if("jpopupmenu".equals(tagName)){
					JPopupMenu comp = new JPopupMenu();
					common(id, comp, attr, l, container, e);
				}else if("jprogressbar".equals(tagName)){
					JProgressBar comp = new JProgressBar();
					common(id, comp, attr, l, container, e);
				}else if("jseparator".equals(tagName)){
					JSeparator comp = new JSeparator();
					common(id, comp, attr, l, container, e);
				}else if("jslider".equals(tagName)){
					JSlider comp = new JSlider();
					common(id, comp, attr, l, container, e);
				}else if("jspinner".equals(tagName)){
					JSpinner comp = new JSpinner();
					common(id, comp, attr, l, container, e);
				}else if("jsplitpane".equals(tagName)){
					JSplitPane comp = new JSplitPane();
					common(id, comp, attr, l, container, e);
				}else if("jtabbedpane".equals(tagName)){
					JTabbedPane comp = new JTabbedPane();
					common(id, comp, attr, l, container, e);
				}else if("jtable".equals(tagName)){
					JTable comp = new JTable();
					common(id, comp, attr, l, container, e);
				}else if("jtableheader".equals(tagName)){
					JTableHeader comp = new JTableHeader();
					common(id, comp, attr, l, container, e);
				}else if("jtoolbar".equals(tagName)){
					JToolBar comp = new JToolBar();
					common(id, comp, attr, l, container, e);
				}else if("jtooltip".equals(tagName)){
					JToolTip comp = new JToolTip();
					common(id, comp, attr, l, container, e);
				}else if("jfilechooser".equals(tagName)){
					JFileChooser comp = new JFileChooser();
					common(id, comp, attr, l, container, e);
				}else if("jtree".equals(tagName)){
					JTree comp = new JTree();
					common(id, comp, attr, l, container, e);
				}else if("jviewport".equals(tagName)){
					JViewport comp = new JViewport();
					common(id, comp, attr, l, container, e);
				}else if("jeditorpane".equals(tagName)){
					JEditorPane comp = new JEditorPane();
					common(id, comp, attr, l, container, e);
				}else if("jdesktoppane".equals(tagName)){
					JDesktopPane comp = new JDesktopPane();
					common(id, comp, attr, l, container, e);
				}else if("jformattedtextfield".equals(tagName)){
					JFormattedTextField comp = new JFormattedTextField();
					common(id, comp, attr, l, container, e);
				}else if("jpasswordfield".equals(tagName)){
					JPasswordField comp = new JPasswordField();
					common(id, comp, attr, l, container, e);
				}else if("jtextpane".equals(tagName)){
					JTextPane comp = new JTextPane();
					common(id, comp, attr, l, container, e);
				}else{
					//扩展组件
					String classPkg = VarsManager.getExtentsCompValue(tagName);
					if(classPkg != null){
						try {
							Class<?> clazz = Class.forName(classPkg);
							Object o = clazz.newInstance();
							if(o instanceof Container){
								Container c = (Container)o;
								common(id, c, attr, l, container, e);
							}else{
								o = null;
							}
						} catch (ClassNotFoundException e1) {
						} catch (InstantiationException e1) {
						}
					}
				}
			}
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} finally{

		}
	}

	public static void common(String id, Container comp, AttributeModel attr, EventListener l, Container container, Element e){
		if(id != null){
			//将组件放进组件管理器
			ComponentManager.putComponent(id, comp);
		}
		AttributeModel defaultAttr = VarsManager.getDefaults().get(e.getName().toLowerCase());
		if(defaultAttr != null && !"true".equals(e.attributeValue("a-ignore"))){
			//设置组件全局属性
			AttributeModel temp = new AttributeModel();
			BeanUtil.apply(defaultAttr, temp);
			BeanUtil.apply(attr, temp);
			attr = temp;
		}
		//设置基本属性,可以覆盖全局属性
		BeanUtil.apply(attr, comp);
		//转换设置组件的公共属性
		ComponentManager.setCommonAttribute(comp, attr);
		//转换设置不同组件的属性
		ComponentManager.setComponentSpecificAttribute(e.getName().toLowerCase(), comp, attr);
		if(l != null){
			//设置监听器
			ListenerManager.setComponentListeners(comp, l);
			//执行初始化
			((AbstractListener)l).init(comp);
		}
		if(container != null && !"false".equals(e.attributeValue("a-added"))){
			if(container instanceof JFrame){
				((JFrame)container).getContentPane().add(comp);
			}else if(container instanceof JWindow){
				((JWindow)container).getContentPane().add(comp);
			}else if(container instanceof JDialog){
				((JDialog)container).getContentPane().add(comp);
			}else if(container instanceof JScrollPane){
				((JScrollPane)container).getViewport().setView(comp);
			}else{
				container.add(comp);
			}
		}
		parse(comp, e, attr);
	}

	@SuppressWarnings("unchecked")
	private static AttributeModel parseAttribute(Element e) throws IllegalArgumentException, IllegalAccessException{
		List<Attribute> attrs = e.attributes();
		AttributeModel model = new AttributeModel();
		if(attrs != null && attrs.size() > 0){
			Field[] fields = model.getClass().getDeclaredFields();
			for(Attribute attr : attrs){
				for(Field field : fields){
					if(attr.getName().equals(field.getName())){
						BeanUtil.setProperty(model, attr.getName(), new String[]{VarsManager.transfer(attr.getText())});
					}
				}
			}
		}
		return model;
	}

	public static void setLog(Boolean log) {
		GuiXmlLoader.log = log;
	}

	public static Boolean getLog() {
		return log;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <EditText
        android:id="@+id/input_edit_text"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:layout_margin="@dimen/mid_margin"
        android:hint="@string/enter_text_hint"
        android:inputType="textMultiLine"
        android:gravity="top"
        android:contentDescription="Text Input Control"/>
</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
Adafruit_Simple_AHRS::Adafruit_Simple_AHRS(Adafruit_Sensor* accelerometer, Adafruit_Sensor* magnetometer):
  _accel(accelerometer),
  _mag(magnetometer)
{}

// Create a simple AHRS from a device with multiple sensors.
Adafruit_Simple_AHRS::Adafruit_Simple_AHRS(Adafruit_Sensor_Set& sensors):
  _accel(sensors.getSensor(SENSOR_TYPE_ACCELEROMETER)),
  _mag(sensors.getSensor(SENSOR_TYPE_MAGNETIC_FIELD))
{}

// Compute orientation based on accelerometer and magnetometer data.
bool Adafruit_Simple_AHRS::getOrientation(sensors_vec_t* orientation) {
  // Validate input and available sensors.
  if (orientation == NULL || _accel == NULL || _mag == NULL) return false;

  // Grab an acceleromter and magnetometer reading.
  sensors_event_t accel_event;
  _accel->getEvent(&accel_event);
  sensors_event_t mag_event;
  _mag->getEvent(&mag_event);

  float const PI_F = 3.14159265F;

  // roll: Rotation around the X-axis. -180 <= roll <= 180
  // a positive roll angle is defined to be a clockwise rotation about the positive X-axis
  //
  //                    y
  //      roll = atan2(---)
  //                    z
  //
  // where:  y, z are returned value from accelerometer sensor
  orientation->roll = (float)atan2(accel_event.acceleration.y, accel_event.acceleration.z);

  // pitch: Rotation around the Y-axis. -180 <= roll <= 180
  // a positive pitch angle is defined to be a clockwise rotation about the positive Y-axis
  //
  //                                 -x
  //      pitch = atan(-------------------------------)
  //                    y * sin(roll) + z * cos(roll)
  //
  // where:  x, y, z are returned value from accelerometer sensor
  if (accel_event.acceleration.y * sin(orientation->roll) + accel_event.acceleration.z * cos(orientation->roll) == 0)
    orientation->pitch = accel_event.acceleration.x > 0 ? (PI_F / 2) : (-PI_F / 2);
  else
    orientation->pitch = (float)atan(-accel_event.acceleration.x / (accel_event.acceleration.y * sin(orientation->roll) + \
                                                                     accel_event.acceleration.z * cos(orientation->roll)));

  // heading: Rotation around the Z-axis. -180 <= roll <= 180
  // a positive heading angle is defined to be a clockwise rotation about the positive Z-axis
  //
  //                                       z * sin(roll) - y * cos(roll)
  //   heading = atan2(--------------------------------------------------------------------------)
  //                    x * cos(pitch) + y * sin(pitch) * sin(roll) + z * sin(pitch) * cos(roll))
  //
  // where:  x, y, z are returned value from magnetometer sensor
  orientation->heading = (float)atan2(mag_event.magnetic.z * sin(orientation->roll) - mag_event.magnetic.y * cos(orientation->roll), \
                                      mag_event.magnetic.x * cos(orientation->pitch) + \
                                      mag_event.magnetic.y * sin(orientation->pitch) * sin(orientation->roll) + \
                                      mag_event.magnetic.z * sin(orientation->pitch) * cos(orientation->roll));

  // Convert angular data to degree
  orientation->roll = orientation->roll * 180 / PI_F;
  orientation->pitch = orientation->pitch * 180 / PI_F;
  orientation->heading = orientation->heading * 180 / PI_F;

  return true;
}


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Castle.Core;
using Core;
using Core.Descriptions;
using Core.Exceptions;
using Core.Interfaces;

namespace SqlServer {
    [CastleComponent("SqlServer.Constraints", typeof (IConstraint), Lifestyle = LifestyleType.Transient)]
    public class Constraints : SqlServerEntity, IConstraint {
        public Constraints(ConnectionInfo database) {
            Initialize(database);
        }

        public void CreatePrimaryKey(PrimaryKeyDescription primaryKeyDescription) {
            var primaryKey = SqlServerDatabase.GetPrimaryKey(new TableDescription {
                Schema = primaryKeyDescription.Schema,
                Name = primaryKeyDescription.TableName
            });

            if (primaryKey != null) throw new MultiplePrimaryKeysException();

            primaryKey = SqlServerDatabase.GetPrimaryKey(primaryKeyDescription.Name, primaryKeyDescription.Schema);
            if (primaryKey != null) throw new InvalidConstraintNameException();

            var createPkCommandText = $"ALTER TABLE [{primaryKeyDescription.Schema}].[{primaryKeyDescription.TableName}] " +
                                      $"ADD CONSTRAINT [{primaryKeyDescription.Name}] " +
                                      $"PRIMARY KEY ({string.Join(",", primaryKeyDescription.Columns.Select(column => $"[{column.Name}]"))})";

            var command = new SqlCommand(createPkCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void RemovePrimaryKey(PrimaryKeyDescription primaryKeyDescription) {
            var primaryKey = SqlServerDatabase.GetPrimaryKey(primaryKeyDescription.Name, primaryKeyDescription.Schema);
            if (primaryKey == null) throw new ConstraintNotFoundException();

            var foreignKeys = SqlServerDatabase.GetForeignKeysReferencing(primaryKeyDescription);
            if (foreignKeys.Any()) throw new ReferencedConstraintException();

            var dropPkCommandText = $"ALTER TABLE [{primaryKeyDescription.Schema}].[{primaryKeyDescription.TableName}] " +
                                    $"DROP CONSTRAINT [{primaryKeyDescription.Name}]";

            var command = new SqlCommand(dropPkCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void CreateForeignKey(ForeignKeyDescription foreignKeyDescription) {
            if (!DescriptionIsValid(foreignKeyDescription))
                throw new InvalidDescriptionException();

            if (ThereIsAnotherForeignKeyWithTheSameName(foreignKeyDescription))
                throw new InvalidConstraintNameException();

            if (!ReferencedColumnsAreValid(foreignKeyDescription))
                throw new InvalidReferenceColumnException();

            var createFkCommandText = $"ALTER TABLE [{foreignKeyDescription.Schema}].[{foreignKeyDescription.TableName}] "+
                                      $"ADD CONSTRAINT [{foreignKeyDescription.Name}] " +
                                      $"FOREIGN KEY ({string.Join(",", foreignKeyDescription.Columns.Select(column => $"[{column.Key}]"))}) " +
                                      $"REFERENCES [{foreignKeyDescription.Columns.Values.First().Schema}].[{foreignKeyDescription.Columns.Values.First().TableName}] " +
                                      $"({string.Join(",", foreignKeyDescription.Columns.Values.Select(column => $"[{column.Name}]"))})";

            var command = new SqlCommand(createFkCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void RemoveForeignKey(ConstraintDescription foreignKeyDescription) {
            var foreignKeys = SqlServerDatabase.GetForeignKeys(new TableDescription {
                Schema = foreignKeyDescription.Schema,
                Name = foreignKeyDescription.TableName
            });

            if (!foreignKeys.Any(key => key.Schema.Equals(foreignKeyDescription.Schema) &&
                                        key.TableName.Equals(foreignKeyDescription.TableName) &&
                                        key.Name.Equals(foreignKeyDescription.Name)))
                throw new ConstraintNotFoundException();

            var dropFkCommandText = $"ALTER TABLE [{foreignKeyDescription.Schema}].[{foreignKeyDescription.TableName}] " +
                                    $"DROP CONSTRAINT [{foreignKeyDescription.Name}]";

            var command = new SqlCommand(dropFkCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void CreateUnique(UniqueDescription uniqueDescription) {
            var uniqueKey = SqlServerDatabase.GetUniqueKey(uniqueDescription.Name, uniqueDescription.Schema);
            if (uniqueKey != null) throw new InvalidConstraintNameException();

            if (!ReferencedColumnsAreValid(uniqueDescription))
                throw new InvalidReferenceColumnException();

            var createUniqueCommnadText = $@"ALTER TABLE [{uniqueDescription.Schema}].[{uniqueDescription.TableName}] " +
                                          $"ADD CONSTRAINT [{uniqueDescription.Name}] " +
                                          $"UNIQUE ({string.Join(",", uniqueDescription.Columns.Select(column => $"[{column.Name}]"))})";

            var command = new SqlCommand(createUniqueCommnadText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void RemoveUnique(UniqueDescription uniqueDescription) {
            var uniqueKey = SqlServerDatabase.GetUniqueKey(uniqueDescription.Name, uniqueDescription.Schema);
            if (uniqueKey == null) throw new ConstraintNotFoundException();

            var foreignKeys = SqlServerDatabase.GetForeignKeysReferencing(uniqueDescription);
            if (foreignKeys.Any()) throw new ReferencedConstraintException();

            var gropUniqueCommandText = $"ALTER TABLE [{uniqueDescription.Schema}].[{uniqueDescription.TableName}] " +
                                        $"DROP CONSTRAINT [{uniqueDescription.Name}]";

            var command = new SqlCommand(gropUniqueCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void CreateDefault(DefaultDescription defaultDescription) {
            var defaults = SqlServerDatabase.GetDefaults();

            if (defaults.Any(d => d.Name.Equals(defaultDescription.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                  d.Schema.Equals(defaultDescription.Schema, StringComparison.InvariantCultureIgnoreCase)))
                throw new InvalidConstraintNameException();

            if (defaults.Any(d => d.Column.Equals(defaultDescription.Column) &&
                                  d.Schema.Equals(defaultDescription.Schema, StringComparison.InvariantCultureIgnoreCase) &&
                                  d.TableName.Equals(defaultDescription.TableName, StringComparison.InvariantCultureIgnoreCase)))
                throw new InvalidReferenceColumnException();

            var crateDefaultCommandText = $"ALTER TABLE [{defaultDescription.Schema}].[{defaultDescription.TableName}] " +
                                          $"ADD CONSTRAINT [{defaultDescription.Name}] "+
                                          $"DEFAULT {defaultDescription.DefaultValue} " +
                                          $"FOR [{defaultDescription.Column.Name}]";

            var command = new SqlCommand(crateDefaultCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        public void RemoveDefault(DefaultDescription defaultDescription) {
            var defaultValue = SqlServerDatabase.GetDefault(defaultDescription.Name, defaultDescription.Schema);
            if (defaultValue == null) throw new ConstraintNotFoundException();

            var dropDefaultCommandText = $"ALTER TABLE [{defaultDescription.Schema}].[{defaultDescription.TableName}] " +
                                         $"DROP CONSTRAINT [{defaultDescription.Name}]";

            var command = new SqlCommand(dropDefaultCommandText);

            SqlServerDatabase.ExecuteNonQuery(command);
        }

        private bool DescriptionIsValid(ForeignKeyDescription foreignKeyDescription) {
            foreach (var column in foreignKeyDescription.Columns.Values) {
                if (foreignKeyDescription.Columns.Values.Count(v =>
                    v.Name.Equals(column.Name, StringComparison.InvariantCultureIgnoreCase) &&
                    v.TableName.Equals(column.TableName, StringComparison.InvariantCultureIgnoreCase)) > 1) {
                    return false;
                }
            }

            return true;
        }

        private bool ThereIsAnotherForeignKeyWithTheSameName(ForeignKeyDescription foreignKeyDescription) {
            var foreignKeys = SqlServerDatabase.GetForeignKeys(new TableDescription {
                Schema = foreignKeyDescription.Schema,
                Name = foreignKeyDescription.TableName
            });

            return foreignKeys.Any(key => key.Name.Equals(foreignKeyDescription.Name, StringComparison.InvariantCultureIgnoreCase));
        }

        private bool ReferencedColumnsAreValid(ForeignKeyDescription foreignKeyDescription) {
            foreach (var column in foreignKeyDescription.Columns.Values) {
                var primaryKey = SqlServerDatabase.GetPrimaryKey(new TableDescription {
                    Schema = column.Schema,
                    Name = column.TableName
                });

                if (primaryKey == null || !primaryKey.Columns.Any(c => c.FullName.Equals(column.FullName, StringComparison.InvariantCultureIgnoreCase)))
                    return false;
            }

            return true;
        }

        private bool ReferencedColumnsAreValid(UniqueDescription uniqueDescription) {
            Database.Tables.Refresh();
            var table = Database.Tables[uniqueDescription.TableName, uniqueDescription.Schema];
            if (table == null) return false;

            var invalidTypes = new List<string> { "text", "ntext", "image", "xml", "geography", "geometry" };
            foreach (var columnDescription in uniqueDescription.Columns) {
                if (uniqueDescription.Columns.Count(c => c.FullName.Equals(columnDescription.FullName, StringComparison.InvariantCultureIgnoreCase)) > 1)
                    return false;

                var column = table.Columns[columnDescription.Name];
                if (column == null) return false;

                var description = SqlServerDatabase.GetColumn(uniqueDescription.Schema, uniqueDescription.TableName, columnDescription.Name);
                if (description == null) return false;

                if (description.Type.Equals("varchar", StringComparison.InvariantCultureIgnoreCase) &&
                    int.Parse(description.Length) > 900)
                    return false;

                if (description.Type.Equals("nvarchar", StringComparison.InvariantCultureIgnoreCase) &&
                    int.Parse(description.Length) > 400)
                    return false;

                if (invalidTypes.Any(t => t.Equals(description.Type, StringComparison.InvariantCultureIgnoreCase)))
                    return false;
            }

            if (SqlServerDatabase.TableHasDuplicatedValuesForColumns(uniqueDescription.Schema, uniqueDescription.TableName,
                uniqueDescription.Columns.Select(c => c.Name).ToList()))
                return false;

            return true;
        }
    }
}


text:
package org.javalite.activeweb.freemarker.tags;

import org.javalite.activeweb.freemarker.FreeMarkerTag;

import java.io.Writer;
import java.util.Map;

/**
 * @author igor on 6/22/14.
 */
public class HeaderTag extends FreeMarkerTag {
    @Override
    protected void render(Map params, String body, Writer writer) throws Exception {
        writer.write("...and the header message is: " + header("message"));
    }
}


text:
using System.IO;

namespace Sharp.Xmpp.Extensions.Socks5
{
    /// <summary>
    /// Adds extension methods to the BinaryReader class to simplify the
    /// deserialization of SOCKS5 messages.
    /// </summary>
    internal static class BinaryReaderExtensions
    {
        /// <summary>
        /// Reads an unsigned integer value from the underlying stream,
        /// optionally using big endian byte ordering.
        /// </summary>
        /// <param name="reader">Extension method for BinaryReader.</param>
        /// <param name="bigEndian">Set to true to interpret the integer value
        /// as big endian value.</param>
        /// <returns>The 32-byte unsigned integer value read from the underlying
        /// stream.</returns>
        public static uint ReadUInt32(this BinaryReader reader, bool bigEndian)
        {
            if (!bigEndian)
                return reader.ReadUInt32();
            int ret = 0;
            ret |= reader.ReadByte() << 24;
            ret |= reader.ReadByte() << 16;
            ret |= reader.ReadByte() << 8;
            ret |= reader.ReadByte() << 0;
            return (uint)ret;
        }

        /// <summary>
        /// Reads an unsigned short value from the underlying stream, optionally
        /// using big endian byte ordering.
        /// </summary>
        /// <param name="reader">Extension method for BinaryReader.</param>
        /// <param name="bigEndian">Set to true to interpret the short value
        /// as big endian value.</param>
        /// <returns>The 16-byte unsigned short value read from the underlying
        /// stream.</returns>
        public static ushort ReadUInt16(this BinaryReader reader, bool bigEndian)
        {
            if (!bigEndian)
                return reader.ReadUInt16();
            int ret = 0;
            ret |= reader.ReadByte() << 8;
            ret |= reader.ReadByte() << 0;
            return (ushort)ret;
        }

        /// <summary>
        /// Reads an short value from the underlying stream, optionally using
        /// big endian byte ordering.
        /// </summary>
        /// <param name="reader">Extension method for BinaryReader.</param>
        /// <param name="bigEndian">Set to true to interpret the short value
        /// as big endian value.</param>
        /// <returns>The 16-byte short value read from the underlying
        /// stream.</returns>
        public static short ReadInt16(this BinaryReader reader, bool bigEndian)
        {
            if (!bigEndian)
                return reader.ReadInt16();
            int ret = 0;
            ret |= reader.ReadByte() << 8;
            ret |= reader.ReadByte() << 0;
            return (short)ret;
        }
    }
}


text:
#include "LocationModule.h"

namespace wfcore {

LocationModule::LocationModule()
{

}

LocationModule::~LocationModule()
{

}

//--------------------------------------------------------------------------
// starting / stopping

void
LocationModule::startPositioning()
{
   startPositioning(m_currentConfig);
}

void
LocationModule::startPositioning(LocationConfig config)
{
   m_currentConfig = config;
   m_proxy.connectToProviders(config);
}

//--------------------------------------------------------------------------
// listener methods

void
LocationModule::registerLocationListener(const LocationListener* listener)
{

}

void
LocationModule::deregisterLocationListener(const LocationListener* listener)
{

}

void
LocationModule::newPosition(WFAPI::WGS84Coordinate* coord)
{
   // update all listeners with the new position
}

}


text:
from pyparsing import (Group, Suppress, Optional, Keyword, SkipTo, LineEnd)
from ..common import (ipv4Address, ipv4AddressNetwork, ipv4Prefix,
                      suppressedKeyword, naturalNumber, accesslistName)

action = (Keyword('permit') ^
          Keyword('deny'))('action')

ipv4AddressHost = suppressedKeyword('host') + ipv4Address
ipv4AddressAny = Keyword('any')

accessListStart = Suppress(Keyword('access-list'))

# Standard access-list
standardAccessListAddress = (ipv4AddressNetwork ^
                             ipv4AddressHost ^
                             ipv4AddressAny ^
                             ipv4Address)('address')
remarkAction = (suppressedKeyword('remark') +
                         SkipTo(LineEnd())('remark'))
standardAccessListOtherActions = (action +
                                  standardAccessListAddress)
standardAccessListActions = (remarkAction ^
                             standardAccessListOtherActions)
standardAccessList = Group(accessListStart +
                           naturalNumber('number') +
                           standardAccessListActions)('standard')

# Extended access-list
extendedAccessListAddress = (ipv4AddressNetwork ^
                             ipv4AddressHost ^
                             ipv4AddressAny)('address')
extendedAccessListOtherActions = (action +
                                  Suppress(Keyword('ip')) +
                                  extendedAccessListAddress('source') +
                                  extendedAccessListAddress('destination'))
extendedAccessListActions = (remarkAction ^
                             extendedAccessListOtherActions)('action')
extendedAccessList = Group(accessListStart +
                           naturalNumber('number') +
                           extendedAccessListActions)('extended')

# Named access-list
namedAccessListAddress = (ipv4Prefix ^
                          ipv4AddressAny)('address')
namedAccessListOtherActions = (action +
                               namedAccessListAddress +
                               Optional(Keyword('exact-match')))
namedAccessListActions = (remarkAction ^
                          namedAccessListOtherActions)
namedAccessList = Group(accessListStart +
                        accesslistName('name') +
                        namedAccessListActions)('named')

accessList = (standardAccessList ^
              extendedAccessList ^
              namedAccessList)


text:
<?php ob_start(); /* Template Name: Registrering */ ?>

<?php get_header(); ?>

    <?php echo do_shortcode('[bv_signup_form]'); ?>

Har du ett konto?

	    <form method="post" class="signup_login--form" action="<?php echo home_url('/logga-in') ?>">
	      <button class="signup_login--btn" title="Logga in">Logga in</button>
	    </form>

När du registrerar dig godkänner du Bonvelos användarvillkor.

<?php get_footer(); ?>


text:
@interface MainViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIStackView *stackView;

@property (nonatomic, strong) ModulesViewController *modulesViewController;
@property (nonatomic, strong) UIView *modulesViewContainer;
@property (nonatomic, strong) NSLayoutConstraint *modulesHeightConstraint;

@end

@implementation MainViewController

- (instancetype)init {
    self = [super init];
    if (self) {

        self.modulesViewController = [[ModulesViewController alloc] init];
    }
    return self;
}

- (void)loadView {

    self.view = [[UIView alloc] init];
    self.view.backgroundColor = [UIColor clearColor];

    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];

    self.stackView = [[UIStackView alloc] initWithArrangedSubviews:@[]];
    self.stackView.backgroundColor = [UIColor blueColor];
    self.stackView.alignment = UIStackViewAlignmentFill;
    self.stackView.axis = UILayoutConstraintAxisVertical;
    [self.scrollView addSubview:self.stackView];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.scrollView ffs_fillContainer];

    [self.stackView ffs_constrainTopSpaceToContainer];
    [self.stackView ffs_constrainBottomSpaceToContainer];

    [self.stackView ffs_constrainTrailingSpaceToContainer];
    [self.stackView ffs_constrainLeadingSpaceToContainer];
    [self.stackView ffs_constrainWidthToView:self.scrollView constant:0.0];

//    UILabel *awesomeLabel = [[UILabel alloc] init];
//    awesomeLabel.backgroundColor = [UIColor whiteColor];
//    [awesomeLabel setText:@"Popular Designers"];
//
//    [self.stackView addArrangedSubview:awesomeLabel];

    if (self.modulesViewContainer == nil) {
        self.modulesViewContainer = [[UIView alloc] init];
    }

    if (self.modulesViewContainer.superview != self.stackView) {

        [self.modulesViewContainer removeFromSuperview];

        [self.stackView insertArrangedSubview:self.modulesViewContainer atIndex:0];
        [self addChildViewController:self.modulesViewController];
        [self.modulesViewContainer addSubview:self.modulesViewController.view];
        [self.modulesViewController didMoveToParentViewController:self];

        [self.modulesViewController reloadWithContent];

        [self.modulesViewController.view ffs_constrainTopSpaceToContainer:41.0];
        [self.modulesViewController.view ffs_constrainBottomSpaceToContainer];
        [self.modulesViewController.view ffs_constrainLeadingSpaceToContainer:0.0];
        [self.modulesViewController.view ffs_constrainTrailingSpaceToContainer:0.0];

        self.modulesHeightConstraint = [self.modulesViewController.view ffs_constrainHeight:[self.modulesViewController contentHeightForTraitCollection:self.view.traitCollection]];
    }

    self.modulesHeightConstraint.constant = [self.modulesViewController contentHeightForTraitCollection:self.view.traitCollection];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////

package gnu.trove;

//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////

/**
 * Iterator for double collections.
 *
 * @author Eric D. Friedman
 * @version $Id: PIterator.template,v 1.1 2006/11/10 23:28:00 robeden Exp $
 */

public class TDoubleIterator extends TPrimitiveIterator {
    /** the collection on which the iterator operates */
    private final TDoubleHash _hash;

    /**
     * Creates a TDoubleIterator for the elements in the specified collection.
     */
    public TDoubleIterator(TDoubleHash hash) {
	super(hash);
	this._hash = hash;
    }

    /**
     * Advances the iterator to the next element in the underlying collection
     * and returns it.
     *
     * @return the next double in the collection
     * @exception NoSuchElementException if the iterator is already exhausted
     */
    public double next() {
	moveToNextIndex();
	return _hash._set[_index];
    }
}// TDoubleIterator


text:
package com.evolveum.midpoint.client.api;

import com.evolveum.midpoint.client.api.verb.Post;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;

/**
 * @author jakmor
 */
public interface ObjectGenerateService<O extends ObjectType> extends Post<ObjectReference<O>>{

	PolicyItemsDefinitionBuilder item();
}


text:
<?php
echo CHtml::openTag('div', array('id' => $id, 'class' => 'relation'));
echo CHtml::ActiveRadiobuttonList(
		$model,
		$field,
		$data,
		$htmlOptions);
echo CHtml::closeTag('div');


text:
package com.lachesis.support.restful.context.vo;

public interface RequestVO {

}


text:
#include "thread_list.h"

#define ATRACE_TAG ATRACE_TAG_DALVIK

#include <cutils/trace.h>
#include <dirent.h>
#include <ScopedLocalRef.h>
#include <ScopedUtfChars.h>
#include <sys/types.h>
#include <unistd.h>

#include "base/mutex.h"
#include "base/mutex-inl.h"
#include "base/timing_logger.h"
#include "debugger.h"
#include "jni_internal.h"
#include "lock_word.h"
#include "monitor.h"
#include "scoped_thread_state_change.h"
#include "thread.h"
#include "trace.h"
#include "utils.h"
#include "well_known_classes.h"

namespace art {

static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);

ThreadList::ThreadList()
    : suspend_all_count_(0), debug_suspend_all_count_(0),
      thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
  CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
}

ThreadList::~ThreadList() {
  // Detach the current thread if necessary. If we failed to start, there might not be any threads.
  // We need to detach the current thread here in case there's another thread waiting to join with
  // us.
  bool contains = false;
  {
    Thread* self = Thread::Current();
    MutexLock mu(self, *Locks::thread_list_lock_);
    contains = Contains(self);
  }
  if (contains) {
    Runtime::Current()->DetachCurrentThread();
  }

  WaitForOtherNonDaemonThreadsToExit();
  // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
  //       Thread::Init.
  SuspendAllDaemonThreads();
}

bool ThreadList::Contains(Thread* thread) {
  return find(list_.begin(), list_.end(), thread) != list_.end();
}

bool ThreadList::Contains(pid_t tid) {
  for (const auto& thread : list_) {
    if (thread->GetTid() == tid) {
      return true;
    }
  }
  return false;
}

pid_t ThreadList::GetLockOwner() {
  return Locks::thread_list_lock_->GetExclusiveOwnerTid();
}

void ThreadList::DumpNativeStacks(std::ostream& os) {
  MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
  for (const auto& thread : list_) {
    os << "DUMPING THREAD " << thread->GetTid() << "\n";
    DumpNativeStack(os, thread->GetTid(), "\t");
    os << "\n";
  }
}

void ThreadList::DumpForSigQuit(std::ostream& os) {
  {
    MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
    DumpLocked(os);
  }
  DumpUnattachedThreads(os);
}

static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
  // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
  // refactor DumpState to avoid skipping analysis.
  Thread::DumpState(os, NULL, tid);
  DumpKernelStack(os, tid, "  kernel: ", false);
  // TODO: Reenable this when the native code in system_server can handle it.
  // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
  if (false) {
    DumpNativeStack(os, tid, "  native: ");
  }
  os << "\n";
}

void ThreadList::DumpUnattachedThreads(std::ostream& os) {
  DIR* d = opendir("/proc/self/task");
  if (!d) {
    return;
  }

  Thread* self = Thread::Current();
  dirent* e;
  while ((e = readdir(d)) != NULL) {
    char* end;
    pid_t tid = strtol(e->d_name, &end, 10);
    if (!*end) {
      bool contains;
      {
        MutexLock mu(self, *Locks::thread_list_lock_);
        contains = Contains(tid);
      }
      if (!contains) {
        DumpUnattachedThread(os, tid);
      }
    }
  }
  closedir(d);
}

void ThreadList::DumpLocked(std::ostream& os) {
  os << "DALVIK THREADS (" << list_.size() << "):\n";
  for (const auto& thread : list_) {
    thread->Dump(os);
    os << "\n";
  }
}

void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
  MutexLock mu(self, *Locks::thread_list_lock_);
  MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
  for (const auto& thread : list_) {
    if (thread != ignore1 && thread != ignore2) {
      CHECK(thread->IsSuspended())
            << "\nUnsuspended thread: <<" << *thread << "\n"
            << "self: <<" << *Thread::Current();
    }
  }
}

#if HAVE_TIMED_RWLOCK
// Attempt to rectify locks so that we dump thread list with required locks before exiting.
static void UnsafeLogFatalForThreadSuspendAllTimeout() NO_THREAD_SAFETY_ANALYSIS __attribute__((noreturn));
static void UnsafeLogFatalForThreadSuspendAllTimeout() {
  Runtime* runtime = Runtime::Current();
  std::ostringstream ss;
  ss << "Thread suspend timeout\n";
  Locks::mutator_lock_->Dump(ss);
  ss << "\n";
  runtime->GetThreadList()->DumpLocked(ss);
  LOG(FATAL) << ss.str();
  exit(0);
}
#endif

// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
// individual thread requires polling. delay_us is the requested sleep and total_delay_us
// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
  useconds_t new_delay_us = (*delay_us) * 2;
  CHECK_GE(new_delay_us, *delay_us);
  if (new_delay_us < 500000) {  // Don't allow sleeping to be more than 0.5s.
    *delay_us = new_delay_us;
  }
  if (*delay_us == 0) {
    sched_yield();
    // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
    *delay_us = 500;
  } else {
    usleep(*delay_us);
    *total_delay_us += *delay_us;
  }
}

size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
  Thread* self = Thread::Current();
  Locks::mutator_lock_->AssertNotExclusiveHeld(self);
  Locks::thread_list_lock_->AssertNotHeld(self);
  Locks::thread_suspend_count_lock_->AssertNotHeld(self);
  if (kDebugLocking) {
    CHECK_NE(self->GetState(), kRunnable);
  }

  std::vector<Thread*> suspended_count_modified_threads;
  size_t count = 0;
  {
    // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
    // manually called.
    MutexLock mu(self, *Locks::thread_list_lock_);
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    for (const auto& thread : list_) {
      if (thread != self) {
        while (true) {
          if (thread->RequestCheckpoint(checkpoint_function)) {
            // This thread will run its checkpoint some time in the near future.
            count++;
            break;
          } else {
            // We are probably suspended, try to make sure that we stay suspended.
            // The thread switched back to runnable.
            if (thread->GetState() == kRunnable) {
              // Spurious fail, try again.
              continue;
            }
            thread->ModifySuspendCount(self, +1, false);
            suspended_count_modified_threads.push_back(thread);
            break;
          }
        }
      }
    }
  }

  // Run the checkpoint on ourself while we wait for threads to suspend.
  checkpoint_function->Run(self);

  // Run the checkpoint on the suspended threads.
  for (const auto& thread : suspended_count_modified_threads) {
    if (!thread->IsSuspended()) {
      // Wait until the thread is suspended.
      useconds_t total_delay_us = 0;
      do {
        useconds_t delay_us = 100;
        ThreadSuspendSleep(self, &delay_us, &total_delay_us);
      } while (!thread->IsSuspended());
      // Shouldn't need to wait for longer than 1000 microseconds.
      constexpr useconds_t kLongWaitThresholdUS = 1000;
      if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
        LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
      }
    }
    // We know for sure that the thread is suspended at this point.
    checkpoint_function->Run(thread);
    {
      MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
      thread->ModifySuspendCount(self, -1, false);
    }
  }

  {
    // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
    // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    Thread::resume_cond_->Broadcast(self);
  }

  // Add one for self.
  return count + suspended_count_modified_threads.size() + 1;
}

// Request that a checkpoint function be run on all active (non-suspended)
// threads.  Returns the number of successful requests.
size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
  Thread* self = Thread::Current();
  if (kIsDebugBuild) {
    Locks::mutator_lock_->AssertNotExclusiveHeld(self);
    Locks::thread_list_lock_->AssertNotHeld(self);
    Locks::thread_suspend_count_lock_->AssertNotHeld(self);
    CHECK_NE(self->GetState(), kRunnable);
  }

  size_t count = 0;
  {
    // Call a checkpoint function for each non-suspended thread.
    MutexLock mu(self, *Locks::thread_list_lock_);
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    for (const auto& thread : list_) {
      if (thread != self) {
        if (thread->RequestCheckpoint(checkpoint_function)) {
          // This thread will run its checkpoint some time in the near future.
          count++;
        }
      }
    }
  }

  // Return the number of threads that will run the checkpoint function.
  return count;
}

void ThreadList::SuspendAll() {
  Thread* self = Thread::Current();

  if (self != nullptr) {
    VLOG(threads) << *self << " SuspendAll starting...";
  } else {
    VLOG(threads) << "Thread[null] SuspendAll starting...";
  }
  ATRACE_BEGIN("Suspending mutator threads");
  uint64_t start_time = NanoTime();

  Locks::mutator_lock_->AssertNotHeld(self);
  Locks::thread_list_lock_->AssertNotHeld(self);
  Locks::thread_suspend_count_lock_->AssertNotHeld(self);
  if (kDebugLocking && self != nullptr) {
    CHECK_NE(self->GetState(), kRunnable);
  }
  {
    MutexLock mu(self, *Locks::thread_list_lock_);
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    // Update global suspend all state for attaching threads.
    ++suspend_all_count_;
    // Increment everybody's suspend count (except our own).
    for (const auto& thread : list_) {
      if (thread == self) {
        continue;
      }
      VLOG(threads) << "requesting thread suspend: " << *thread;
      thread->ModifySuspendCount(self, +1, false);
    }
  }

  // Block on the mutator lock until all Runnable threads release their share of access.
#if HAVE_TIMED_RWLOCK
  // Timeout if we wait more than 30 seconds.
  if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
    UnsafeLogFatalForThreadSuspendAllTimeout();
  }
#else
  Locks::mutator_lock_->ExclusiveLock(self);
#endif

  uint64_t end_time = NanoTime();
  if (end_time - start_time > kLongThreadSuspendThreshold) {
    LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
  }

  if (kDebugLocking) {
    // Debug check that all threads are suspended.
    AssertThreadsAreSuspended(self, self);
  }

  ATRACE_END();
  ATRACE_BEGIN("Mutator threads suspended");

  if (self != nullptr) {
    VLOG(threads) << *self << " SuspendAll complete";
  } else {
    VLOG(threads) << "Thread[null] SuspendAll complete";
  }
}

void ThreadList::ResumeAll() {
  Thread* self = Thread::Current();

  if (self != nullptr) {
    VLOG(threads) << *self << " ResumeAll starting";
  } else {
    VLOG(threads) << "Thread[null] ResumeAll starting";
  }

  ATRACE_END();
  ATRACE_BEGIN("Resuming mutator threads");

  if (kDebugLocking) {
    // Debug check that all threads are suspended.
    AssertThreadsAreSuspended(self, self);
  }

  Locks::mutator_lock_->ExclusiveUnlock(self);
  {
    MutexLock mu(self, *Locks::thread_list_lock_);
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    // Update global suspend all state for attaching threads.
    --suspend_all_count_;
    // Decrement the suspend counts for all threads.
    for (const auto& thread : list_) {
      if (thread == self) {
        continue;
      }
      thread->ModifySuspendCount(self, -1, false);
    }

    // Broadcast a notification to all suspended threads, some or all of
    // which may choose to wake up.  No need to wait for them.
    if (self != nullptr) {
      VLOG(threads) << *self << " ResumeAll waking others";
    } else {
      VLOG(threads) << "Thread[null] ResumeAll waking others";
    }
    Thread::resume_cond_->Broadcast(self);
  }
  ATRACE_END();

  if (self != nullptr) {
    VLOG(threads) << *self << " ResumeAll complete";
  } else {
    VLOG(threads) << "Thread[null] ResumeAll complete";
  }
}

void ThreadList::Resume(Thread* thread, bool for_debugger) {
  Thread* self = Thread::Current();
  DCHECK_NE(thread, self);
  VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
      << (for_debugger ? " (debugger)" : "");

  {
    // To check Contains.
    MutexLock mu(self, *Locks::thread_list_lock_);
    // To check IsSuspended.
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    DCHECK(thread->IsSuspended());
    if (!Contains(thread)) {
      // We only expect threads within the thread-list to have been suspended otherwise we can't
      // stop such threads from delete-ing themselves.
      LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
          << ") thread not within thread list";
      return;
    }
    thread->ModifySuspendCount(self, -1, for_debugger);
  }

  {
    VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
    Thread::resume_cond_->Broadcast(self);
  }

  VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
}

static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
  JNIEnvExt* env = self->GetJniEnv();
  ScopedLocalRef<jstring>
      scoped_name_string(env, (jstring)env->GetObjectField(peer,
                                                          WellKnownClasses::java_lang_Thread_name));
  ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
  if (scoped_name_chars.c_str() == NULL) {
      LOG(level) << message << ": " << peer;
      env->ExceptionClear();
  } else {
      LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
  }
}

Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
                                        bool debug_suspension, bool* timed_out) {
  static const useconds_t kTimeoutUs = 30 * 1000000;  // 30s.
  useconds_t total_delay_us = 0;
  useconds_t delay_us = 0;
  bool did_suspend_request = false;
  *timed_out = false;
  Thread* self = Thread::Current();
  VLOG(threads) << "SuspendThreadByPeer starting";
  while (true) {
    Thread* thread;
    {
      // Note: this will transition to runnable and potentially suspend. We ensure only one thread
      // is requesting another suspend, to avoid deadlock, by requiring this function be called
      // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
      // than request thread suspension, to avoid potential cycles in threads requesting each other
      // suspend.
      ScopedObjectAccess soa(self);
      MutexLock mu(self, *Locks::thread_list_lock_);
      thread = Thread::FromManagedThread(soa, peer);
      if (thread == nullptr) {
        ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
        return nullptr;
      }
      if (!Contains(thread)) {
        VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
            << reinterpret_cast<void*>(thread);
        return nullptr;
      }
      VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
      {
        MutexLock mu(self, *Locks::thread_suspend_count_lock_);
        if (request_suspension) {
          thread->ModifySuspendCount(self, +1, debug_suspension);
          request_suspension = false;
          did_suspend_request = true;
        } else {
          // If the caller isn't requesting suspension, a suspension should have already occurred.
          CHECK_GT(thread->GetSuspendCount(), 0);
        }
        // IsSuspended on the current thread will fail as the current thread is changed into
        // Runnable above. As the suspend count is now raised if this is the current thread
        // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
        // to just explicitly handle the current thread in the callers to this code.
        CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
        // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
        // count, or else we've waited and it has self suspended) or is the current thread, we're
        // done.
        if (thread->IsSuspended()) {
          VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
          return thread;
        }
        if (total_delay_us >= kTimeoutUs) {
          ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
          if (did_suspend_request) {
            thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
          }
          *timed_out = true;
          return nullptr;
        }
      }
      // Release locks and come out of runnable state.
    }
    VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
    ThreadSuspendSleep(self, &delay_us, &total_delay_us);
  }
}

static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
  LOG(level) << StringPrintf("%s: %d", message, thread_id);
}

Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
                                            bool* timed_out) {
  static const useconds_t kTimeoutUs = 30 * 1000000;  // 30s.
  useconds_t total_delay_us = 0;
  useconds_t delay_us = 0;
  *timed_out = false;
  Thread* suspended_thread = nullptr;
  Thread* self = Thread::Current();
  CHECK_NE(thread_id, kInvalidThreadId);
  VLOG(threads) << "SuspendThreadByThreadId starting";
  while (true) {
    {
      // Note: this will transition to runnable and potentially suspend. We ensure only one thread
      // is requesting another suspend, to avoid deadlock, by requiring this function be called
      // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
      // than request thread suspension, to avoid potential cycles in threads requesting each other
      // suspend.
      ScopedObjectAccess soa(self);
      MutexLock mu(self, *Locks::thread_list_lock_);
      Thread* thread = nullptr;
      for (const auto& it : list_) {
        if (it->GetThreadId() == thread_id) {
          thread = it;
          break;
        }
      }
      if (thread == nullptr) {
        CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
            << " no longer in thread list";
        // There's a race in inflating a lock and the owner giving up ownership and then dying.
        ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
        return nullptr;
      }
      VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
      DCHECK(Contains(thread));
      {
        MutexLock mu(self, *Locks::thread_suspend_count_lock_);
        if (suspended_thread == nullptr) {
          thread->ModifySuspendCount(self, +1, debug_suspension);
          suspended_thread = thread;
        } else {
          CHECK_EQ(suspended_thread, thread);
          // If the caller isn't requesting suspension, a suspension should have already occurred.
          CHECK_GT(thread->GetSuspendCount(), 0);
        }
        // IsSuspended on the current thread will fail as the current thread is changed into
        // Runnable above. As the suspend count is now raised if this is the current thread
        // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
        // to just explicitly handle the current thread in the callers to this code.
        CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
        // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
        // count, or else we've waited and it has self suspended) or is the current thread, we're
        // done.
        if (thread->IsSuspended()) {
          VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
          return thread;
        }
        if (total_delay_us >= kTimeoutUs) {
          ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
          if (suspended_thread != nullptr) {
            thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
          }
          *timed_out = true;
          return nullptr;
        }
      }
      // Release locks and come out of runnable state.
    }
    VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
    ThreadSuspendSleep(self, &delay_us, &total_delay_us);
  }
}

Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
  Thread* self = Thread::Current();
  MutexLock mu(self, *Locks::thread_list_lock_);
  for (const auto& thread : list_) {
    if (thread->GetThreadId() == thin_lock_id) {
      CHECK(thread == self || thread->IsSuspended());
      return thread;
    }
  }
  return NULL;
}

void ThreadList::SuspendAllForDebugger() {
  Thread* self = Thread::Current();
  Thread* debug_thread = Dbg::GetDebugThread();

  VLOG(threads) << *self << " SuspendAllForDebugger starting...";

  {
    MutexLock mu(self, *Locks::thread_list_lock_);
    {
      MutexLock mu(self, *Locks::thread_suspend_count_lock_);
      // Update global suspend all state for attaching threads.
      DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
      ++suspend_all_count_;
      ++debug_suspend_all_count_;
      // Increment everybody's suspend count (except our own).
      for (const auto& thread : list_) {
        if (thread == self || thread == debug_thread) {
          continue;
        }
        VLOG(threads) << "requesting thread suspend: " << *thread;
        thread->ModifySuspendCount(self, +1, true);
      }
    }
  }

  // Block on the mutator lock until all Runnable threads release their share of access then
  // immediately unlock again.
#if HAVE_TIMED_RWLOCK
  // Timeout if we wait more than 30 seconds.
  if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
    UnsafeLogFatalForThreadSuspendAllTimeout();
  } else {
    Locks::mutator_lock_->ExclusiveUnlock(self);
  }
#else
  Locks::mutator_lock_->ExclusiveLock(self);
  Locks::mutator_lock_->ExclusiveUnlock(self);
#endif
  AssertThreadsAreSuspended(self, self, debug_thread);

  VLOG(threads) << *self << " SuspendAllForDebugger complete";
}

void ThreadList::SuspendSelfForDebugger() {
  Thread* self = Thread::Current();

  // The debugger thread must not suspend itself due to debugger activity!
  Thread* debug_thread = Dbg::GetDebugThread();
  CHECK(debug_thread != NULL);
  CHECK(self != debug_thread);
  CHECK_NE(self->GetState(), kRunnable);
  Locks::mutator_lock_->AssertNotHeld(self);

  {
    // Collisions with other suspends aren't really interesting. We want
    // to ensure that we're the only one fiddling with the suspend count
    // though.
    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
    self->ModifySuspendCount(self, +1, true);
    CHECK_GT(self->GetSuspendCount(), 0);
  }

  VLOG(threads) << *self << " self-suspending (debugger)";

  // Tell JDWP we've completed invocation and are ready to suspend.
  DebugInvokeReq* pReq = self->GetInvokeReq();
  DCHECK(pReq != NULL);
  if (pReq->invoke_needed) {
    // Clear this before signaling.
    pReq->Clear();

    VLOG(jdwp) << "invoke complete, signaling";
    MutexLock mu(self, pReq->lock);
    pReq->cond.Signal(self);
  }

  // Tell JDWP that we've completed suspension. The JDWP thread can't
  // tell us to resume before we're fully asleep because we hold the
  // suspend count lock.
  Dbg::ClearWaitForEventThread();

  {
    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
    while (self->GetSuspendCount() != 0) {
      Thread::resume_cond_->Wait(self);
      if (self->GetSuspendCount() != 0) {
        // The condition was signaled but we're still suspended. This
        // can happen when we suspend then resume all threads to
        // update instrumentation or compute monitor info. This can
        // also happen if the debugger lets go while a SIGQUIT thread
        // dump event is pending (assuming SignalCatcher was resumed for
        // just long enough to try to grab the thread-suspend lock).
        VLOG(jdwp) << *self << " still suspended after undo "
                   << "(suspend count=" << self->GetSuspendCount() << ", "
                   << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
      }
    }
    CHECK_EQ(self->GetSuspendCount(), 0);
  }

  VLOG(threads) << *self << " self-reviving (debugger)";
}

void ThreadList::ResumeAllForDebugger() {
  Thread* self = Thread::Current();
  Thread* debug_thread = Dbg::GetDebugThread();

  VLOG(threads) << *self << " ResumeAllForDebugger starting...";

  // Threads can't resume if we exclusively hold the mutator lock.
  Locks::mutator_lock_->AssertNotExclusiveHeld(self);

  {
    MutexLock mu(self, *Locks::thread_list_lock_);
    {
      MutexLock mu(self, *Locks::thread_suspend_count_lock_);
      // Update global suspend all state for attaching threads.
      DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
      if (debug_suspend_all_count_ > 0) {
        --suspend_all_count_;
        --debug_suspend_all_count_;
      } else {
        // We've been asked to resume all threads without being asked to
        // suspend them all before. That may happen if a debugger tries
        // to resume some suspended threads (with suspend count == 1)
        // at once with a VirtualMachine.Resume command. Let's print a
        // warning.
        LOG(WARNING) << "Debugger attempted to resume all threads without "
                     << "having suspended them all before.";
      }
      // Decrement everybody's suspend count (except our own).
      for (const auto& thread : list_) {
        if (thread == self || thread == debug_thread) {
          continue;
        }
        if (thread->GetDebugSuspendCount() == 0) {
          // This thread may have been individually resumed with ThreadReference.Resume.
          continue;
        }
        VLOG(threads) << "requesting thread resume: " << *thread;
        thread->ModifySuspendCount(self, -1, true);
      }
    }
  }

  {
    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
    Thread::resume_cond_->Broadcast(self);
  }

  VLOG(threads) << *self << " ResumeAllForDebugger complete";
}

void ThreadList::UndoDebuggerSuspensions() {
  Thread* self = Thread::Current();

  VLOG(threads) << *self << " UndoDebuggerSuspensions starting";

  {
    MutexLock mu(self, *Locks::thread_list_lock_);
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    // Update global suspend all state for attaching threads.
    suspend_all_count_ -= debug_suspend_all_count_;
    debug_suspend_all_count_ = 0;
    // Update running threads.
    for (const auto& thread : list_) {
      if (thread == self || thread->GetDebugSuspendCount() == 0) {
        continue;
      }
      thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
    }
  }

  {
    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
    Thread::resume_cond_->Broadcast(self);
  }

  VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
}

void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
  Thread* self = Thread::Current();
  Locks::mutator_lock_->AssertNotHeld(self);
  bool all_threads_are_daemons;
  do {
    {
      // No more threads can be born after we start to shutdown.
      MutexLock mu(self, *Locks::runtime_shutdown_lock_);
      CHECK(Runtime::Current()->IsShuttingDownLocked());
      CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
    }
    all_threads_are_daemons = true;
    MutexLock mu(self, *Locks::thread_list_lock_);
    for (const auto& thread : list_) {
      if (thread != self && !thread->IsDaemon()) {
        all_threads_are_daemons = false;
        break;
      }
    }
    if (!all_threads_are_daemons) {
      // Wait for another thread to exit before re-checking.
      thread_exit_cond_.Wait(self);
    }
  } while (!all_threads_are_daemons);
}

void ThreadList::SuspendAllDaemonThreads() {
  Thread* self = Thread::Current();
  MutexLock mu(self, *Locks::thread_list_lock_);
  {  // Tell all the daemons it's time to suspend.
    MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
    for (const auto& thread : list_) {
      // This is only run after all non-daemon threads have exited, so the remainder should all be
      // daemons.
      CHECK(thread->IsDaemon()) << *thread;
      if (thread != self) {
        thread->ModifySuspendCount(self, +1, false);
      }
    }
  }
  // Give the threads a chance to suspend, complaining if they're slow.
  bool have_complained = false;
  for (int i = 0; i < 10; ++i) {
    usleep(200 * 1000);
    bool all_suspended = true;
    for (const auto& thread : list_) {
      if (thread != self && thread->GetState() == kRunnable) {
        if (!have_complained) {
          LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
          have_complained = true;
        }
        all_suspended = false;
      }
    }
    if (all_suspended) {
      return;
    }
  }
  LOG(ERROR) << "suspend all daemons failed";
}
void ThreadList::Register(Thread* self) {
  DCHECK_EQ(self, Thread::Current());

  if (VLOG_IS_ON(threads)) {
    std::ostringstream oss;
    self->ShortDump(oss);  // We don't hold the mutator_lock_ yet and so cannot call Dump.
    LOG(INFO) << "ThreadList::Register() " << *self  << "\n" << oss.str();
  }

  // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
  // SuspendAll requests.
  MutexLock mu(self, *Locks::thread_list_lock_);
  MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
  CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
  // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
  // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
  for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
    self->ModifySuspendCount(self, +1, true);
  }
  for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
    self->ModifySuspendCount(self, +1, false);
  }
  CHECK(!Contains(self));
  list_.push_back(self);
}

void ThreadList::Unregister(Thread* self) {
  DCHECK_EQ(self, Thread::Current());

  VLOG(threads) << "ThreadList::Unregister() " << *self;

  // Any time-consuming destruction, plus anything that can call back into managed code or
  // suspend and so on, must happen at this point, and not in ~Thread.
  self->Destroy();

  // If tracing, remember thread id and name before thread exits.
  Trace::StoreExitingThreadInfo(self);

  uint32_t thin_lock_id = self->GetThreadId();
  while (self != nullptr) {
    // Remove and delete the Thread* while holding the thread_list_lock_ and
    // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
    // Note: deliberately not using MutexLock that could hold a stale self pointer.
    Locks::thread_list_lock_->ExclusiveLock(self);
    if (!Contains(self)) {
      std::ostringstream os;
      DumpNativeStack(os, GetTid(), "  native: ", nullptr);
      LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
      self = nullptr;
    } else {
      // Note: we don't take the thread_suspend_count_lock_ here as to be suspending a thread other
      // than yourself you need to hold the thread_list_lock_ (see Thread::ModifySuspendCount).
      if (!self->IsSuspended()) {
        list_.remove(self);
        delete self;
        self = nullptr;
      }
    }
    Locks::thread_list_lock_->ExclusiveUnlock(self);
  }
  // Release the thread ID after the thread is finished and deleted to avoid cases where we can
  // temporarily have multiple threads with the same thread id. When this occurs, it causes
  // problems in FindThreadByThreadId / SuspendThreadByThreadId.
  ReleaseThreadId(nullptr, thin_lock_id);

  // Clear the TLS data, so that the underlying native thread is recognizably detached.
  // (It may wish to reattach later.)
  CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");

  // Signal that a thread just detached.
  MutexLock mu(NULL, *Locks::thread_list_lock_);
  thread_exit_cond_.Signal(NULL);
}

void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
  for (const auto& thread : list_) {
    callback(thread, context);
  }
}

void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
  MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
  for (const auto& thread : list_) {
    thread->VisitRoots(callback, arg);
  }
}

uint32_t ThreadList::AllocThreadId(Thread* self) {
  MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
  for (size_t i = 0; i < allocated_ids_.size(); ++i) {
    if (!allocated_ids_[i]) {
      allocated_ids_.set(i);
      return i + 1;  // Zero is reserved to mean "invalid".
    }
  }
  LOG(FATAL) << "Out of internal thread ids";
  return 0;
}

void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
  MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
  --id;  // Zero is reserved to mean "invalid".
  DCHECK(allocated_ids_[id]) << id;
  allocated_ids_.reset(id);
}

}  // namespace art


text:
#region About and License
//=======================================================================
// Copyright Andrew Szot 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE.txt)
//=======================================================================
#endregion

using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Xna.Framework;

namespace BaseLogic.Player.AI.Graph
{
    /// <summary>
    ///
    /// </summary>
    [Serializable]
    public class SparseGraph
    {
        /// <summary>
        /// The _edges
        /// </summary>
        private List<GraphEdge> _edges = new List<GraphEdge>();

        /// <summary>
        /// The _nodes
        /// </summary>
        private List<GraphNode> _nodes = new List<GraphNode>();

        /// <summary>
        /// The b_digraph
        /// </summary>
        private bool b_digraph;

        /// <summary>
        /// The b_serilize
        /// </summary>
        private bool b_serilize = true;

        /// <summary>
        /// The i_next node index
        /// </summary>
        private int i_nextNodeIndex;

        /// <summary>
        /// Initializes a new instance of the <see cref="SparseGraph"/> class.
        /// </summary>
        /// <param name="digraph">if set to <c>true</c> [digraph].</param>
        public SparseGraph(bool digraph)
        {
            i_nextNodeIndex = 0;
            b_digraph = digraph;
        }

        /// <summary>
        /// Gets a value indicating whether this <see cref="SparseGraph"/> is digraph.
        /// </summary>
        /// <value>
        ///   <c>true</c> if digraph; otherwise, <c>false</c>.
        /// </value>
        public bool Digraph
        {
            get { return b_digraph; }
        }

        /// <summary>
        /// Gets the edges.
        /// </summary>
        /// <value>
        /// The edges.
        /// </value>
        public List<GraphEdge> Edges
        {
            get { return _edges; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is empty.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is empty; otherwise, <c>false</c>.
        /// </value>
        public bool IsEmpty
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the nodes.
        /// </summary>
        /// <value>
        /// The nodes.
        /// </value>
        public List<GraphNode> Nodes
        {
            get { return _nodes; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="SparseGraph"/> is serilize.
        /// </summary>
        /// <value>
        ///   <c>true</c> if serilize; otherwise, <c>false</c>.
        /// </value>
        public bool Serilize
        {
            get { return b_serilize; }
            set { b_serilize = value; }
        }

        /// <summary>
        /// Generates the grid graph.
        /// </summary>
        /// <param name="m">The m.</param>
        /// <param name="n">The n.</param>
        /// <param name="spacing">The spacing.</param>
        /// <param name="centerOffset">The center offset.</param>
        /// <returns></returns>
        public static SparseGraph GenerateGridGraph(int m, int n, float spacing, Vector3 centerOffset)
        {
            GraphNode[,] nodes = GenerateGraphNodes(n, m, spacing, centerOffset);
            // Copy over to the sparse graph.
            SparseGraph sparseGraph = new SparseGraph(false);
            for (int i = 0; i < m; ++i)
            {
                for (int j = 0; j < n; ++j)
                    sparseGraph.Nodes.Add(nodes[i, j]);
            }

            List<GraphEdge> edges = GenerateGraphEdges(nodes, m, n);

            sparseGraph.Edges.AddRange(edges);

            return sparseGraph;
        }

        /// <summary>
        /// Adds the edge.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns></returns>
        public bool AddEdge(int from, int to)
        {
            return AddEdge(from, to, 1.0f);
        }

        /// <summary>
        /// Adds the edge.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <param name="cost">The cost.</param>
        /// <returns></returns>
        public bool AddEdge(int from, int to, float cost)
        {
            return AddEdge(new GraphEdge(from, to, cost));
        }

        /// <summary>
        /// Adds the edge.
        /// </summary>
        /// <param name="edge">The edge.</param>
        /// <returns></returns>
        public bool AddEdge(GraphEdge edge)
        {
            bool copyExists = false;
            foreach (GraphEdge cEdge in _edges)
            {
                if (cEdge == edge)
                    copyExists = true;
            }
            if (!copyExists)
                _edges.Add(edge);

            return copyExists;
        }

        /// <summary>
        /// Adds the edges for rendering.
        /// </summary>
        /// <param name="primitivesRenderer">The primitives renderer.</param>
        /// <param name="renderColor">Color of the render.</param>
        /// <param name="selectedRenderColor">Color of the selected render.</param>
        /// <param name="selectedIndicies">The selected indicies.</param>
        public void AddEdgesForRendering(BaseLogic.Graphics.PrimitivesRenderer primitivesRenderer,
            Microsoft.Xna.Framework.Color renderColor, Microsoft.Xna.Framework.Color selectedRenderColor, List<int> selectedIndicies)
        {
            for (int i = 0; i < _edges.Count; ++i)
            {
                GraphEdge edge = _edges[i];

                GraphNode node1 = GetNode(edge.To);
                GraphNode node2 = GetNode(edge.From);

                if (selectedIndicies.Contains(i))
                    primitivesRenderer.AddRenderLine(node1.Position, node2.Position, selectedRenderColor);
                else
                    primitivesRenderer.AddRenderLine(node1.Position, node2.Position, renderColor);
            }
        }

        /// <summary>
        /// Adds the node.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="z">The z.</param>
        /// <returns></returns>
        public int AddNode(float x, float y, float z)
        {
            return AddNode(new Microsoft.Xna.Framework.Vector3(x, y, z));
        }

        /// <summary>
        /// Adds the node.
        /// </summary>
        /// <param name="pos">The position.</param>
        /// <returns></returns>
        public int AddNode(Microsoft.Xna.Framework.Vector3 pos)
        {
            GraphNode graphNode = new GraphNode(i_nextNodeIndex++);
            graphNode.Position = pos;
            _nodes.Add(graphNode);

            return i_nextNodeIndex;
        }

        /// <summary>
        /// Adds the node.
        /// </summary>
        /// <returns></returns>
        public int AddNode()
        {
            GraphNode graphNode = new GraphNode(i_nextNodeIndex++);
            _nodes.Add(graphNode);

            return i_nextNodeIndex;
        }

        /// <summary>
        /// Clears this instance.
        /// </summary>
        public void Clear()
        {
            _edges.Clear();
            _nodes.Clear();
            i_nextNodeIndex = 0;
        }

        /// <summary>
        /// Generates the distance based costs.
        /// </summary>
        public void GenerateDistanceBasedCosts()
        {
            foreach (GraphEdge edge in _edges)
            {
                GraphNode from = GetNode(edge.From);
                GraphNode to = GetNode(edge.To);

                float distance = Vector3.Distance(from.Position, to.Position);
                edge.Cost = distance;
            }
        }

        /// <summary>
        /// Gets the edge.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns></returns>
        public GraphEdge GetEdge(int from, int to)
        {
            foreach (GraphEdge edge in _edges)
            {
                if (edge.From == from && edge.To == to)
                    return edge;
            }
            return null;
        }

        /// <summary>
        /// Gets the graph save data.
        /// </summary>
        /// <returns></returns>
        public GraphSaveData GetGraphSaveData()
        {
            GraphSaveData graphSaveData;
            var nodeSaveDatas = from n in _nodes
                                select n.GetNodeSaveData();
            var edgeSaveDatas = from e in _edges
                                select e.GetEdgeSaveData();
            graphSaveData.NodeSaveData = nodeSaveDatas.ToArray();
            graphSaveData.EdgeSaveData = edgeSaveDatas.ToArray();
            graphSaveData.NextNodeIndex = i_nextNodeIndex;
            graphSaveData.Digraph = b_digraph;

            return graphSaveData;
        }

        /// <summary>
        /// Gets the next free node.
        /// </summary>
        /// <returns></returns>
        public int GetNextFreeNode()
        {
            return i_nextNodeIndex;
        }

        /// <summary>
        /// Gets the node.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        public GraphNode GetNode(int index)
        {
            foreach (GraphNode node in _nodes)
            {
                if (node.Index == index)
                    return node;
            }
            return null;
        }

        /// <summary>
        /// Gets the node closest to position.
        /// </summary>
        /// <param name="pos">The position.</param>
        /// <returns></returns>
        public GraphNode GetNodeClosestToPosition(Vector3 pos)
        {
            float closestDistSq = float.MaxValue;
            GraphNode closestNode = null;

            foreach (GraphNode node in _nodes)
            {
                float distanceSq = Vector3.DistanceSquared(pos, node.Position);
                if (distanceSq < closestDistSq)
                {
                    closestNode = node;
                    closestDistSq = distanceSq;
                }
            }

            return closestNode;
        }

        /// <summary>
        /// Gets the node edges.
        /// </summary>
        /// <param name="nodeIndex">Index of the node.</param>
        /// <returns></returns>
        public IEnumerable<GraphEdge> GetNodeEdges(int nodeIndex)
        {
            List<GraphEdge> graphEdges = new List<GraphEdge>();
            foreach (GraphEdge edge in _edges)
            {
                if (edge.From == nodeIndex)
                    graphEdges.Add(edge);
            }

            return graphEdges;
        }

        /// <summary>
        /// Gets the number active nodes.
        /// </summary>
        /// <returns></returns>
        public int GetNumActiveNodes()
        {
            // So far there is no difference between an inactive and active node.
            return GetNumNodes();
        }

        /// <summary>
        /// Gets the number edges.
        /// </summary>
        /// <returns></returns>
        public int GetNumEdges()
        {
            return _edges.Count;
        }

        /// <summary>
        /// Gets the number nodes.
        /// </summary>
        /// <returns></returns>
        public int GetNumNodes()
        {
            return _nodes.Count;
        }

        /// <summary>
        /// Removes the associated sides.
        /// </summary>
        /// <param name="nodeIndex">Index of the node.</param>
        public void RemoveAssociatedSides(int nodeIndex)
        {
            for (int i = 0; i < _edges.Count; ++i)
            {
                GraphEdge edge = _edges.ElementAt(i);
                if (edge.To == nodeIndex || edge.From == nodeIndex)
                    _edges.RemoveAt(i++);
            }
        }

        /// <summary>
        /// Removes the edge.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns></returns>
        public bool RemoveEdge(int from, int to)
        {
            for (int i = 0; i < _edges.Count; ++i)
            {
                GraphEdge edge = _edges[i];
                if (edge.From == from && edge.To == to)
                {
                    _edges.RemoveAt(i);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Removes nodes which don't have any edges associated with them.
        /// </summary>
        public void RemoveLoneNodes()
        {
            for (int i = 0; i < _nodes.Count; ++i)
            {
                GraphNode node = _nodes[i];
                bool found = false;
                for (int j = 0; j < _edges.Count; ++j)
                {
                    GraphEdge edge = _edges[j];
                    if (edge.From == node.Index || edge.To == node.Index)
                        found = true;
                }
                if (!found)
                    _nodes.RemoveAt(i++);
            }
        }

        /// <summary>
        /// Removes the node.
        /// </summary>
        /// <param name="nodeIndex">Index of the node.</param>
        /// <returns></returns>
        public bool RemoveNode(int nodeIndex)
        {
            for (int i = 0; i < _nodes.Count; ++i)
            {
                GraphNode cNode = _nodes.ElementAt(i);
                if (cNode.Index == nodeIndex)
                {
                    _nodes.RemoveAt(i);
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Removes the obstructing edges.
        /// </summary>
        /// <param name="physics">The physics.</param>
        public void RemoveObstructingEdges(BaseLogic.Manager.GamePhysicsMgr physics)
        {
            for (int i = 0; i < _edges.Count; ++i)
            {
                GraphEdge edge = _edges[i];
                GraphNode fromNode = GetNode(edge.From);
                GraphNode toNode = GetNode(edge.To);
                BaseLogic.Manager.RaytraceFireInfo rayFireInfo =
                    new BaseLogic.Manager.RaytraceFireInfo(fromNode.Position, toNode.Position);

                BaseLogic.Manager.RaytraceIntersectionInfo rii = physics.Raytrace(rayFireInfo);
                if (rii != null)
                {
                    // This edge is obstructing geometry we have to remove it.
                    _edges.RemoveAt(i++);
                }
            }
        }

        /// <summary>
        /// Sets the graph load data.
        /// </summary>
        /// <param name="graphSaveData">The graph save data.</param>
        public void SetGraphLoadData(GraphSaveData graphSaveData)
        {
            i_nextNodeIndex = graphSaveData.NextNodeIndex;
            b_digraph = graphSaveData.Digraph;

            foreach (NodeSaveData nsd in graphSaveData.NodeSaveData)
            {
                GraphNode graphNode = new GraphNode();
                graphNode.SetNodeLoadData(nsd);
                _nodes.Add(graphNode);
            }

            foreach (EdgeSaveData esd in graphSaveData.EdgeSaveData)
            {
                GraphEdge graphEdge = new GraphEdge();
                graphEdge.SetEdgeLoadData(esd);
                _edges.Add(graphEdge);
            }
        }

        /// <summary>
        /// Generates the graph edges.
        /// </summary>
        /// <param name="nodes">The nodes.</param>
        /// <param name="m">The m.</param>
        /// <param name="n">The n.</param>
        /// <returns></returns>
        private static List<GraphEdge> GenerateGraphEdges(GraphNode[,] nodes, int m, int n)
        {
            List<GraphEdge> edges = new List<GraphEdge>();

            for (int i = 0; i < m; ++i)
            {
                for (int j = 0; j < n; ++j)
                {
                    IEnumerable<GraphEdge> neighborEdges = GetNeighborEdgesOfNode(i, j, nodes, m, n);
                    edges.AddRange(neighborEdges);
                }
            }

            return edges;
        }

        /// <summary>
        /// Generates the graph nodes.
        /// </summary>
        /// <param name="m">The m.</param>
        /// <param name="n">The n.</param>
        /// <param name="spacing">The spacing.</param>
        /// <param name="centerOffset">The center offset.</param>
        /// <returns></returns>
        private static GraphNode[,] GenerateGraphNodes(int m, int n, float spacing, Vector3 centerOffset)
        {
            int centerSpotX = m / 2;
            int centerSpotZ = n / 2;

            Vector3 topLeftPos = new Vector3(0f, centerOffset.Y, 0f);
            topLeftPos.X = centerOffset.X - (spacing * (float)centerSpotX);
            topLeftPos.Z = centerOffset.Z - (spacing * (float)centerSpotZ);

            int nodeIndex = 0;

            GraphNode[,] nodes = new GraphNode[m, n];

            for (int i = 0; i < m; ++i)
            {
                for (int j = 0; j < n; ++j)
                {
                    Vector3 pos = new Vector3(spacing * (float)i, 0f, spacing * (float)j);
                    pos += topLeftPos;
                    nodes[i, j] = new GraphNode(nodeIndex++, pos);
                }
            }

            return nodes;
        }

        /// <summary>
        /// Gets the neighbor edges of node.
        /// </summary>
        /// <param name="i">The i.</param>
        /// <param name="j">The j.</param>
        /// <param name="nodes">The nodes.</param>
        /// <param name="m">The m.</param>
        /// <param name="n">The n.</param>
        /// <returns></returns>
        private static IEnumerable<GraphEdge> GetNeighborEdgesOfNode(int i, int j, GraphNode[,] nodes, int m, int n)
        {
            // In thhe depiction below the pluses are the neighbors this function will generate. The '@' is the current node.
            /*
             * + + +
             * + @ +
             * + + +
             */

            GraphNode fromNode = nodes[i, j];

            GraphEdge edge00 = ((i - 1) > 0 && (j - 1) > 0) ? new GraphEdge(fromNode.Index, nodes[i - 1, j - 1].Index) : null;
            GraphEdge edge01 = ((j - 1) > 0) ? new GraphEdge(fromNode.Index, nodes[i, j - 1].Index) : null;
            GraphEdge edge02 = ((i + 1) < m && (j - 1) > 0) ? new GraphEdge(fromNode.Index, nodes[i + 1, j - 1].Index) : null;

            GraphEdge edge10 = (i - 1 > 0) ? new GraphEdge(fromNode.Index, nodes[i - 1, j].Index) : null;
            // We are not going to include the current edge.
            GraphEdge edge13 = (i + 1 < m) ? new GraphEdge(fromNode.Index, nodes[i + 1, j].Index) : null;

            GraphEdge edge20 = (i - 1 > 0 && j + 1 < n) ? new GraphEdge(fromNode.Index, nodes[i - 1, j + 1].Index) : null;
            GraphEdge edge21 = (j + 1 < n) ? new GraphEdge(fromNode.Index, nodes[i, j + 1].Index) : null;
            GraphEdge edge22 = (i + 1 < m && j + 1 < n) ? new GraphEdge(fromNode.Index, nodes[i + 1, j + 1].Index) : null;

            // The order of the array is not relevant.
            GraphEdge[] neighborEdges = { edge00, edge01, edge02, edge10, edge13, edge20, edge21, edge22 };

            IEnumerable<GraphEdge> finalNeighborEdges = from e in neighborEdges
                                                        where e != null
                                                        select e;

            return finalNeighborEdges;
        }
    }
}


text:
package namesys

import (
	"strings"
	"time"

	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	ci "github.com/ipfs/go-ipfs/p2p/crypto"
	path "github.com/ipfs/go-ipfs/path"
	routing "github.com/ipfs/go-ipfs/routing"
)

// mpns (a multi-protocol NameSystem) implements generic IPFS naming.
//
// Uses several Resolvers:
// (a) ipfs routing naming: SFS-like PKI names.
// (b) dns domains: resolves using links in DNS TXT records
// (c) proquints: interprets string as the raw byte data.
//
// It can only publish to: (a) ipfs routing naming.
//
type mpns struct {
	resolvers  map[string]resolver
	publishers map[string]Publisher
}

// NewNameSystem will construct the IPFS naming system based on Routing
func NewNameSystem(r routing.IpfsRouting, ds ds.Datastore) NameSystem {
	return &mpns{
		resolvers: map[string]resolver{
			"dns":      newDNSResolver(),
			"proquint": new(ProquintResolver),
			"dht":      newRoutingResolver(r),
		},
		publishers: map[string]Publisher{
			"/ipns/": NewRoutingPublisher(r, ds),
		},
	}
}

// Resolve implements Resolver.
func (ns *mpns) Resolve(ctx context.Context, name string) (path.Path, error) {
	return ns.ResolveN(ctx, name, DefaultDepthLimit)
}

// ResolveN implements Resolver.
func (ns *mpns) ResolveN(ctx context.Context, name string, depth int) (path.Path, error) {
	if strings.HasPrefix(name, "/ipfs/") {
		return path.ParsePath(name)
	}

	if !strings.HasPrefix(name, "/") {
		return path.ParsePath("/ipfs/" + name)
	}

	return resolve(ctx, ns, name, depth, "/ipns/")
}

// resolveOnce implements resolver.
func (ns *mpns) resolveOnce(ctx context.Context, name string) (path.Path, error) {
	if !strings.HasPrefix(name, "/ipns/") {
		name = "/ipns/" + name
	}
	segments := strings.SplitN(name, "/", 3)
	if len(segments) < 3 || segments[0] != "" {
		log.Warningf("Invalid name syntax for %s", name)
		return "", ErrResolveFailed
	}

	for protocol, resolver := range ns.resolvers {
		log.Debugf("Attempting to resolve %s with %s", name, protocol)
		p, err := resolver.resolveOnce(ctx, segments[2])
		if err == nil {
			return p, err
		}
	}
	log.Warningf("No resolver found for %s", name)
	return "", ErrResolveFailed
}

// Publish implements Publisher
func (ns *mpns) Publish(ctx context.Context, name ci.PrivKey, value path.Path) error {
	return ns.publishers["/ipns/"].Publish(ctx, name, value)
}

func (ns *mpns) PublishWithEOL(ctx context.Context, name ci.PrivKey, val path.Path, eol time.Time) error {
	return ns.publishers["/ipns/"].PublishWithEOL(ctx, name, val, eol)
}


text:
package org.schema.api.model.thing.intangible;

import org.schema.api.model.thing.intangible.Intangible;

public class Class extends Intangible
{
}