text:
package org.olat.lms.search.document.file;

import java.io.BufferedInputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.olat.data.commons.vfs.VFSLeaf;
import org.olat.lms.search.SearchResourceContext;
import org.olat.system.logging.log4j.LoggerHelper;

/**
 * Lucene document mapper.
 *
 * @author Christian Guretzki
 */
public class ExcelDocument extends FileDocument {
    private static final Logger log = LoggerHelper.getLogger();

    public final static String FILE_TYPE = "type.file.excel";

    public ExcelDocument() {
        super();
    }

    public static Document createDocument(final SearchResourceContext leafResourceContext, final VFSLeaf leaf) throws IOException, DocumentException,
            DocumentAccessException {
        final ExcelDocument excelDocument = new ExcelDocument();
        excelDocument.init(leafResourceContext, leaf);
        excelDocument.setFileType(FILE_TYPE);
        excelDocument.setCssIcon("b_filetype_xls");
        if (log.isDebugEnabled()) {
            log.debug(excelDocument.toString());
        }
        return excelDocument.getLuceneDocument();
    }

    @Override
    protected String readContent(final VFSLeaf leaf) throws IOException, DocumentException {
        BufferedInputStream bis = null;
        int cellNullCounter = 0;
        int rowNullCounter = 0;
        int sheetNullCounter = 0;

        try {
            bis = new BufferedInputStream(leaf.getInputStream());
            final StringBuilder content = new StringBuilder(bis.available());
            final POIFSFileSystem fs = new POIFSFileSystem(bis);
            final HSSFWorkbook workbook = new HSSFWorkbook(fs);

            for (int sheetNumber = 0; sheetNumber < workbook.getNumberOfSheets(); sheetNumber++) {
                final HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
                if (sheet != null) {
                    for (int rowNumber = sheet.getFirstRowNum(); rowNumber <= sheet.getLastRowNum(); rowNumber++) {
                        final HSSFRow row = sheet.getRow(rowNumber);
                        if (row != null) {
                            for (int cellNumber = row.getFirstCellNum(); cellNumber <= row.getLastCellNum(); cellNumber++) {
                                final HSSFCell cell = row.getCell(cellNumber);
                                if (cell != null) {
                                    // if (cell.getCellStyle().equals(HSSFCell.CELL_TYPE_NUMERIC))
                                    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                                        content.append(cell.getStringCellValue()).append(' ');
                                    }
                                } else {
                                    // throw new DocumentException();
                                    cellNullCounter++;
                                }
                            }
                        } else {
                            rowNullCounter++;
                        }
                    }
                } else {
                    sheetNullCounter++;
                }
            }
            if (log.isDebugEnabled()) {
                if ((cellNullCounter > 0) || (rowNullCounter > 0) || (sheetNullCounter > 0)) {
                    log.debug("Read Excel content cell=null #:" + cellNullCounter + ", row=null #:" + rowNullCounter + ", sheet=null #:" + sheetNullCounter);
                }
            }
            return content.toString();
        } catch (final Exception ex) {
            throw new DocumentException("Can not read XLS Content. File=" + leaf.getName());
        } finally {
            if (bis != null) {
                bis.close();
            }

        }
    }

}


text:
/*
 * DataPacket.java
 *
 */

package bluetoothgateway;

import java.io.InvalidClassException;
import java.util.Date;
import java.util.Vector;

/**
 *
 * @author Clemens Lombriser <lombriser@ife.ee.ethz.ch>
 */
public class DataPacket {

   private Date   m_timestamp;
   private Date   m_original_timestamp;
   private Vector m_data;
   private String m_sensorname;
   private String[]m_channels;

   public DataPacket(Date timestamp, Vector data, String sensorname, String [] channels) {
      m_original_timestamp = m_timestamp = timestamp;
      m_data = data;
      m_sensorname = sensorname;
      m_channels = channels;
   }

   public String getSensorname() {
      return m_sensorname;
   }

   public String [] getChannels() {
      return m_channels;
   }

   public Vector getValues() {
      return m_data;
   }

   public long getTimestamp() {
      return m_timestamp.getTime();
   }

   public void setTimestamp(Date timestamp) {
      m_timestamp = timestamp;
   }

   /**
    * Returns the timestamp that was given initially to the DataPacket. This
    * timestamp may have changed
    * @return
    */
   public Date getOriginalTimestamp() {
      return m_original_timestamp;
   }

   /**
    * Prints a timestamp and the data into a string to be returned.
    * @return data contained within the packet
    */
   public String toString() {
      String strMessage = printDigits(m_timestamp.getTime(),12,true);

      // print individual values - special handling for Characters
      for(int i=0; i < m_data.size();i++) {
         if ( m_data.get(i) instanceof Character) {
            strMessage += " " + Character.getNumericValue(((Character)m_data.get(i)).charValue());
         } else {
            strMessage += " " + m_data.get(i);
         }
      }

      return strMessage;
   }

   /**
    * Returns the content of the data element index as integer value
    * @param index index of the data element
    * @return integer value of the data element
    * @throws java.lang.IndexOutOfBoundsException thrown when index is too high
    * @throws java.io.InvalidClassException thrown if data does not contain any known data type
    */
   public int getIntValue(int index) throws IndexOutOfBoundsException, InvalidClassException {
      if ( index >= m_data.size()) throw new IndexOutOfBoundsException();

      Object obj = m_data.get(index);

      // change value to integer - throw error if unknown type is found
      int value;
      if (obj instanceof Character) {
         value = (int) ((Character)obj).charValue();
      } else if (obj instanceof Short) {
         value = (int) ((Short)obj).shortValue();
      } if (obj instanceof Integer) {
         value = (int) ((Integer)obj).intValue();
      } else {
         throw new InvalidClassException("Unkown data type within DataPacket value");
      }

      return value;
   }

   /**
    * Retrieves the maximal value for the element at position index.
    * @param index
    * @return
    * @throws java.lang.IndexOutOfBoundsException thrown when index is too high
    * @throws java.io.InvalidClassException thrown if data does not contain any known data type
    */
   public long getMaxValue(int index) throws IndexOutOfBoundsException, InvalidClassException {
      if ( index >= m_data.size()) throw new IndexOutOfBoundsException();

      Object obj = m_data.get(index);

      // get maximum value - throw error if unknown type is found
      long value;
      if (obj instanceof Character) {
         value = Character.MAX_VALUE;
      } else if (obj instanceof Short) {
         value = Short.MAX_VALUE;
      } if (obj instanceof Integer) {
         value = Integer.MAX_VALUE;
      } else {
         throw new InvalidClassException("Unkown data type within DataPacket value");
      }

      return value;
   }

    /**
     * Returns a string with iDigits bytes representing the number given. This relates to printf("%03f",iNumber) with zeroPadding=true and iDigits=3.
     * @param iNumber  Number to convert
     * @param iDigits  Digits to represent
     * @param zeroPadding fill in leading zeros
     * @return string with converted number
     */
    private String printDigits( long iNumber, int iDigits, boolean zeroPadding) {
        byte [] converted = new byte[iDigits];
        long curNumber = iNumber;

        // step from LSB to MSB
        for (int i=0; i< converted.length; i++) {
            if ( curNumber > 0 ) {
                converted[converted.length-1-i] = (byte) ('0' + curNumber % 10);
                curNumber /= 10;
            } else {
                converted[converted.length-1-i] = (byte) (zeroPadding ? '0' : ' ');
            }
        }
        return new String(converted);
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
class Index  extends Controller
{
	public function index()
	{
		return $this->fetch();
	}

}


text:
var rk = require('rekuire');

var processorFactory = rk('processors/processor_factory.js');

function Entry(path, golemSrc, golemDest) {
  this._path = path;
  this._dest = path.replace(golemSrc, golemDest);

  var split = path.replace(golemSrc, '').split('/');
  this._name = split[split.length - 1];
  this._parent = split[split.length - 2];
  this._grandParent = split[split.length - 3];

  this._processor = processorFactory.getProcessor(this);
}

Entry.prototype.path = function() {
  return this._path;
};

Entry.prototype.dest = function() {
  return this._dest;
};

Entry.prototype.name = function() {
  return this._name;
};

Entry.prototype.parent = function() {
  return this._parent;
};

Entry.prototype.grandParent = function() {
  return this._grandParent;
};

Entry.prototype.processor = function() {
  return this._processor;
};

module.exports = Entry


text:
package jp.co.acroquest.endosnipe.collector.notification;

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

import jp.co.acroquest.endosnipe.collector.exception.InitializeException;
import jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender;

/**
 * アラーム通知を行うObserverクラスの
 * @author fujii
 *
 */
public class AlarmObserverFactory
{
    private SMTPSender smtpSender_;

    /**
     * アラーム通知を行うオブジェクトを取得する。
     * @param entry {@link AlarmEntry}
     * @return アラーム通知を行うオブジェクト一覧
     */
    public List<AlarmObserver> getAlarmObserverList(final AlarmEntry entry)
    {
        List<AlarmObserver> observerList = new ArrayList<AlarmObserver>();

        if (entry.isSendMail())
        {
            if (smtpSender_ == null)
            {
                try
                {
                    smtpSender_ = new SMTPSender();
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();
                }
                catch (InitializeException ex)
                {
                    ex.printStackTrace();
                }
            }
            observerList.add(smtpSender_);
        }
        return observerList;

    }
}


text:
/*	$NetBSD: networkdelta.c,v 1.12 2003/08/07 11:25:46 agc Exp $	*/

/*-
 * Copyright (c) 1985, 1993 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)networkdelta.c	8.3 (Berkeley) 4/27/95";
#else
__RCSID("$NetBSD: networkdelta.c,v 1.12 2003/08/07 11:25:46 agc Exp $");
#endif
#endif /* not lint */

#include "globals.h"

static long median(float, float*, long*, long*, unsigned int);

/*
 * Compute a corrected date.
 *	Compute the median of the reasonable differences.  First compute
 *	the median of all authorized differences, and then compute the
 *	median of all differences that are reasonably close to the first
 *	median.
 *
 * This differs from the original BSD implementation, which looked for
 *	the largest group of machines with essentially the same date.
 *	That assumed that machines with bad clocks would be uniformly
 *	distributed.  Unfortunately, in real life networks, the distribution
 *	of machines is not uniform among models of machines, and the
 *	distribution of errors in clocks tends to be quite consistent
 *	for a given model.  In other words, all model VI Supre Servres
 *	from GoFast Inc. tend to have about the same error.
 *	The original BSD implementation would chose the clock of the
 *	most common model, and discard all others.
 *
 *	Therefore, get best we can do is to try to average over all
 *	of the machines in the network, while discarding "obviously"
 *	bad values.
 */
long
networkdelta(void)
{
	struct hosttbl *htp;
	long med;
	long lodelta, hidelta;
	long logood, higood;
	long x[NHOSTS];
	long *xp;
	int numdelta;
	float eps;

	/*
	 * compute the median of the good values
	 */
	med = 0;
	numdelta = 1;
	xp = &x[0];
	*xp = 0;			/* account for ourself */
	for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
		if (htp->good
		    && htp->noanswer == 0
		    && htp->delta != HOSTDOWN) {
			med += htp->delta;
			numdelta++;
			*++xp = htp->delta;
		}
	}

	/*
	 * If we are the only trusted time keeper, then do not change our
	 * clock.  There may be another time keeping service active.
	 */
	if (numdelta == 1)
		return 0;

	med /= numdelta;
	eps = med - x[0];
	if (trace)
		fprintf(fd, "median of %d values starting at %ld is about ",
			numdelta, med);
	med = median(med, &eps, &x[0], xp+1, VALID_RANGE);

	/*
	 * compute the median of all values near the good median
	 */
	hidelta = med + GOOD_RANGE;
	lodelta = med - GOOD_RANGE;
	higood = med + VGOOD_RANGE;
	logood = med - VGOOD_RANGE;
	xp = &x[0];
	htp = &self;
	do {
		if (htp->noanswer == 0
		    && htp->delta >= lodelta
		    && htp->delta <= hidelta
		    && (htp->good
			|| (htp->delta >= logood
			    && htp->delta <= higood))) {
			*xp++ = htp->delta;
		}
	} while (&self != (htp = htp->l_fwd));

	if (xp == &x[0]) {
		if (trace)
			fprintf(fd, "nothing close to median %ld\n", med);
		return med;
	}

	if (xp == &x[1]) {
		if (trace)
			fprintf(fd, "only value near median is %ld\n", x[0]);
		return x[0];
	}

	if (trace)
		fprintf(fd, "median of %ld values starting at %ld is ",
		        (long)(xp - &x[0]), med);
	return median(med, &eps, &x[0], xp, 1);
}

/*
 * compute the median of an array of signed integers, using the idea
 *	in <<Numerical Recipes>>.
 */
static long
median(float a,				/* initial guess for the median */
       float *eps_ptr,			/* spacing near the median */
       long *x, long *xlim,		/* the data */
       unsigned int gnuf)		/* good enough estimate */
{
	long *xptr;
	float ap = LONG_MAX;		/* bounds on the median */
	float am = -LONG_MAX;
	float aa;
	int npts;			/* # of points above & below guess */
	float xp;			/* closet point above the guess */
	float xm;			/* closet point below the guess */
	float eps;
	float dum, sum, sumx;
	int pass;
#define AMP	1.5			/* smoothing constants */
#define AFAC	1.5

	eps = *eps_ptr;
	if (eps < 1.0) {
		eps = -eps;
		if (eps < 1.0)
			eps = 1.0;
	}

	for (pass = 1; ; pass++) {	/* loop over the data */
		sum = 0.0;
		sumx = 0.0;
		npts = 0;
		xp = LONG_MAX;
		xm = -LONG_MAX;

		for (xptr = x; xptr != xlim; xptr++) {
			float xx = *xptr;

			dum = xx - a;
			if (dum != 0.0) {	/* avoid dividing by 0 */
				if (dum > 0.0) {
					npts++;
					if (xx < xp)
						xp = xx;
				} else {
					npts--;
					if (xx > xm)
						xm = xx;
					dum = -dum;
				}
				dum = 1.0/(eps + dum);
				sum += dum;
				sumx += xx * dum;
			}
		}

		if (ap-am < gnuf || sum == 0) {
			if (trace)
				fprintf(fd,
			           "%ld in %d passes; early out balance=%d\n",
				        (long)a, pass, npts);
			return a;	/* guess was good enough */
		}

		aa = (sumx/sum-a)*AMP;
		if (npts >= 2) {	/* guess was too low */
			am = a;
			aa = xp + max(0.0, aa);
			if (aa > ap)
				aa = (a + ap)/2;

		} else if (npts <= -2) {  /* guess was two high */
			ap = a;
			aa = xm + min(0.0, aa);
			if (aa < am)
				aa = (a + am)/2;

		} else {
			break;		/* got it */
		}

		if (a == aa) {
			if (trace)
				fprintf(fd,
				  "%ld in %d passes; force out balance=%d\n",
				        (long)a, pass, npts);
			return a;
		}
		eps = AFAC*abs(aa - a);
		*eps_ptr = eps;
		a = aa;
	}

	if (((x - xlim) % 2) != 0) {    /* even number of points? */
		if (npts == 0)		/* yes, return an average */
			a = (xp+xm)/2;
		else if (npts > 0)
			a =  (a+xp)/2;
		else
			a = (xm+a)/2;

	} else 	if (npts != 0) {	/* odd number of points */
		if (npts > 0)
			a = xp;
		else
			a = xm;
	}

	if (trace)
		fprintf(fd, "%ld in %d passes\n", (long)a, pass);
	return a;
}


text:
#ifndef SVGResourcesCycleSolver_h
#define SVGResourcesCycleSolver_h

#include "wtf/Allocator.h"
#include "wtf/HashSet.h"
#include "wtf/Noncopyable.h"

namespace blink {

class LayoutObject;
class LayoutSVGResourceContainer;
class SVGResources;

class SVGResourcesCycleSolver {
    STACK_ALLOCATED();
    WTF_MAKE_NONCOPYABLE(SVGResourcesCycleSolver);
public:
    SVGResourcesCycleSolver(LayoutObject*, SVGResources*);
    ~SVGResourcesCycleSolver();

    void resolveCycles();

    typedef HashSet<LayoutSVGResourceContainer*> ResourceSet;

private:
    bool resourceContainsCycles(LayoutSVGResourceContainer*);
    void breakCycle(LayoutSVGResourceContainer*);

    LayoutObject* m_layoutObject;
    SVGResources* m_resources;

    ResourceSet m_activeResources;
    ResourceSet m_dagCache;
};

}

#endif


text:
package com.intellij.notification.impl.ui;

import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.impl.NotificationSettings;
import com.intellij.notification.impl.NotificationsConfigurationImpl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.ui.ComboBoxTableRenderer;
import com.intellij.openapi.ui.StripeTable;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;

/**
 * @author spleaner
 */
public class NotificationsConfigurablePanel extends JPanel implements Disposable {
  private NotificationsTable myTable;
  private static final String REMOVE_KEY = "REMOVE";
  private final JCheckBox myDisplayBalloons;

  public NotificationsConfigurablePanel() {
    setLayout(new BorderLayout());
    myTable = new NotificationsTable();

    JScrollPane scrollPane = new JBScrollPane(myTable);
    scrollPane.setBorder(new LineBorder(UIUtil.getBorderColor()));
    add(scrollPane, BorderLayout.CENTER);
    myDisplayBalloons = new JCheckBox("Display balloon notifications");
    myDisplayBalloons.setMnemonic('b');
    add(myDisplayBalloons, BorderLayout.NORTH);
    myDisplayBalloons.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        myTable.repaint();
      }

    });

    myTable.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), REMOVE_KEY);
    myTable.getActionMap().put(REMOVE_KEY, new AbstractAction() {
      public void actionPerformed(final ActionEvent e) {
        removeSelected();
      }
    });
  }

  private void removeSelected() {
    myTable.removeSelected();
  }

  public void dispose() {
    myTable = null;
  }

  public boolean isModified() {
    final List<SettingsWrapper> list = myTable.getAllSettings();
    for (SettingsWrapper settingsWrapper : list) {
      if (settingsWrapper.hasChanged()) {
        return true;
      }
    }

    return NotificationsConfigurationImpl.getNotificationsConfigurationImpl().SHOW_BALLOONS != myDisplayBalloons.isSelected();
  }

  public void apply() {
    final List<SettingsWrapper> list = myTable.getAllSettings();
    for (SettingsWrapper settingsWrapper : list) {
      settingsWrapper.apply();
    }

    NotificationsConfigurationImpl.getNotificationsConfigurationImpl().SHOW_BALLOONS = myDisplayBalloons.isSelected();
  }

  public void reset() {
    final List<SettingsWrapper> list = myTable.getAllSettings();
    for (SettingsWrapper settingsWrapper : list) {
      settingsWrapper.reset();
    }

    myDisplayBalloons.setSelected(NotificationsConfigurationImpl.getNotificationsConfigurationImpl().SHOW_BALLOONS);

    myTable.invalidate();
    myTable.repaint();
  }

  private class NotificationsTable extends StripeTable {
    private static final int ID_COLUMN = 0;
    private static final int DISPLAY_TYPE_COLUMN = 1;
    private static final int LOG_COLUMN = 2;

    public NotificationsTable() {
      super(new NotificationsTableModel());

      final TableColumn idColumn = getColumnModel().getColumn(ID_COLUMN);
      idColumn.setPreferredWidth(200);

      final TableColumn displayTypeColumn = getColumnModel().getColumn(DISPLAY_TYPE_COLUMN);
      displayTypeColumn.setMaxWidth(300);
      displayTypeColumn.setPreferredWidth(250);
      displayTypeColumn.setCellRenderer(new ComboBoxTableRenderer<NotificationDisplayType>(NotificationDisplayType.values()) {
        @Override
        protected void customizeComponent(NotificationDisplayType value, JTable table, boolean isSelected) {
          super.customizeComponent(value, table, isSelected);
          if (!myDisplayBalloons.isSelected() && !isSelected) {
            setBackground(UIUtil.getComboBoxDisabledBackground());
            setForeground(UIUtil.getComboBoxDisabledForeground());
          }
        }

        @Override
        protected String getTextFor(@NotNull NotificationDisplayType value) {
          return value.getTitle();
        }
      });

      displayTypeColumn.setCellEditor(new ComboBoxTableRenderer<NotificationDisplayType>(NotificationDisplayType.values()) {

        @Override
        public boolean isCellEditable(EventObject event) {
          if (!myDisplayBalloons.isSelected()) {
            return false;
          }

          if (event instanceof MouseEvent) {
            return ((MouseEvent)event).getClickCount() >= 1;
          }

          return false;
        }

        @Override
        protected boolean isApplicable(NotificationDisplayType value, int row) {
          if (value != NotificationDisplayType.TOOL_WINDOW) return true;

          String groupId = ((NotificationsTableModel)getModel()).getSettings(row).getGroupId();
          return NotificationsConfigurationImpl.getNotificationsConfigurationImpl().hasToolWindowCapability(groupId);
        }

        @Override
        protected String getTextFor(@NotNull NotificationDisplayType value) {
          return value.getTitle();
        }
      });

      final TableColumn logColumn = getColumnModel().getColumn(LOG_COLUMN);
      logColumn.setMaxWidth(logColumn.getPreferredWidth());

      getEmptyText().setText("No notifications configured");
    }

    @Override
    public Dimension getMinimumSize() {
      return calcSize(super.getMinimumSize());
    }

    @Override
    public Dimension getPreferredSize() {
      return calcSize(super.getPreferredSize());
    }

    private Dimension calcSize(@NotNull final Dimension s) {
      final Container container = getParent();
      if (container != null) {
        final Dimension size = container.getSize();
        return new Dimension(size.width, s.height);
      }

      return s;
    }

    public List<SettingsWrapper> getSettings() {
      return ((NotificationsTableModel)getModel()).getSettings();
    }

    public void removeSelected() {
      final ListSelectionModel selectionModel = getSelectionModel();
      if (!selectionModel.isSelectionEmpty()) {
        final int min = selectionModel.getMinSelectionIndex();
        final int max = selectionModel.getMaxSelectionIndex();

        final List<SettingsWrapper> settings = getSettings();
        final List<SettingsWrapper> toRemove = new ArrayList<SettingsWrapper>();

        for (int i = min; i <= max && i < settings.size(); i++) {
          toRemove.add(settings.get(i));
        }

        if (toRemove.size() > 0) {
          ((NotificationsTableModel)getModel()).remove(toRemove);

          revalidate();
          repaint();
        }
      }
    }

    public List<SettingsWrapper> getAllSettings() {
      return ((NotificationsTableModel)getModel()).getAllSettings();
    }
  }

  private static class SettingsWrapper extends NotificationSettings {
    private final NotificationSettings myOriginal;
    private boolean myRemoved = false;

    private SettingsWrapper(@NotNull final NotificationSettings original) {
      super(original.getGroupId(), original.getDisplayType(), original.isShouldLog());
      myOriginal = original;
    }

    public boolean hasChanged() {
      return !getDisplayType().equals(myOriginal.getDisplayType()) || isShouldLog() != myOriginal.isShouldLog() || myRemoved;
    }

    public void remove() {
      myRemoved = true;
    }

    public boolean isRemoved() {
      return myRemoved;
    }

    public void apply() {
      if (myRemoved) {
        NotificationsConfigurationImpl.remove(myOriginal.getGroupId());
      }
      else {
        if (hasChanged()) {
          myOriginal.setDisplayType(getDisplayType());
          myOriginal.setShouldLog(isShouldLog());
        }
      }
    }

    public void reset() {
      if (hasChanged()) {
        setDisplayType(myOriginal.getDisplayType());
        myRemoved = false;
      }
    }
  }

  private static class NotificationsTableModel extends AbstractTableModel {
    private final List<SettingsWrapper> mySettings;

    public NotificationsTableModel() {
      final NotificationSettings[] settings = NotificationsConfigurationImpl.getAllSettings();
      final List<SettingsWrapper> list = new ArrayList<SettingsWrapper>();
      for (NotificationSettings setting : settings) {
        list.add(new SettingsWrapper(setting));
      }

      mySettings = list;
    }

    public List<SettingsWrapper> getSettings() {
      return getActiveSettings();
    }

    @Override
    public void setValueAt(final Object value, final int rowIndex, final int columnIndex) {
      final NotificationSettings settings = getSettings(rowIndex);

      switch (columnIndex) {
        case NotificationsTable.DISPLAY_TYPE_COLUMN:
          settings.setDisplayType((NotificationDisplayType)value);
          break;
        case NotificationsTable.LOG_COLUMN:
          settings.setShouldLog((Boolean)value);
          break;
      }
    }

    public int getRowCount() {
      return getSettings().size();
    }

    public NotificationSettings getSettings(int row) {
      return getSettings().get(row);
    }

    public int getColumnCount() {
      return 3;
    }

    @Override
    public Class<?> getColumnClass(final int columnIndex) {
      if (NotificationsTable.DISPLAY_TYPE_COLUMN == columnIndex) {
        return NotificationDisplayType.class;
      }
      if (NotificationsTable.LOG_COLUMN == columnIndex) {
        return Boolean.class;
      }

      return String.class;
    }

    @Override
    public String getColumnName(final int column) {
      switch (column) {
        case NotificationsTable.ID_COLUMN:
          return "Group";
        case NotificationsTable.LOG_COLUMN:
          return "Log";
        default:
          return "Popup";
      }
    }

    @Override
    public boolean isCellEditable(final int rowIndex, final int columnIndex) {
      return columnIndex > 0;
    }

    public Object getValueAt(final int rowIndex, final int columnIndex) {
      switch (columnIndex) {
        case NotificationsTable.ID_COLUMN:
          return getSettings().get(rowIndex).getGroupId();
        case NotificationsTable.LOG_COLUMN:
          return getSettings().get(rowIndex).isShouldLog();
        case NotificationsTable.DISPLAY_TYPE_COLUMN:
        default:
          return getSettings().get(rowIndex).getDisplayType();
      }
    }

    public static void remove(List<SettingsWrapper> toRemove) {
      for (SettingsWrapper settingsWrapper : toRemove) {
        settingsWrapper.remove();
      }
    }

    public List<SettingsWrapper> getAllSettings() {
      return mySettings;
    }

    private List<SettingsWrapper> getActiveSettings() {
      final List<SettingsWrapper> result = new ArrayList<SettingsWrapper>(mySettings);
      final Iterator<SettingsWrapper> iterator = result.iterator();
      while (iterator.hasNext()) {
        final SettingsWrapper wrapper = iterator.next();
        if (wrapper.isRemoved()) {
          iterator.remove();
        }
      }

      return result;
    }
  }
}


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

namespace QuestEditor
{
	class Program
	{
		//Перед вами стоит задача написать кусочек редактора квестов для RPG игры. Редактор представляет собой набор готовых блоков с
		//основными условиями и их результатами, которые может комбинировать между собой пользователь.

		//Вы отвечаете за разработку бизнес-слоя, содержащего "блоки" квеста и их логику. Выберите подходящий паттерн(ы),
		//которые вы будете использовать для реализации данной задачи.

		//Обоснуйте свой выбор. Напишите простейший пример (без UI) для одного из блоков.

		//Пример квеста в редакторе:

		//герой повстречал персонажа -> вызвать диалог -> вывести текст -> ... -> при выборе первого пункта добавить квест на выполение в таблицу квестов.

		//Предложенное решение должно быть легко расширяемым для быстрого добавления новых элементов в редактор.
		static void Main(string[] args)
		{
		}
	}
}


text:
static wchar LogName[NM];
static RAR_CHARSET LogCharset=RCH_DEFAULT;

void InitLogOptions(const wchar *LogFileName,RAR_CHARSET CSet)
{
  wcsncpyz(LogName,LogFileName,ASIZE(LogName));
  LogCharset=CSet;
}

#ifndef SILENT
void Log(const wchar *ArcName,const wchar *fmt,...)
{
  // Preserve the error code for possible following system error message.
  int Code=ErrHandler.GetSystemErrorCode();

  uiAlarm(UIALARM_ERROR);

  // This buffer is for format string only, not for entire output,
  // so it can be short enough.
  wchar fmtw[1024];
  PrintfPrepareFmt(fmt,fmtw,ASIZE(fmtw));

  safebuf wchar Msg[2*NM+1024];
  va_list arglist;
  va_start(arglist,fmt);
  vswprintf(Msg,ASIZE(Msg),fmtw,arglist);
  va_end(arglist);
  eprintf(L"%ls",Msg);
  ErrHandler.SetSystemErrorCode(Code);
}
#endif


text:
import codecs
import re
from os.path import dirname, join, abspath

from setuptools import find_packages, setup

NAME = 'vigenere'
PACKAGES = find_packages(where='src')
META_PATH = join('src', 'vigenere', '__init__.py')
KEYWORDS = ['encryption']
CLASSIFIERS = [
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: MacOS :: MacOS X',
    'Operating System :: Unix',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.5',
    'Topic :: Security :: Cryptography'
]
INSTALL_REQUIRES = []

HERE = abspath(dirname(__file__))

def read(*parts):
    """
    Build an absolute path from `parts` and return the contents of the resulting file.
    """
    with codecs.open(join(HERE, *parts), 'rb', 'utf-8') as f:
        return f.read()

META_FILE = read(META_PATH)

def find_meta(meta):
    """
    Extract __*meta*__ from META_FILE.
    """
    meta_match = re.search(
        r'^__{meta}__ = [\'"]([^\'"]*)[\'"]'.format(meta=meta),
        META_FILE, re.M
    )
    if meta_match:
        return meta_match.group(1)
    raise RuntimeError('Unable to find __{meta}__ string.'.format(meta=meta))

if __name__ == '__main__':
    setup(
        name=NAME,
        description=find_meta('description'),
        license=find_meta('license'),
        url=find_meta('uri'),
        version=find_meta('version'),
        author=find_meta("author"),
        author_email=find_meta("email"),
        maintainer=find_meta("author"),
        maintainer_email=find_meta("email"),
        keywords=KEYWORDS,
        packages=PACKAGES,
        package_dir={"": "src"},
        zip_safe=False,
        classifiers=CLASSIFIERS,
        install_requires=INSTALL_REQUIRES,
    )


text:
@interface WYAutoCarusel ()<UIScrollViewDelegate>

//定义全局变量
@property(nonatomic,strong)UIScrollView * scrollView;

//页面控制
@property(nonatomic,strong)UIPageControl * pageControl;

@end

@implementation WYAutoCarusel

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)createCaruselWithFrame:(CGRect)rect WithSuperView:(UIView *)superView WithImageUrlArr:(NSArray *)imageUrlArr WithPlaceholderImageName:(NSString *)imageName WithInterval:(NSInteger)interval{

    self.scrollView = [[UIScrollView alloc] initWithFrame:rect];

    for (int i = 0; i < imageUrlArr.count + 2; i++) {

        UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width * i, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];

        if (i == 0) {
            [imageV sd_setImageWithURL:[NSURL URLWithString:[imageUrlArr lastObject]] placeholderImage:[UIImage imageNamed:imageName]];
        }else if (i == imageUrlArr.count + 1){
            [imageV sd_setImageWithURL:[NSURL URLWithString:[imageUrlArr firstObject]] placeholderImage:[UIImage imageNamed:imageName]];
        }else{
            [imageV sd_setImageWithURL:[NSURL URLWithString:imageUrlArr[i - 1]] placeholderImage:[UIImage imageNamed:imageName]];
        }

        imageV.tag = 10000 + i;

        imageV.userInteractionEnabled = YES;

        [imageV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewGestureAction:)]];
//        [imageV addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewLongGestureAction:)]];

        [self.scrollView addSubview:imageV];
    }

    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * (imageUrlArr.count + 2), self.scrollView.frame.size.height);

    self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);

    self.scrollView.delegate = self;

    self.scrollView.showsHorizontalScrollIndicator = NO;

    self.scrollView.pagingEnabled = YES;

    [self createTimerWithTimeInterval:interval];

    [superView addSubview:self.scrollView];
}

- (void)imageViewGestureAction:(UITapGestureRecognizer *)tap{

//    self.imageActionBlock(tap.view.tag - 10000);

    [self.delegate pushViewController:tap.view.tag];

}

//-(void)imageViewLongGestureAction:(UILongPressGestureRecognizer *)tap
//{
//    [self.timer setFireDate:[NSDate distantFuture]];
//}

- (void)createPageControlWithFrame:(CGRect)rect WithSuperView:(UIView *)superView WithPageNum:(NSInteger)pageNum WithCurrentColor:(UIColor *)currentColor WithTintColor:(UIColor *)tintColor{

    self.pageControl = [[UIPageControl alloc] initWithFrame:rect];

    self.pageControl.currentPageIndicatorTintColor = tintColor;

    self.pageControl.pageIndicatorTintColor = currentColor;

    self.pageControl.numberOfPages = pageNum;

    [superView addSubview:self.pageControl];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    NSLog(@"这里开始拖动");
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{

    [self.timer setFireDate:[NSDate distantPast]];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.scrollView) {
        NSInteger maxPage = scrollView.contentSize.width / scrollView.frame.size.width;
        NSInteger page = scrollView.contentOffset.x / scrollView.frame.size.width;
        if (page == 1) {

            scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width * (maxPage - 1), 0);
            self.pageControl.currentPage = maxPage - 2;

        }else if (page == maxPage - 1){
            scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);
            self.pageControl.currentPage = 0;
        }else{
            self.pageControl.currentPage = page - 1;
        }
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self scrollViewDidEndDecelerating:scrollView];
}

- (void)createTimerWithTimeInterval:(NSInteger)interval{

    self.timer = [[NSTimer alloc] init];

    self.timer = [NSTimer timerWithTimeInterval:interval target:self selector:@selector(changePage) userInfo:nil repeats:YES];

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)changePage{
    NSInteger maxPage = self.scrollView.contentSize.width / self.scrollView.frame.size.width;

    NSInteger page = self.scrollView.contentOffset.x / self.scrollView.frame.size.width;

    if (page == maxPage) {
        page = 0;
    }

    page++;

    [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * page, 0) animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [self.timer invalidate];
}

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

@end


text:
<?php

/**
 * Interface implemented by compiler classes.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @deprecated since 1.12 (to be removed in 3.0)
 */
interface Twig_CompilerInterface
{
    /**
     * Compiles a node.
     *
     * @return $this
     */
    public function compile(Twig_NodeInterface $node);

    /**
     * Gets the current PHP code after compilation.
     *
     * @return string The PHP code
     */
    public function getSource();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>configuration</artifactId>
    <packaging>jar</packaging>
    <name>configuration</name>

    <parent>
        <groupId>com.proofpoint.platform</groupId>
        <artifactId>platform</artifactId>
        <version>2.74-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>jakarta.validation</groupId>
            <artifactId>jakarta.validation-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.el</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>3.2.8</version>
        </dependency>

        <dependency>
            <groupId>com.google.auto.value</groupId>
            <artifactId>auto-value-annotations</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- for testing -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.proofpoint.platform</groupId>
            <artifactId>testing</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>mango.image.InterpolationType.real — mango 0.9.8 documentation</title>

    <link rel="stylesheet" href="../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="mango 0.9.8 documentation" href="../../../index.html" />
    <link rel="up" title="mango.image.InterpolationType" href="../../mango.image.InterpolationType.html" />
    <link rel="next" title="mango.image.InterpolationType.values" href="mango.image.InterpolationType.values.html" />
    <link rel="prev" title="mango.image.InterpolationType.numerator" href="mango.image.InterpolationType.numerator.html" />

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Image Processing and Analysis (<tt class="docutils literal">mango.image</tt>) »

mango.image.InterpolationType »

mango.image.InterpolationType.real¶

<tt class="descclassname">InterpolationType.</tt><tt class="descname">real</tt>¶

the real part of a complex number

Previous topic

mango.image.InterpolationType.numerator

Next topic

mango.image.InterpolationType.values

This Page

Show Source

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Image Processing and Analysis (<tt class="docutils literal">mango.image</tt>) »

mango.image.InterpolationType »

        © Copyright 2014, Department of Applied Mathematics, The Australian National University.
      Created using Sphinx 1.2.3.


text:
set -e -x -o pipefail

mkdir -p $PREFIX/bin

if [ "$(uname)" == "Darwin" ]; then
    echo "Platform: Mac"

    cp $SRC_DIR/bin/* $PREFIX/bin/

elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
    echo "Platform: Linux"

    cd $SRC_DIR/c++/
    # --with-hard-runpath is needed otherwise BLAST programs would search
    # libraries first in the directories defined by the LD_LIBRARY_PATH
    # environment variable, instead of using the rpath specified by conda
    ./configure --prefix=$PREFIX --with-hard-runpath

    make -j${CPU_COUNT}

    cp $SRC_DIR/c++/ReleaseMT/bin/* $PREFIX/bin/
fi

chmod +x $PREFIX/bin/*


text:
module API
  module V1
    # Actions for the v1 Meetings API
    class MeetingsController < ApiVersionsController
      # GET /api/meetings.json
      def index
        @meetings = Meeting.all
      end

      # GET /api/meetings/1.json
      def show
        @meeting = Meeting.find(params[:id])
      end
    end
  end
end


text:
<!DOCTYPE html>

		<title>{{ ctf_name() }}</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="shortcut icon" href="{{ request.script_root }}/themes/{{ ctf_theme() }}/static/img/favicon.ico" type="image/x-icon">
		<link rel="icon" href="{{ request.script_root }}/themes/{{ ctf_theme() }}/static/img/favicon.ico" type="image/x-icon">
		<link rel="stylesheet" href="{{ request.script_root }}/themes/{{ ctf_theme() }}/static/css/vendor/bootstrap.min.css">
		<link rel="stylesheet" href="{{ request.script_root }}/themes/{{ ctf_theme() }}/static/css/vendor/font-awesome/css/font-awesome.min.css" />
		<link href='{{ request.script_root }}/themes/{{ ctf_theme() }}/static/css/vendor/lato.css' rel='stylesheet' type='text/css'>
		<link href='{{ request.script_root }}/themes/{{ ctf_theme() }}/static/css/vendor/raleway.css' rel='stylesheet' type='text/css'>
		<link rel="stylesheet" href="{{ request.script_root }}/themes/{{ ctf_theme() }}/static/css/style.css">
		<link rel="stylesheet" type="text/css" href="{{ request.script_root }}/static/user.css">
		{% block stylesheets %}{% endblock %}

					<button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse" type="button">

					</button>
					{{ ctf_name() }}

						{% for page in pages() %}

{{ page.route|title }}

						{% endfor %}

Teams

						{% if not hide_scores() %}

Scoreboard

						{% endif %}

Challenges

					{% if username is defined %}
						{% if admin %}

Admin

						{% endif %}

Team

Profile

Logout

					{% else %}
						{% if can_register() %}

Register

|

						{% endif %}

Login

					{% endif %}

		{% block content %}
		{% endblock %}

Powered by CTFd

	{% block scripts %}
	{% endblock %}


text:
using namespace tvmet;
using namespace std;
using namespace voom;

typedef SemiflexibleGel<2> Gel;
typedef std::map< std::string, std::string > ParamMap;
typedef ParamMap::iterator PMIter;

struct NodePair {
  Gel::DefNode* node1;
  Gel::DefNode* node2;

  double initAngle;
};

struct DataPoint {
  double rL;

  int nDatPts;
  double mean;
  double stddev;
};

typedef std::vector< DataPoint > DataSet;
typedef std::vector< NodePair > NodePairList;
typedef std::vector< NodePairList > NodePairData;
typedef std::map< Gel::DefNode*, tvmet::Vector<double,2> > InitPositionMap;

int getFilSegs(double avgCL, double nodesPerCL) {
  return (int)((avgCL+1)*nodesPerCL);
}

int getCurGelNum(std::string firstGelName) {
  std::ifstream testStream;
  bool fileFound = true;
  int startPos = firstGelName.find("gelnum");
  int endPos = firstGelName.find(".gelsave");
  int i = atoi((firstGelName.substr(startPos+7,endPos-7-startPos)).data());

  // find first available gel name //
  while(fileFound) {
    testStream.open(firstGelName.c_str());
    if(testStream.fail()) {
      fileFound = false;
    }
    else{
      i++;
      startPos = firstGelName.find("gelnum");
      endPos = firstGelName.find(".gelsave");
      ostringstream tmpi;
      tmpi << i;
      firstGelName.replace(startPos+7,endPos-7-startPos,tmpi.str());
    }
    testStream.close();
  }

  return i;
}

std::string getGelFileName(std::string gelLibDir, ParamMap & pmap, int gelNum=-1) {
  // get necessary parameters from map, construct file name //
  char * gelStoreFN = new char[256];
  double L = atof(pmap["L"].data());
  double l_c = L/(atof(pmap["L/l_c"].data()));
  double kcl = atof(pmap["crosslink stiffness"].data());
  double Wx = atof(pmap["Wx"].data());
  double Wy = atof(pmap["Wy"].data());
  double dL = atof(pmap["dL"].data());
  double Snem = atof(pmap["nematic order parameter"].data());
  std::string gelStoreName;

  if(gelNum == -1){
    sprintf(gelStoreFN,"gel-L=%f-l_C=%f-dL=%f-Wx=%f-Wy=%f-kcl=%f-S=%f-gelnum=1.gelsave",L,l_c,dL,Wx,Wy,kcl,Snem);
    gelStoreName.assign(gelStoreFN);
    gelStoreName.insert(0,gelLibDir);
    gelNum = getCurGelNum(gelStoreName);
    gelStoreName.clear();
    delete gelStoreFN;
    gelStoreFN = new char[128];
  }

  sprintf(gelStoreFN,"gel-L=%f-l_C=%f-dL=%f-Wx=%f-Wy=%f-kcl=%f-S=%f-gelnum=%d.gelsave",L,l_c,dL,Wx,Wy,kcl,Snem,gelNum);
  gelStoreName.assign(gelStoreFN);
  gelStoreName.insert(0,gelLibDir);
  return gelStoreName;
}

// void setParamsfromFileName(std::string fileName, ParamMap & pmap) {

// }

void guessAffineShearX(Gel * gel, double shear) {
  Vector2D cent;
  cent = gel->box()->size();
  cent /= 2.0;
  int nFils = gel->filaments().size();
  for(int i=0; i<nFils; i++) {
    Gel::Filament * fil = gel->filament(i);
    int nNodesHere = fil->nodes.size();
    for(int j=0; j<nNodesHere; j++) {
      Vector2D diff;
      diff = fil->nodes[j]->position() - cent;
      Vector2D affdef;
      affdef[1] = 0.0;
      affdef[0] = shear*diff[1];
      affdef += fil->nodes[j]->position();
      fil->nodes[j]->setPoint(affdef);
    }
  }

}

void guessAffineShearY(Gel * gel, double shear) {
  Vector2D cent;
  cent = gel->box()->size();
  cent /= 2.0;
  int nFils = gel->filaments().size();
  for(int i=0; i<nFils; i++) {
    Gel::Filament * fil = gel->filament(i);
    int nNodesHere = fil->nodes.size();
    for(int j=0; j<nNodesHere; j++) {
      Vector2D diff;
      diff = fil->nodes[j]->position() - cent;
      Vector2D affdef;
      affdef[0] = 0.0;
      affdef[1] = -shear*diff[0];
      affdef += fil->nodes[j]->position();
      fil->nodes[j]->setPoint(affdef);
    }
  }

}

void guessExpXY(Gel * gel, double expand) {
  Vector2D cent;
  cent = gel->box()->size();
  cent /= 2.0;
  int nFils = gel->filaments().size();
  for(int i=0; i<nFils; i++) {
    Gel::Filament * fil = gel->filament(i);
    int nNodesHere = fil->nodes.size();
    for(int j=0; j<nNodesHere; j++) {
      Vector2D diff;
      diff = fil->nodes[j]->position() - cent;
      Vector2D affdef;
      affdef[1] = diff[1]*expand;
      affdef[0] = diff[0]*expand;
      affdef += fil->nodes[j]->position();
      fil->nodes[j]->setPoint(affdef);
    }
  }

}

void guessExpX(Gel * gel, double expand) {
  Vector2D cent;
  cent = gel->box()->size();
  cent /= 2.0;
  int nFils = gel->filaments().size();
  for(int i=0; i<nFils; i++) {
    Gel::Filament * fil = gel->filament(i);
    int nNodesHere = fil->nodes.size();
    for(int j=0; j<nNodesHere; j++) {
      Vector2D diff;
      diff = fil->nodes[j]->position() - cent;
      Vector2D affdef;
      affdef[1] = 0.0;
      affdef[0] = diff[0]*expand;
      affdef += fil->nodes[j]->position();
      fil->nodes[j]->setPoint(affdef);
    }
  }

}

void guessExpY(Gel * gel, double expand) {
  Vector2D cent;
  cent = gel->box()->size();
  cent /= 2.0;
  int nFils = gel->filaments().size();
  for(int i=0; i<nFils; i++) {
    Gel::Filament * fil = gel->filament(i);
    int nNodesHere = fil->nodes.size();
    for(int j=0; j<nNodesHere; j++) {
      Vector2D diff;
      diff = fil->nodes[j]->position() - cent;
      Vector2D affdef;
      affdef[0] = 0.0;
      affdef[1] = diff[1]*expand;
      affdef += fil->nodes[j]->position();
      fil->nodes[j]->setPoint(affdef);
    }
  }

}

int main(int argc, char* argv[]) {

  int verbose = 1;

  char* paramFileName = argv[1];

  std::ifstream inFile(paramFileName);
  if(!(inFile.good())) {
    std::cerr << "Error: input file name does not exist!" << std::endl;
    exit(1);
  }

  std::string pfn(paramFileName);
  int runnumStart = pfn.find_first_of("0123456789");
  int runnumEnd = pfn.find_first_not_of("0123456789",runnumStart);
  int runNum = atoi(pfn.substr(runnumStart,runnumEnd-runnumStart).data());

  char newDirName[128];
  sprintf(newDirName,"mkdir -p Run%d",runNum);
  system(newDirName);

  if(USEOPENMP) std::cout << "Open MP being used." << std::endl;
  else std::cout << "Open MP not being used." << std::endl;

  ////////////////////////////////////////////////////////////////////
  // Parameters
  ////////////////////////////////////////////////////////////////////

  double kT = -1.0; // temperature in pN-microns //
  double kC = -1.0; // bending modulus of actin in pN-microns^2 //
  double L_p = -1.0; // persistence length of actin in microns //
  double visc = -1.0; // viscosity //
  //  double r = -1.0; // radius of actin filaments in microns //
  double l_B = -1.0; // ratio of bending/stretching modulii //
  tvmet::Vector<double,2> syssize; // system size in microns //
  double kBond = -1.0; // spring constant for rods in pN/micron //
  double kAngle = -1.0; // spring constant for rod joints (angles) in pN-microns //
  double kcl = -1.0; // crosslink spring constant (negative for pinned node crosslinks) in pN/micron //
  double dt = -1.0; // time step in seconds //
  double L = -1.0; // length of filaments in microns //
  double dL = -1.0; // length of rods (filament sections) in microns //
  double tmpratio = -1.0; // nominal value of L/l_c //
  double actuall_c = -1.0; // actual value of l_c //
  double lambda = -1.0; // l_c*(l_c/l_B)^z //
  double F_max = -1.0; // maximum force allowed in nonlinear rods (entropic elasticity) //
  int fitOrder = -1; // order of fitting function to use for entropic springs //
  double filDens = -1.0; // filament density in microns^-2 //
  int nNodesPerFilament = -1; // # of nodes per filament //
  double nodesPerCL = 2.5; // avg # of nodes between crosslinks //
  double nematicOP = 0.0;
  double actualnemOP = -1.0;
  double nemDirectorAngle = 0.0;
  std::string nemPDFparam;
  bool prestress = false;
  std::string nemPDFtype = "Gaussian";

  int nGels2avg = 1;
  int curGelNum = -1;

  std::string gelDirectory = "./";
  std::string gelFileName;
  std::string bondType = "Spring";

  std::string solverType = "LBFGSB";

  bool cutOffEnds = false;

  bool relaxPrestress = false;

  bool retrieveGel = false;

  bool shearXtest = false;
  bool shearYtest = false;
  bool expXYtest = false;
  bool expXtest = false;
  bool expYtest = false;

  bool writeStates = false;
  bool zeroReturn = false;

  bool adaptiveMeshing = false;
  double minLength = -1.0;

  std::string polydisp = "none";
  double actualL;

  // parameters for nematic test //
  double shrEnd = -1.0;
  int nShrSteps = -1;
  double shrStep = -1.0;
  double stretchEnd = -1.0;
  int nStretchSteps = -1;
  double stretchStep = -1.0;
  double expandEnd = -1.0;
  int nExpandSteps = -1;
  double expandStep = -1.0;

  ParamMap pm;
  std::string curString;
  std::string parName;
  std::string parValStr;
  double parVal;
  std::string::iterator curStrIt;

  while(!inFile.eof()) {
    char curLine[256];
    inFile.getline(curLine,256);
    curString.assign(curLine);
    curStrIt = curString.begin();
    if(*curStrIt != '#' && curString.length() > 2) {
      int pNameEnd = curString.find_first_of('\t');
      parName.assign(curString,0,pNameEnd);
      pNameEnd = curString.find_first_not_of('\t',pNameEnd);
      pNameEnd = curString.find_first_of('\t',pNameEnd);
      int pNameBegin = curString.find_first_not_of('\t',pNameEnd);
      pNameEnd = curString.find_first_of('\t',pNameBegin);
      parValStr.assign(curString,pNameBegin,pNameEnd-pNameBegin);
      if(parName.find("GelFile") != string::npos) gelFileName.assign(parValStr);
      else if(parName.find("GelDirectory") != string::npos) gelDirectory.assign(parValStr);
      else if(parName.find("kT")!=string::npos) {
	kT = atof(parValStr.data());
	pm.insert(pair< std::string, std::string>("kT",parValStr));
      }
      else if(parName.find("L_p")!=string::npos) L_p = atof(parValStr.data());
      else if(parName.find("kC")!=string::npos) kC = atof(parValStr.data());
      else if(parName.find("visc")!=string::npos) {
	visc = atof(parValStr.data());
	pm.insert(pair< std::string, std::string >("viscosity",parValStr));
      }
      else if(parName.find("SolverType")!=string::npos) solverType = parValStr.data();
      // else if(parName.find("r")!=string::npos) r = parVal;
      else if(parName.find("F_max")!=string::npos) {
	F_max = atof(parValStr.data());
	pm.insert(pair< std::string, std::string >("F_max",parValStr));
	bondType = "EntropicSpring";
      }
      else if(parName.find("NodesPerCL")!=string::npos) {
	nodesPerCL = atof(parValStr.data());
      }
      else if(parName.find("dt")!=string::npos) {
	dt = atof(parValStr.data());
	pm.insert(pair< std::string, std::string >("time step",parValStr));
      }
      else if(parName.find("L/l_C")!=string::npos) tmpratio = atof(parValStr.data());
      else if(parName.find("Wx")!=string::npos) syssize[0] = atof(parValStr.data());
      else if(parName.find("Wy")!=string::npos) syssize[1] = atof(parValStr.data());
      else if(parName.find("kcl")!=string::npos) {
	kcl = atof(parValStr.data());
	pm.insert(pair< std::string, std::string >("crosslink stiffness",parValStr));
      }
      else if(parName.find("l_B")!=string::npos) {
	l_B = atof(parValStr.data());
	pm.insert(pair< std::string, std::string >("l_B",parValStr));
      }
      else if(parName.find("fit")!=string::npos) {
	fitOrder = atoi(parValStr.data());
	pm.insert(pair< std::string, std::string >("fit order",parValStr));
      }
      else if(parName.find("Shear_final")!=string::npos) shrEnd = atof(parValStr.data());
      else if(parName.find("Shear_size")!=string::npos) shrStep = atof(parValStr.data());
      else if(parName.find("Stretch_final")!=string::npos) stretchEnd = atof(parValStr.data());
      else if(parName.find("Stretch_steps")!=string::npos) nStretchSteps = atoi(parValStr.data());
      else if(parName.find("Expand_final")!=string::npos) expandEnd = atof(parValStr.data());
      else if(parName.find("Expand_steps")!=string::npos) nExpandSteps = atoi(parValStr.data());
//       else if(parName.find("Affine_method")!=string::npos) affmethod.assign(parValStr);
//       else if(parName.find("Affine_shear")!=string::npos) affshear = atof(parValStr.data());
//       else if(parName.find("Affine_gels")!=string::npos) nGels2avg = atoi(parValStr.data());
//       else if(parName.find("Affine_space")!=string::npos) affbinspace = atof(parValStr.data());
//       else if(parName.find("Affine_tol")!=string::npos) affbintol = atof(parValStr.data());
//       else if(parName.find("Affine_min")!=string::npos) affmin = atof(parValStr.data());
//       else if(parName.find("Affine_max")!=string::npos) affmax = atof(parValStr.data());
      else if(parName.find("FilDens")!=string::npos) filDens = atof(parValStr.data());
      else if(parName.find("NemPDF_param")!=string::npos) {
	nemPDFparam = parValStr;
	pm.insert(pair< std::string, std::string >("nematic PDF param",nemPDFparam));
      }
      else if(parName.find("NemPDF_type")!=string::npos) {
	nemPDFtype = parValStr;
	pm.insert(pair< std::string, std::string >("orientational PDF",nemPDFtype));
      }
      else if(parName.find("NematicOP")!=string::npos) {
	pm.insert(pair< std::string, std::string >("nematic order parameter",parValStr));
	nematicOP = atof(parValStr.data());
      }
      else if(parName.find("NemDirAngle")!=string::npos) {
        pm.insert(pair< std::string, std::string >("nematic direction angle",parValStr));
	nemDirectorAngle = atof(parValStr.data());
      }
      else if(parName.find("MaxPrestress")!=string::npos) {
	if(atof(parValStr.data()) > 1.0e-6) {
	  pm.insert(pair< std::string, std::string >("maximum prestress",parValStr));
        }
      }
      else if(parName.find("RelaxPrestress")!=string::npos) {
	if(atof(parValStr.data()) >= .5) relaxPrestress = true;
      }
      else if(parName.find("Prestress")!=string::npos) {
	if(atof(parValStr.data()) < 0.5) pm.insert(pair< std::string, std::string >("prestress","false"));
	else pm.insert(pair< std::string, std::string >("prestress","true"));
      }
      else if(parName.find("Retrieve")!=string::npos) {
	if(atof(parValStr.data()) < 0.5) retrieveGel = false;
	else retrieveGel = true;
      }
      else if(parName.find("AdaptiveMesh")!=string::npos) {
	if(atof(parValStr.data()) >= .5) adaptiveMeshing = true;
      }
      else if(parName.find("ShortSegRelief")!=string::npos) {
	pm.insert(pair< std::string, std::string >("nearby pair removal method",parValStr.data()));
      }
      else if(parName.find("TargetSegLength")!=string::npos) {
	pm.insert(pair< std::string, std::string >("target segment length", parValStr.data()));
      }
      else if(parName.find("MinSegLength")!=string::npos) {
        minLength = atof(parValStr.data());
      }
      else if(parName.find("CutOffEnds")!=string::npos) {
	if(atof(parValStr.data()) >= 0.5) cutOffEnds = true;
      }
      else if(parName.find("ShearXTest")!=string::npos) {
	if(atof(parValStr.data()) >= .5) shearXtest = true;
      }
      else if(parName.find("ShearYTest")!=string::npos) {
	if(atof(parValStr.data()) >= .5) shearYtest = true;
      }
      else if(parName.find("ExpXYTest")!=string::npos) {
	if(atof(parValStr.data()) >= .5) expXYtest = true;
      }
      else if(parName.find("ExpXTest")!=string::npos) {
	if(atof(parValStr.data()) >= .5) expXtest = true;
      }
      else if(parName.find("ExpYTest")!=string::npos) {
	if(atof(parValStr.data()) >= .5) expYtest = true;
      }
      else if(parName.find("WriteStates")!=string::npos) {
	if(atof(parValStr.data()) >= .5) writeStates = true;
      }
      else if(parName.find("Zero_Return")!=string::npos) {
	if(atof(parValStr.data()) >= .5) zeroReturn = true;
      }
      else if(parName.find("Polydispersity")!=string::npos) {
	polydisp = parValStr;
	pm.insert(pair< std::string, std::string >("polydispersity",polydisp));
      }
      else if(parName.find("Long/short")!=string::npos) {
	pm.insert(pair< std::string, std::string >("longshortratio",parValStr));
      }
      else if(parName.find("Long fraction")!=string::npos) {
	pm.insert(pair< std::string, std::string >("longfraction",parValStr));
      }
      else if(parName.find("Min. length")!=string::npos) {
	pm.insert(pair< std::string, std::string >("minlength",parValStr));
      }
      else if(parName.find("L")!=string::npos) {
	L = atof(parValStr.data());
	pm.insert(pair< std::string, std::string >("L",parValStr));
      }
      // add polydispersity stuff //
    }
    curString.clear();
    parName.clear();
    parValStr.clear();
  }
  inFile.close();

  SemiflexibleGel<2> * gel;
  SemiflexibleGel<2>::DefNodeContainer nodes;
  PeriodicBox * box;
  GelOutput<2> output;

  if(kC < 0.0) {
    kC = kT*L_p;
  }

  if(retrieveGel) {
    if(kC > 0.0 && l_B > 0.0) {
      std::ostringstream tmpStr;
      tmpStr << setprecision(16) << kC;
      if(!adaptiveMeshing) pm.insert(pair< std::string, std::string>("bending modulus",tmpStr.str()));
      else pm.insert(pair< std::string, std::string>("angle stiffness",tmpStr.str()));
      // get nominal l_c and L from gel file name //
      int Lpos = gelFileName.find("L=") + 2;
      int l_Cpos = gelFileName.find("l_C");
      int dLpos = gelFileName.find("dL");
      int Wxpos = gelFileName.find("Wx");
      int kclpos = gelFileName.find("kcl");
      int nempos = gelFileName.find("S");
      int gelNumpos = gelFileName.find("gelnum");
      int endPos = gelFileName.find(".gelsave");
      std::string Lstr;
      Lstr.assign(gelFileName,Lpos,l_Cpos-1-Lpos);
      pm["L"] = Lstr;
      L = atof(Lstr.data());
      std::string l_Cstr;
      l_Cstr.assign(gelFileName,l_Cpos+4,dLpos-5-l_Cpos);
      tmpratio = L/atof(l_Cstr.data());
      std::ostringstream tm;
      tm << setprecision(16) << tmpratio;
      pm["L/l_c"] = tm.str();
      std::string dLstr;
      dLstr.assign(gelFileName,dLpos+3,Wxpos-4-dLpos);
      if(!adaptiveMeshing) {
        pm["dL"] = dLstr;
        dL = atof(dLstr.data());
      }
      else dL = -1.0;
      std::string kclStr;
      kclStr.assign(gelFileName,kclpos+4,nempos-5-kclpos);
      kcl = atof(kclStr.data());
      pm["crosslink stiffness"] = kclStr;
      std::string nemstr;
      nemstr.assign(gelFileName,nempos+2,gelNumpos-nempos-3);
      nematicOP = atof(nemstr.data());
      std::string GNstr;
      GNstr.assign(gelFileName,gelNumpos+7,endPos-gelNumpos-7);
      curGelNum = atoi(GNstr.data());
      gelFileName.insert(0,gelDirectory);
      lambda = (tmpratio/L)*pow(tmpratio/(L*l_B),1.0/3.0);
      std::ostringstream lambstr;
      lambstr << setprecision(16) << lambda;
      pm["lambda"] = lambstr.str();
      if(adaptiveMeshing) {
        double mu = kC/sqr(l_B);
        std::ostringstream mustream;
        mustream << setprecision(16) << mu;
	pm["bond stiffness"] = mustream.str();
      }

      if(!adaptiveMeshing) {
        gel = new SemiflexibleGel<2>(gelFileName,nodes,bondType,cutOffEnds,pm,0.0);
      }
      else {
        gel = new SemiflexibleGel<2>(gelFileName,nodes,bondType,cutOffEnds,minLength,pm);
      }
      box = gel->box();
      syssize = box->size();
      std::cout << "Retrieved and set up a gel with the following properties:" << std::endl;
      std::cout << "System size: " << syssize[0] << ", " << syssize[1] << std::endl;
      std::cout << "Bond type: " << bondType << std::endl;
      for(PMIter pmi=pm.begin(); pmi!=pm.end(); pmi++) {
	std::cout << pmi->first << ": " << pmi->second << std::endl;
      }
      std::ostringstream ss0;
      ss0 << setprecision(16) << syssize[0];
      std::ostringstream ss1;
      ss1 << setprecision(16) << syssize[1];
      pm["Wx"] = ss0.str();
      pm["Wy"] = ss1.str();

      if(relaxPrestress) {
	gel->removePrestress();
	std::cout << "Reset spring rest lengths/stiffnesses to relax prestress." << std::endl;
      }
    }
    else {
      std::cerr << "Error: input file must have either persistence length L_p or bending modulus kC." << std::endl;
      exit(1);
    }
  }

  else {
    if(nematicOP >= 1.0e-6) {
      pm.insert(pair< std::string, std::string >("nematic PDF param",nemPDFparam));
    }

    for(int dn=0;dn<2;dn++) {
      syssize[dn] *= L;
    }

    // get number of rods per filament from requirement of nodes between crosslinks, then set all other parameters //
    if(!adaptiveMeshing) {
      nNodesPerFilament = 1 + getFilSegs(tmpratio-1,nodesPerCL);
      dL = L/(nNodesPerFilament - 1);
      // Estimate kAngle = E*I/L = kT\xi_p/dL; kT=4.1pN-nm, \xi_p=10^4nm, dL~100nm
      //make kAngle 100 times larger to simulate the rotation diffusion

      if(kC > 0.0) {
        kAngle = kC/dL;
        std::ostringstream tmpStr;
        tmpStr << setprecision(16) << kAngle;
        pm.insert(pair< std::string, std::string>("angle stiffness",tmpStr.str()));
      }
      else {
        std::cerr << "Error: input file must have either persistence length L_p or bending modulus kC." << std::endl;
        exit(1);
      }
      if(l_B > 0.0) {
        kBond = kAngle/sqr(l_B);
        std::ostringstream tmpStr;
        tmpStr << setprecision(16) << kBond;
        pm.insert(pair< std::string, std::string>("bond stiffness",tmpStr.str()));
      }
      else {
        std::cerr << "Error: input file must have a value for the bending/stretching length l_B." << std::endl;
      }
    }
    else {
      dL = -1.0;
      std::ostringstream tmpStr;
      tmpStr << setprecision(16) << kC;
      pm.insert(pair< std::string, std::string>("angle stiffness",tmpStr.str()));
      double mu = kC/sqr(l_B);
      std::ostringstream tmpStr2;
      tmpStr2 << setprecision(16) << mu;
      pm.insert(pair< std::string, std::string>("bond stiffness",tmpStr2.str()));
    }

    lambda = (tmpratio/L)*pow(tmpratio/(L*l_B),1.0/3.0);
    std::ostringstream lambstr;
    lambstr << setprecision(16) << lambda;
    pm["lambda"] = lambstr.str();

    std::ostringstream tmpSx;
    tmpSx << setprecision(16) << syssize[0];
    pm.insert(pair< std::string, std::string >("Wx",tmpSx.str()));
    std::ostringstream tmpSy;
    tmpSy << setprecision(16) << syssize[1];
    pm.insert(pair< std::string, std::string >("Wy",tmpSy.str()));
    std::ostringstream tmpLl_c;
    tmpLl_c << setprecision(16) << tmpratio;
    pm.insert(pair< std::string, std::string >("L/l_c",tmpLl_c.str()));
    std::ostringstream tmpdL;
    tmpdL << setprecision(16) << dL;
    pm.insert(pair< std::string, std::string >("dL",tmpdL.str()));

    std::cout << "Constructing a gel with the following properties:" << std::endl;
    std::cout << "System size: " << syssize[0] << ", " << syssize[1] << std::endl;
    std::cout << "# nodes/filament: " << nNodesPerFilament << std::endl;
    std::cout << "Bond type: " << bondType << std::endl;
    for(PMIter pmi=pm.begin(); pmi!=pm.end(); pmi++) {
      std::cout << pmi->first << ": " << pmi->second << std::endl;
    }

    std::string fName = getGelFileName(gelDirectory,pm);
    curGelNum = getCurGelNum(fName);

    if(adaptiveMeshing) pm.insert(pair<std::string, std::string>("storage file name",fName));

    // make periodic box //
    box = new LeesEdwards(syssize[0],syssize[1],0.0);

    // create body //
    if(!adaptiveMeshing) {
      gel = new SemiflexibleGel<2>(nodes,box,filDens,nNodesPerFilament,dL,bondType,cutOffEnds,pm);
    }
    else {
      gel = new SemiflexibleGel<2>(nodes,box,filDens,L,bondType,cutOffEnds,minLength,pm);
    }
    //gel->addPinch(6.0,false,nodes,kBond,kAngle,visc,kT,dt,kcl);

    // write gel data to file //
    if(!adaptiveMeshing) {
      gel->storeGel(fName);
    }

    // now retrieve gel and confirm that nodes are at same positions //
//     SemiflexibleGel<2> * gel2;
//     SemiflexibleGel<2>::DefNodeContainer nodes2;
//     PeriodicBox * box2;
//     std::ostringstream tmpStr;
//     tmpStr << setprecision(16) << kC;
//     pm.insert(pair< std::string, std::string>("bending modulus",tmpStr.str()));
//     std::ostringstream kclStr;
//     kclStr << setprecision(16) << kcl;
//     pm["crosslink stiffness"] = kclStr.str();
//     gel2 = new SemiflexibleGel<2>(fName,nodes2,bondType,cutOffEnds,pm);
//     int nF = gel2->filaments().size();
//     for(int fi=0; fi<nF; fi++) {
//       SemiflexibleGel<2>::Filament * f1p = gel->filament(fi);
//       SemiflexibleGel<2>::Filament * f2p = gel2->filament(fi);
//       int nA2,nB2,nN2;
//       nA2 = f2p->angles.size();
//       nB2 = f2p->bonds.size();
//       nN2 = f2p->nodes.size();
//       int nA,nB,nN;
//       nA = f1p->angles.size();
//       nB = f1p->bonds.size();
//       nN = f1p->nodes.size();
//       if(nA!=nA2 || nB!=nB2 || nN!=nN2) {
// 	std::cout << "Error in gel storage/retrieval: filament " << fi << " was not stored or retrieved correctly." << std::endl;
//       }
//       else {
// 	SemiflexibleGel<2>::AngleContainer angs1;
// 	SemiflexibleGel<2>::AngleContainer angs2;
// 	angs1 = f1p->angles;
// 	angs2 = f2p->angles;
// 	for(int ai=0; ai<nA; ai++) {
// 	  if(angs1[ai]->stiffness() != angs2[ai]->stiffness()) {
// 	    std::cout << "Error in gel storage/retrieval: angle spring " << ai << " on filament " << fi << "." << std::endl;
// 	    std::cout << "Original stiffness = " << angs1[ai]->stiffness() << "; retrieved stiffness = " << angs2[ai]->stiffness() << "." << std::endl;
// 	  }
// 	}
// 	for(int bi=0; bi<nB; bi++) {
// 	  if(f1p->bonds[bi]->stiffness() != f2p->bonds[bi]->stiffness()) {
// 	    std::cout << "Error in gel storage/retrieval: spring " << bi << " on filament " << fi << "." << std::endl;
// 	    std::cout << "Original stiffness = " << f1p->bonds[bi]->stiffness() << "; retrieved stiffness = " << f2p->bonds[bi]->stiffness() << "." << std::endl;
// 	    std::cout << "Stiffness disparity = " << abs(f1p->bonds[bi]->stiffness()-f2p->bonds[bi]->stiffness()) << std::endl;
// 	  }
// 	}
// 	for(int ni=0; ni<nN; ni++) {
// 	  if(f1p->nodes[ni]->point()[0] != f2p->nodes[ni]->point()[0] || f1p->nodes[ni]->point()[1] != f2p->nodes[ni]->point()[1]) {
// 	    std::cout << "Error in gel storage/retrieval: node " << ni << " on filament " << fi << " has inconsistent displacement value." << std::endl;
// 	  }
// 	  if(f1p->nodes[ni]->position()[0] != f2p->nodes[ni]->position()[0] || f1p->nodes[ni]->position()[1] != f2p->nodes[ni]->position()[1]) {
// 	    std::cout << "Error in gel storage/retrieval: node " << ni << " on filament " << fi << " has inconsistent position value." << std::endl;
// 	  }
// 	}
//       }
//     }
    fName.clear();

    if(relaxPrestress) {
      gel->removePrestress();
      std::cout << "Reset spring rest lengths/stiffnesses to relax prestress." << std::endl;
    }

    char clinkdistfile[128];
    sprintf(clinkdistfile,"Run%d/CrosslinkSepDistro-L=%f-l_C=%f-dL=%f-S=%f-gelnum=%d.dat",runNum,L,L/tmpratio,dL,nematicOP,curGelNum);
    fName.assign(clinkdistfile);
    output.printCrosslinkData(gel,fName);

    fName.clear();
    char fillendistfile[128];
    sprintf(fillendistfile,"Run%d/FilLengthDistro-L=%f-l_C=%f-dL=%f-S=%f-gelnum=%d.dat",runNum,L,L/tmpratio,dL,nematicOP,curGelNum);
    fName.assign(fillendistfile);
    output.printFilLengthData(gel,fName);

    fName.clear();
    char nematicdistfile[128];
    sprintf(nematicdistfile,"Run%d/NematicDistro-L=%f-l_C=%f-dL=%f-S=%f-gelnum=%d.dat",runNum,L,L/tmpratio,dL,nematicOP,curGelNum);
    fName.assign(nematicdistfile);
    output.printNematicData(gel,fName);

    fName.clear();
  }

  // check to make sure filaments aren't multiply crosslinked //
  // gel->checkCrosslinks();

  if(shearXtest || shearYtest || expXYtest || expXtest || expYtest) {
    actuall_c = gel->getMeanCLsep();
    actualnemOP = gel->getNematicOP();
    double actuallamb = actuall_c*pow(actuall_c/l_B,1.0/3.0);

    char nemFileName[256];

    sprintf(nemFileName,"Run%d/nematicgel-L=%f-l_C=%f-dL=%f-S=%f-Wx=%f-Wy=%f-gelnum=%d",runNum,L,L/tmpratio,dL,nematicOP,syssize[0],syssize[1],curGelNum);

    //first, let system relax with no shear, stretch, etc., and store resultant positions in map.  then do various tests, returning after each to the original relaxed state//
    Model::NodeContainer modelnodes;
    modelnodes.reserve( nodes.size() );
    for(SemiflexibleGel<2>::DefNodeIterator n=nodes.begin(); n!=nodes.end(); n++) {
      modelnodes.push_back( *n );
    }
    Model model(modelnodes);
    model.pushBackBody( gel );

    int m=7;
    double factr=1.0e+1;
    double pgtol=1.0e-6;
    double gtol = 1.0e-5;
    int iprint = 1;
    int maxiter = 1500000;
    Solver * solver;
    if(solverType.find("LBFGSB")!=string::npos) {
      ifstream lbfgsbinp("lbfgsb.inp");
      lbfgsbinp >> iprint >> factr >> pgtol >> m ;
      if(verbose) {
	std::cout << "Input iprint: " << iprint << std::endl
		  << "Input factr: " << factr << std::endl
		  << "Input pgtol: " << pgtol << std::endl
		  << "Input m: " << m << std::endl;
      }
      solver = new Lbfgsb(model.dof(),m,factr,pgtol,iprint,maxiter);
    }
    //else {
    //  ifstream lbfgsinp("lbfgs.inp");
    //  lbfgsinp >> iprint >> gtol >> m ;
    //  if(verbose) {
    //	std::cout << "Input iprint: " << iprint << std::endl
    //		  << "Input gtol: " << gtol << std::endl
    //		  << "Input m: " << m << std::endl;
    //  }
    //  solver = new Lbfgs(m,gtol,iprint,maxiter);
    // }
    //    Lbfgsb solver(model.dof(), m, factr, pgtol, iprint, maxiter );
    box->setShear(0.0);
    std::cout << "Relaxing gel with no shear/stretching." << std::endl;
    solver->solve(&model);

    InitPositionMap ipmap;
    for(SemiflexibleGel<2>::DefNodeIterator n=nodes.begin(); n!=nodes.end(); n++) {
      ipmap[*n] = (*n)->point();
    }

    if(zeroReturn) {
      box->setShear(.0025);
      double oldenergy = gel->energy();
      std::cout << "Current energy with no shear = " << oldenergy << "; shearing gel slightly and relaxing, then setting shear to 0 and relaxing again." << std::endl;
      solver->solve(&model);
      box->setShear(0.0);
      solver->solve(&model);
      std::cout << "New energy with no shear = " << gel->energy() << "." << std::endl;
      if(gel->energy() <= oldenergy) {
        for(SemiflexibleGel<2>::DefNodeIterator n=nodes.begin(); n!=nodes.end(); n++) {
          ipmap[*n] = (*n)->point();
        }
      }
    }

    std::string fname2print;

    std::string nematicFileName(nemFileName);

//     char solverDataFN[256];
//     sprintf(solverDataFN,"Run%d/solverData",runNum);
//     std::string solverDataFileName(solverDataFN);
    std::ostringstream paramstring;
    paramstring << "Parameters: "
		<< "L/l_C = " << L/actuall_c
		<< ", L = " << L
		<< ", S = " << actualnemOP
		<< ", l_B = " << l_B
		<< ", Wx = " << syssize[0]
		<< ", Wy = " << syssize[1];

    // rotate system and make sure energy is the same //
//     if(abs(syssize[0]-syssize[1]) < 1.0e-6) {
//       double olden = gel->energy();
//       for(SemiflexibleGel<2>::DefNodeIterator n=nodes.begin(); n!=nodes.end(); n++) {
// 	tvmet::Vector<double,2> oldpos = (*n)->point();
// 	tvmet::Vector<double,2> newpos;
// 	newpos[0] = -oldpos[1];
// 	newpos[1] = oldpos[0];
// 	(*n)->setPoint(newpos);
//       }
//       double newen = gel->energy();
//       solver.solve(&model);
//       std::cout << "Gel energy before rotation = " << olden << "; gel energy after rotation = " << newen << "; gel energy after new minimization = " << gel->energy() << "." << std::endl;
//     }

    if(shearXtest) {
      std::cout << std::endl << "Shearing gel in X direction." << std::endl;
      std::string shearXFileName = nematicFileName + "-ShearX.dat";
      std::string shearXAffineFileName = nematicFileName + "-affine-ShearX.dat";
      for(InitPositionMap::iterator ipit=ipmap.begin(); ipit!=ipmap.end(); ipit++) {
	(ipit->first)->setPoint(ipit->second);
      }
      output.printParamHeader(shearXFileName,paramstring.str());
      output.printParamHeader(shearXAffineFileName,paramstring.str());
      std::string fieldString = "ShearX\tE_tot\tE_cl\tE_bend\tE_strc";
      output.printFieldLabels(shearXFileName,fieldString);
      output.printFieldLabels(shearXAffineFileName,fieldString);
      nShrSteps = (int)(abs(shrEnd)/shrStep);
      for(int sx=0; sx<=nShrSteps; sx++) {
	std::cout << "Shear X = " << shrStep*sx << std::endl;
	box->setShearX(shrStep*sx);
	guessAffineShearX(gel,shrStep*sx);
	gel->compute(true,true,false);
	output.printEnergies(gel,shearXAffineFileName,shrStep*sx);
	solver->solve(&model);
	gel->compute(true,true,false);
	//gel->printBigBends();
	output.printEnergies(gel,shearXFileName,shrStep*sx);

	//output.printSolverData(gel,solver,shearXSolverFN);
	if(writeStates) {
	  fname2print.clear();
	  char shearXname[128];
	  sprintf(shearXname,"Run%d/shearX=%f",runNum,shrStep*sx);
	  fname2print.assign(shearXname);
	  gel->print(fname2print);
	}

	char affXname[128];
	sprintf(affXname,"Run%d/afftest-shearX=%f.dat",runNum,shrStep*sx);
	std::string affXFN(affXname);
	gel->storeGel(affXFN);

      }
    }

    if(shearYtest) {
      std::cout << std::endl << "Shearing gel in Y direction." << std::endl;
      for(InitPositionMap::iterator ipit=ipmap.begin(); ipit!=ipmap.end(); ipit++) {
	(ipit->first)->setPoint(ipit->second);
      }

      box->setShear(0.0);

      std::string shearYFileName = nematicFileName + "-ShearY.dat";
      std::string shearYAffineFileName = nematicFileName + "-affine-ShearY.dat";
      output.printParamHeader(shearYFileName,paramstring.str());
      output.printParamHeader(shearYAffineFileName,paramstring.str());
      std::string fieldString = "ShearY\tE_tot\tE_cl\tE_bend\tE_strc";
      output.printFieldLabels(shearYFileName,fieldString);
      output.printFieldLabels(shearYAffineFileName,fieldString);
      nShrSteps = (int)(abs(shrEnd)/shrStep);
      for(int sy=0; sy<=nShrSteps; sy++) {
	std::cout << "Shear Y = " << shrStep*sy << std::endl;
	box->setShearY(shrStep*sy);
	guessAffineShearY(gel,shrStep*sy);
	gel->compute(true,true,false);
	output.printEnergies(gel,shearYAffineFileName,shrStep*sy);
	solver->solve(&model);
	gel->compute(true,true,false);
	output.printEnergies(gel,shearYFileName,shrStep*sy);
	//output.printSolverData(gel,solver,shearYSolverFN);
	if(writeStates) {
	  fname2print.clear();
	  char shearYname[128];
	  sprintf(shearYname,"Run%d/shearY=%f",runNum,shrStep*sy);
	  fname2print.assign(shearYname);
	  gel->print(fname2print);
	}

        char affYname[128];
	sprintf(affYname,"Run%d/afftest-shearY=%f.dat",runNum,shrStep*sy);
        std::string affYFN(affYname);
        gel->storeGel(affYFN);
      }
    }

    if(expXYtest) {
      std::cout << "Expanding gel uniformly." << std::endl;
      for(InitPositionMap::iterator ipit=ipmap.begin(); ipit!=ipmap.end(); ipit++) {
	(ipit->first)->setPoint(ipit->second);
      }

      box->setShear(0.0);

      std::string expXYFileName = nematicFileName + "-ExpXY.dat";
      std::string expXYAffineFileName = nematicFileName + "-affine-ExpXY.dat";
      output.printParamHeader(expXYFileName,paramstring.str());
      output.printParamHeader(expXYAffineFileName,paramstring.str());
      std::string fieldString = "ExpXY\tE_tot\tE_cl\tE_bend\tE_strc";
      output.printFieldLabels(expXYFileName,fieldString);
      output.printFieldLabels(expXYAffineFileName,fieldString);

      expandStep = (expandEnd-1.0)/nExpandSteps;
      for(int ne=0; ne<=nExpandSteps; ne++) {
	double strtchFactor = 1.0+(expandStep*ne);
	double strtchPct = 100.0*(strtchFactor-1.0);
	std::cout << "Isotropic expansion pct. = " << strtchPct << std::endl;
	box->setSize(syssize);
	box->stretchXY(strtchFactor);
	guessExpXY(gel,expandStep*ne);
	gel->compute(true,true,false);
	output.printEnergies(gel,expXYAffineFileName,strtchFactor-1.0);
	solver->solve(&model);
	gel->compute(true,true,false);
	output.printEnergies(gel,expXYFileName,strtchFactor-1.0);
	//output.printSolverData(gel,solver,expXYSolverFN);
	if(writeStates) {
	  fname2print.clear();
	  char expXYname[128];
	  sprintf(expXYname,"Run%d/expXY=%f",runNum,strtchFactor);
	  fname2print.assign(expXYname);
	  gel->print(fname2print);
	}

	char affExpXYname[128];
	sprintf(affExpXYname,"Run%d/afftest-expXY=%f.dat",runNum,strtchFactor);
        std::string affExpXYFN(affExpXYname);
        gel->storeGel(affExpXYFN);
      }
    }

    if(expXtest) {
      std::cout << "Stretching gel in X direction." << std::endl;
      for(InitPositionMap::iterator ipit=ipmap.begin(); ipit!=ipmap.end(); ipit++) {
	(ipit->first)->setPoint(ipit->second);
      }

      box->setShear(0.0);
      box->setSize(syssize);

      std::string expXFileName = nematicFileName + "-ExpX.dat";
      std::string expXAffineFileName = nematicFileName + "-affine-ExpX.dat";
      output.printParamHeader(expXFileName,paramstring.str());
      output.printParamHeader(expXAffineFileName,paramstring.str());
      std::string fieldString = "StrX\tE_tot\tE_cl\tE_bend\tE_strc";
      output.printFieldLabels(expXFileName,fieldString);
      output.printFieldLabels(expXAffineFileName,fieldString);

      stretchStep = (stretchEnd-1.0)/nStretchSteps;
      for(int nsx=0; nsx<=nStretchSteps; nsx++) {
	double strtchFactor = 1.0+(stretchStep*nsx);
	double strtchPct = 100.0*(strtchFactor-1.0);
	std::cout << "X expansion pct. = " << strtchPct << std::endl;
	box->setSize(syssize);
	box->stretchX(strtchFactor);
	guessExpX(gel,stretchStep*nsx);
	gel->compute(true,true,false);
	output.printEnergies(gel,expXAffineFileName,strtchFactor-1.0);
	solver->solve(&model);
	gel->compute(true,true,false);
	output.printEnergies(gel,expXFileName,strtchFactor-1.0);
	//output.printSolverData(gel,solver,expXSolverFN);
	if(writeStates) {
	  fname2print.clear();
	  char expXname[128];
	  sprintf(expXname,"Run%d/expX=%f",runNum,strtchFactor);
	  fname2print.assign(expXname);
	  gel->print(fname2print);
	}

	char affExpXname[128];
	sprintf(affExpXname,"Run%d/afftest-expX=%f.dat",runNum,strtchFactor);
        std::string affExpXFN(affExpXname);
        gel->storeGel(affExpXFN);
      }
    }

    if(expYtest) {
      std::cout << "Stretching gel in Y direction." << std::endl;
      for(InitPositionMap::iterator ipit=ipmap.begin(); ipit!=ipmap.end(); ipit++) {
	(ipit->first)->setPoint(ipit->second);
      }

      box->setShear(0.0);
      box->setSize(syssize);

      std::string expYFileName = nematicFileName + "-ExpY.dat";
      std::string expYAffineFileName = nematicFileName + "-affine-ExpY.dat";
      output.printParamHeader(expYFileName,paramstring.str());
      output.printParamHeader(expYAffineFileName,paramstring.str());
      std::string fieldString = "StrY\tE_tot\tE_cl\tE_bend\tE_strc";
      output.printFieldLabels(expYFileName,fieldString);
      output.printFieldLabels(expYAffineFileName,fieldString);

      stretchStep = (stretchEnd-1.0)/nStretchSteps;
      for(int nsy=0; nsy<=nStretchSteps; nsy++) {
	double strtchFactor = 1.0+(stretchStep*nsy);
	double strtchPct = 100.0*(strtchFactor-1.0);
	std::cout << "Y expansion pct. = " << strtchPct << std::endl;
	box->setSize(syssize);
	box->stretchY(strtchFactor);
	guessExpY(gel,stretchStep*nsy);
	gel->compute(true,true,false);
	output.printEnergies(gel,expYAffineFileName,strtchFactor-1.0);
	solver->solve(&model);
	gel->compute(true,true,false);
	output.printEnergies(gel,expYFileName,strtchFactor-1.0);
	//output.printSolverData(gel,solver,expYSolverFN);
	if(writeStates) {
	  fname2print.clear();
	  char expYname[128];
	  sprintf(expYname,"Run%d/expY=%f",runNum,strtchFactor);
	  fname2print.assign(expYname);
	  gel->print(fname2print);
	}

	char affExpYname[128];
	sprintf(affExpYname,"Run%d/afftest-expY=%f.dat",runNum,strtchFactor);
        std::string affExpYFN(affExpYname);
        gel->storeGel(affExpYFN);
      }
    }

    std::cout << "Finished testing gel." << std::endl;

  }
}


text:
require 'spec_helper'

describe MachinesController, machine_spec: true, story_113: true do
  include_context 'signed_in_as_admin'

  let!(:machine) { create(:machine) }
  let!(:scheduled_imprint) { create(:print, scheduled_at: Time.now, estimated_time: 1, machine: machine ) }

  describe 'POST #create' do
    context 'with valid input' do
      it 'redirects to #show' do
        post :create, machine: attributes_for(:machine)
        expect(response).to redirect_to(machines_path)
      end

    end

    context 'with invalid input' do
      it 'renders #new' do
        post :create, machine: attributes_for(:blank_machine, name: nil)
        expect(response).to render_template('new')
      end
    end
  end

  describe 'PUT #update' do
    context 'with valid input' do
      it 'redirects to #show' do
        put :update, id: machine.id, machine: attributes_for(:machine, name: 'New Name')
        expect(response).to redirect_to(machines_path)
      end
    end

    context 'with invalid input' do
      it 'renders #edit' do
        put :update, id: machine.id, machine: attributes_for(:machine, name: nil)
        expect(response).to render_template('edit')
      end
    end

  end

  describe 'GET #scheduled' do
    it 'assigns @machine', scheduled: true do
      get :scheduled, { id: machine.id, format: :json }
      expect(assigns[:machine]).to eq machine
    end
  end

end


text:
<?php

namespace Drupal\field_group\Routing;

use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscriber for Field group routes.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * The entity type manager
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $manager;

  /**
   * Constructs a RouteSubscriber object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $manager
   *   The entity type manager.
   */
  public function __construct(EntityManagerInterface $manager) {
    $this->manager = $manager;
  }

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    // Create fieldgroup routes for every entity.
    foreach ($this->manager->getDefinitions() as $entity_type_id => $entity_type) {
      $defaults = array();
      if ($route_name = $entity_type->get('field_ui_base_route')) {
        // Try to get the route from the current collection.
        if (!$entity_route = $collection->get($route_name)) {
          continue;
        }
        $path = $entity_route->getPath();

        $options = $entity_route->getOptions();

        // Special parameter used to easily recognize all Field UI routes.
        $options['_field_ui'] = TRUE;

        if (($bundle_entity_type = $entity_type->getBundleEntityType()) && $bundle_entity_type !== 'bundle') {
          $options['parameters'][$entity_type->getBundleEntityType()] = array(
            'type' => 'entity:' . $entity_type->getBundleEntityType(),
          );
        }

        $options['parameters']['field_group'] = array(
          'type' => 'field_group',
          'entity_type' => $entity_type->getBundleEntityType(),
        );

        $defaults_delete = [
          'entity_type_id' => $entity_type_id,
          '_form' => '\Drupal\field_group\Form\FieldGroupDeleteForm',
        ];
        $defaults_add = [
          'entity_type_id' => $entity_type_id,
          '_form' => '\Drupal\field_group\Form\FieldGroupAddForm',
          '_title' => 'Add group',
        ];

        // If the entity type has no bundles and it doesn't use {bundle} in its
        // admin path, use the entity type.
        if (strpos($path, '{bundle}') === FALSE) {
          $defaults_add['bundle'] = !$entity_type->hasKey('bundle') ? $entity_type_id : '';
          $defaults_delete['bundle'] = $defaults_add['bundle'];
        }

        // Routes to delete field groups.
        $route = new Route(
          "$path/form-display/{field_group_name}/delete",
          ['context' => 'form'] + $defaults_delete,
          array('_permission' => 'administer ' . $entity_type_id . ' form display'),
          $options
        );
        $collection->add("field_ui.field_group_delete_$entity_type_id.form_display", $route);

        $route = new Route(
          "$path/form-display/{form_mode_name}/{field_group_name}/delete",
          ['context' => 'form'] + $defaults_delete,
          array('_permission' => 'administer ' . $entity_type_id . ' form display'),
          $options
        );
        $collection->add("field_ui.field_group_delete_$entity_type_id.form_display.form_mode", $route);

        $route = new Route(
          "$path/display/{field_group_name}/delete",
          ['context' => 'view'] + $defaults_delete,
          array('_permission' => 'administer ' . $entity_type_id . ' display'),
          $options
        );
        $collection->add("field_ui.field_group_delete_$entity_type_id.display", $route);

        $route = new Route(
          "$path/display/{view_mode_name}/{field_group_name}/delete",
          ['context' => 'view'] + $defaults_delete,
          array('_permission' => 'administer ' . $entity_type_id . ' display'),
          $options
        );
        $collection->add("field_ui.field_group_delete_$entity_type_id.display.view_mode", $route);

        // Routes to add field groups.
        $route = new Route(
          "$path/form-display/add-group",
          ['context' => 'form'] + $defaults_add,
          array('_permission' => 'administer ' . $entity_type_id . ' form display'),
          $options
        );
        $collection->add("field_ui.field_group_add_$entity_type_id.form_display", $route);

        $route = new Route(
          "$path/form-display/{form_mode_name}/add-group",
          ['context' => 'form'] + $defaults_add,
          array('_permission' => 'administer ' . $entity_type_id . ' form display'),
          $options
        );
        $collection->add("field_ui.field_group_add_$entity_type_id.form_display.form_mode", $route);

        $route = new Route(
          "$path/display/add-group",
          ['context' => 'view'] + $defaults_add,
          array('_permission' => 'administer ' . $entity_type_id . ' display'),
          $options
        );
        $collection->add("field_ui.field_group_add_$entity_type_id.display", $route);

        $route = new Route(
          "$path/display/{view_mode_name}/add-group",
          ['context' => 'view'] + $defaults_add,
          array('_permission' => 'administer ' . $entity_type_id . ' display'),
          $options
        );
        $collection->add("field_ui.field_group_add_$entity_type_id.display.view_mode", $route);

      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    //$events = parent::getSubscribedEvents();
    // Come after field_ui, config_translation.
    $events[RoutingEvents::ALTER] = array('onAlterRoutes', -210);
    return $events;
  }

}


text:
package org.jetbrains.idea.svn.commandLine;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.api.Depth;
import org.jetbrains.idea.svn.api.ProgressTracker;
import org.jetbrains.idea.svn.properties.PropertyValue;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc2.SvnTarget;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author Konstantin Kolosovsky.
 */
// TODO: Probably make command immutable and use CommandBuilder for updates.
public class Command {

  @NotNull private final List<String> myParameters = ContainerUtil.newArrayList();
  @NotNull private final List<String> myOriginalParameters = ContainerUtil.newArrayList();
  @NotNull private final SvnCommandName myName;

  private File workingDirectory;
  @Nullable private File myConfigDir;
  @Nullable private LineCommandListener myResultBuilder;
  @Nullable private volatile SVNURL myRepositoryUrl;
  @NotNull private SvnTarget myTarget;
  @Nullable private Collection<File> myTargets;
  @Nullable private PropertyValue myPropertyValue;

  @Nullable private ProgressTracker myCanceller;

  public Command(@NotNull SvnCommandName name) {
    myName = name;
  }

  public void put(@Nullable Depth depth) {
    CommandUtil.put(myParameters, depth, false);
  }

  public void put(@NotNull SvnTarget target) {
    CommandUtil.put(myParameters, target);
  }

  public void put(@Nullable SVNRevision revision) {
    CommandUtil.put(myParameters, revision);
  }

  public void put(@NotNull String parameter, boolean condition) {
    CommandUtil.put(myParameters, condition, parameter);
  }

  public void put(@NonNls @NotNull String... parameters) {
    put(Arrays.asList(parameters));
  }

  public void put(@NotNull List<String> parameters) {
    myParameters.addAll(parameters);
  }

  public void putIfNotPresent(@NotNull String parameter) {
    if (!myParameters.contains(parameter)) {
      myParameters.add(parameter);
    }
  }

  @Nullable
  public ProgressTracker getCanceller() {
    return myCanceller;
  }

  public void setCanceller(@Nullable ProgressTracker canceller) {
    myCanceller = canceller;
  }

  @Nullable
  public File getConfigDir() {
    return myConfigDir;
  }

  public File getWorkingDirectory() {
    return workingDirectory;
  }

  @Nullable
  public LineCommandListener getResultBuilder() {
    return myResultBuilder;
  }

  @Nullable
  public SVNURL getRepositoryUrl() {
    return myRepositoryUrl;
  }

  @NotNull
  public SVNURL requireRepositoryUrl() {
    SVNURL result = getRepositoryUrl();
    assert result != null;

    return result;
  }

  @NotNull
  public SvnTarget getTarget() {
    return myTarget;
  }

  @Nullable
  public List<String> getTargetsPaths() {
    return ContainerUtil.isEmpty(myTargets) ? null : ContainerUtil.map(myTargets, new Function<File, String>() {
      @Override
      public String fun(File file) {
        return CommandUtil.format(file.getAbsolutePath(), null);
      }
    });
  }

  @Nullable
  public PropertyValue getPropertyValue() {
    return myPropertyValue;
  }

  @NotNull
  public SvnCommandName getName() {
    return myName;
  }

  public void setWorkingDirectory(File workingDirectory) {
    this.workingDirectory = workingDirectory;
  }

  public void setConfigDir(@Nullable File configDir) {
    this.myConfigDir = configDir;
  }

  public void setResultBuilder(@Nullable LineCommandListener resultBuilder) {
    myResultBuilder = resultBuilder;
  }

  public void setRepositoryUrl(@Nullable SVNURL repositoryUrl) {
    myRepositoryUrl = repositoryUrl;
  }

  public void setTarget(@NotNull SvnTarget target) {
    myTarget = target;
  }

  public void setTargets(@Nullable Collection<File> targets) {
    myTargets = targets;
  }

  public void setPropertyValue(@Nullable PropertyValue propertyValue) {
    myPropertyValue = propertyValue;
  }

  // TODO: used only to ensure authentication info is not logged to file. Remove when command execution model is refactored
  // TODO: - so we could determine if parameter should be logged by the parameter itself.
  public void saveOriginalParameters() {
    myOriginalParameters.clear();
    myOriginalParameters.addAll(myParameters);
  }

  @NotNull
  public List<String> getParameters() {
    return ContainerUtil.newArrayList(myParameters);
  }

  public String getText() {
    List<String> data = new ArrayList<>();

    if (myConfigDir != null) {
      data.add("--config-dir");
      data.add(myConfigDir.getPath());
    }
    data.add(myName.getName());
    data.addAll(myOriginalParameters);

    List<String> targetsPaths = getTargetsPaths();
    if (!ContainerUtil.isEmpty(targetsPaths)) {
      data.addAll(targetsPaths);
    }

    return StringUtil.join(data, " ");
  }

  public boolean isLocalInfo() {
    return is(SvnCommandName.info) && hasLocalTarget() && !myParameters.contains("--revision");
  }

  public boolean isLocalStatus() {
    return is(SvnCommandName.st) && hasLocalTarget() && !myParameters.contains("-u");
  }

  public boolean isLocalProperty() {
    boolean isPropertyCommand =
      is(SvnCommandName.proplist) || is(SvnCommandName.propget) || is(SvnCommandName.propset) || is(SvnCommandName.propdel);

    return isPropertyCommand && hasLocalTarget() && isLocal(getRevision());
  }

  public boolean isLocalCat() {
    return is(SvnCommandName.cat) && hasLocalTarget() && isLocal(getRevision());
  }

  @Nullable
  private SVNRevision getRevision() {
    int index = myParameters.indexOf("--revision");

    return index >= 0 && index + 1 < myParameters.size() ? SVNRevision.parse(myParameters.get(index + 1)) : null;
  }

  public boolean is(@NotNull SvnCommandName name) {
    return name.equals(myName);
  }

  private boolean hasLocalTarget() {
    return myTarget.isFile() && isLocal(myTarget.getPegRevision());
  }

  private static boolean isLocal(@Nullable SVNRevision revision) {
    return revision == null ||
           SVNRevision.UNDEFINED.equals(revision) ||
           SVNRevision.BASE.equals(revision) ||
           SVNRevision.WORKING.equals(revision);
  }
}