text:
DEFINE_int32(filtered_re2_min_atom_len,
             3,
             "Strings less than this length are not stored as atoms");

namespace re2 {

PrefilterTree::PrefilterTree()
    : compiled_(false) {
}

PrefilterTree::~PrefilterTree() {
  for (size_t i = 0; i < prefilter_vec_.size(); i++)
    delete prefilter_vec_[i];

  for (size_t i = 0; i < entries_.size(); i++)
    delete entries_[i].parents;
}

// Functions used for adding and Compiling prefilters to the
// PrefilterTree.
static bool KeepPart(Prefilter* prefilter, int level) {
  if (prefilter == NULL)
    return false;

  switch (prefilter->op()) {
    default:
      LOG(DFATAL) << "Unexpected op in KeepPart: "
                  << prefilter->op();
      return false;

    case Prefilter::ALL:
      return false;

    case Prefilter::ATOM:
      return prefilter->atom().size() >=
          static_cast<size_t>(FLAGS_filtered_re2_min_atom_len);

    case Prefilter::AND: {
      int j = 0;
      vector<Prefilter*>* subs = prefilter->subs();
      for (size_t i = 0; i < subs->size(); i++)
        if (KeepPart((*subs)[i], level + 1))
          (*subs)[j++] = (*subs)[i];
        else
          delete (*subs)[i];

      subs->resize(j);
      return j > 0;
    }

    case Prefilter::OR:
      for (size_t i = 0; i < prefilter->subs()->size(); i++)
        if (!KeepPart((*prefilter->subs())[i], level + 1))
          return false;
      return true;
  }
}

void PrefilterTree::Add(Prefilter *f) {
  if (compiled_) {
    LOG(DFATAL) << "Add after Compile.";
    return;
  }
  if (f != NULL && !KeepPart(f, 0)) {
    delete f;
    f = NULL;
  }

  prefilter_vec_.push_back(f);
}

void PrefilterTree::Compile(vector<string>* atom_vec) {
  if (compiled_) {
    LOG(DFATAL) << "Compile after Compile.";
    return;
  }

  // We do this check to support some legacy uses of
  // PrefilterTree that call Compile before adding any regexps,
  // and expect Compile not to have effect.
  if (prefilter_vec_.empty())
    return;

  compiled_ = true;

  AssignUniqueIds(atom_vec);

  // Identify nodes that are too common among prefilters and are
  // triggering too many parents. Then get rid of them if possible.
  // Note that getting rid of a prefilter node simply means they are
  // no longer necessary for their parent to trigger; that is, we do
  // not miss out on any regexps triggering by getting rid of a
  // prefilter node.
  for (size_t i = 0; i < entries_.size(); i++) {
    StdIntMap* parents = entries_[i].parents;
    if (parents->size() > 8) {
      // This one triggers too many things. If all the parents are AND
      // nodes and have other things guarding them, then get rid of
      // this trigger. TODO(vsri): Adjust the threshold appropriately,
      // make it a function of total number of nodes?
      bool have_other_guard = true;
      for (StdIntMap::iterator it = parents->begin();
           it != parents->end(); ++it) {
        have_other_guard = have_other_guard &&
            (entries_[it->first].propagate_up_at_count > 1);
      }

      if (have_other_guard) {
        for (StdIntMap::iterator it = parents->begin();
             it != parents->end(); ++it)
          entries_[it->first].propagate_up_at_count -= 1;

        parents->clear();  // Forget the parents
      }
    }
  }

  PrintDebugInfo();
}

Prefilter* PrefilterTree::CanonicalNode(Prefilter* node) {
  string node_string = NodeString(node);
  map<string, Prefilter*>::iterator iter = node_map_.find(node_string);
  if (iter == node_map_.end())
    return NULL;
  return (*iter).second;
}

static string Itoa(int n) {
  char buf[100];
  snprintf(buf, sizeof buf, "%d", n);
  return string(buf);
}

string PrefilterTree::NodeString(Prefilter* node) const {
  // Adding the operation disambiguates AND/OR/atom nodes.
  string s = Itoa(node->op()) + ":";
  if (node->op() == Prefilter::ATOM) {
    s += node->atom();
  } else {
    for (size_t i = 0; i < node->subs()->size(); i++) {
      if (i > 0)
        s += ',';
      s += Itoa((*node->subs())[i]->unique_id());
    }
  }
  return s;
}

void PrefilterTree::AssignUniqueIds(vector<string>* atom_vec) {
  atom_vec->clear();

  // Build vector of all filter nodes, sorted topologically
  // from top to bottom in v.
  vector<Prefilter*> v;

  // Add the top level nodes of each regexp prefilter.
  for (size_t i = 0; i < prefilter_vec_.size(); i++) {
    Prefilter* f = prefilter_vec_[i];
    if (f == NULL)
      unfiltered_.push_back(i);

    // We push NULL also on to v, so that we maintain the
    // mapping of index==regexpid for level=0 prefilter nodes.
    v.push_back(f);
  }

  // Now add all the descendant nodes.
  for (size_t i = 0; i < v.size(); i++) {
    Prefilter* f = v[i];
    if (f == NULL)
      continue;
    if (f->op() == Prefilter::AND || f->op() == Prefilter::OR) {
      const vector<Prefilter*>& subs = *f->subs();
      for (size_t j = 0; j < subs.size(); j++)
        v.push_back(subs[j]);
    }
  }

  // Identify unique nodes.
  int unique_id = 0;
  for (int i = v.size() - 1; i >= 0; i--) {
    Prefilter *node = v[i];
    if (node == NULL)
      continue;
    node->set_unique_id(-1);
    Prefilter* canonical = CanonicalNode(node);
    if (canonical == NULL) {
      // Any further nodes that have the same node string
      // will find this node as the canonical node.
      node_map_[NodeString(node)] = node;
      if (node->op() == Prefilter::ATOM) {
        atom_vec->push_back(node->atom());
        atom_index_to_id_.push_back(unique_id);
      }
      node->set_unique_id(unique_id++);
    } else {
      node->set_unique_id(canonical->unique_id());
    }
  }
  entries_.resize(node_map_.size());

  // Create parent StdIntMap for the entries.
  for (int i = v.size()  - 1; i >= 0; i--) {
    Prefilter* prefilter = v[i];
    if (prefilter == NULL)
      continue;

    if (CanonicalNode(prefilter) != prefilter)
      continue;

    Entry* entry = &entries_[prefilter->unique_id()];
    entry->parents = new StdIntMap();
  }

  // Fill the entries.
  for (int i = v.size()  - 1; i >= 0; i--) {
    Prefilter* prefilter = v[i];
    if (prefilter == NULL)
      continue;

    if (CanonicalNode(prefilter) != prefilter)
      continue;

    Entry* entry = &entries_[prefilter->unique_id()];

    switch (prefilter->op()) {
      default:
      case Prefilter::ALL:
        LOG(DFATAL) << "Unexpected op: " << prefilter->op();
        return;

      case Prefilter::ATOM:
        entry->propagate_up_at_count = 1;
        break;

      case Prefilter::OR:
      case Prefilter::AND: {
        set<int> uniq_child;
        for (size_t j = 0; j < prefilter->subs()->size(); j++) {
          Prefilter* child = (*prefilter->subs())[j];
          Prefilter* canonical = CanonicalNode(child);
          if (canonical == NULL) {
            LOG(DFATAL) << "Null canonical node";
            return;
          }
          int child_id = canonical->unique_id();
          uniq_child.insert(child_id);
          // To the child, we want to add to parent indices.
          Entry* child_entry = &entries_[child_id];
          if (child_entry->parents->find(prefilter->unique_id()) ==
              child_entry->parents->end()) {
            (*child_entry->parents)[prefilter->unique_id()] = 1;
          }
        }
        entry->propagate_up_at_count =
            prefilter->op() == Prefilter::AND ? uniq_child.size() : 1;

        break;
      }
    }
  }

  // For top level nodes, populate regexp id.
  for (size_t i = 0; i < prefilter_vec_.size(); i++) {
    if (prefilter_vec_[i] == NULL)
      continue;
    int id = CanonicalNode(prefilter_vec_[i])->unique_id();
    DCHECK_LE(0, id);
    Entry* entry = &entries_[id];
    entry->regexps.push_back(i);
  }
}

// Functions for triggering during search.
void PrefilterTree::RegexpsGivenStrings(
    const vector<int>& matched_atoms,
    vector<int>* regexps) const {
  regexps->clear();
  if (!compiled_) {
    LOG(WARNING) << "Compile() not called";
    for (size_t i = 0; i < prefilter_vec_.size(); ++i)
      regexps->push_back(i);
  } else {
    if (!prefilter_vec_.empty()) {
      IntMap regexps_map(prefilter_vec_.size());
      vector<int> matched_atom_ids;
      for (size_t j = 0; j < matched_atoms.size(); j++) {
        matched_atom_ids.push_back(atom_index_to_id_[matched_atoms[j]]);
        VLOG(10) << "Atom id:" << atom_index_to_id_[matched_atoms[j]];
      }
      PropagateMatch(matched_atom_ids, &regexps_map);
      for (IntMap::iterator it = regexps_map.begin();
           it != regexps_map.end();
           ++it)
        regexps->push_back(it->index());

      regexps->insert(regexps->end(), unfiltered_.begin(), unfiltered_.end());
    }
  }
  sort(regexps->begin(), regexps->end());
}

void PrefilterTree::PropagateMatch(const vector<int>& atom_ids,
                                   IntMap* regexps) const {
  IntMap count(entries_.size());
  IntMap work(entries_.size());
  for (size_t i = 0; i < atom_ids.size(); i++)
    work.set(atom_ids[i], 1);
  for (IntMap::iterator it = work.begin(); it != work.end(); ++it) {
    const Entry& entry = entries_[it->index()];
    VLOG(10) << "Processing: " << it->index();
    // Record regexps triggered.
    for (size_t i = 0; i < entry.regexps.size(); i++) {
      VLOG(10) << "Regexp triggered: " << entry.regexps[i];
      regexps->set(entry.regexps[i], 1);
    }
    int c;
    // Pass trigger up to parents.
    for (StdIntMap::iterator it = entry.parents->begin();
         it != entry.parents->end();
         ++it) {
      int j = it->first;
      const Entry& parent = entries_[j];
      VLOG(10) << " parent= " << j << " trig= " << parent.propagate_up_at_count;
      // Delay until all the children have succeeded.
      if (parent.propagate_up_at_count > 1) {
        if (count.has_index(j)) {
          c = count.get_existing(j) + 1;
          count.set_existing(j, c);
        } else {
          c = 1;
          count.set_new(j, c);
        }
        if (c < parent.propagate_up_at_count)
          continue;
      }
      VLOG(10) << "Triggering: " << j;
      // Trigger the parent.
      work.set(j, 1);
    }
  }
}

// Debugging help.
void PrefilterTree::PrintPrefilter(int regexpid) {
  LOG(INFO) << DebugNodeString(prefilter_vec_[regexpid]);
}

void PrefilterTree::PrintDebugInfo() {
  VLOG(10) << "#Unique Atoms: " << atom_index_to_id_.size();
  VLOG(10) << "#Unique Nodes: " << entries_.size();

  for (size_t i = 0; i < entries_.size(); ++i) {
    StdIntMap* parents = entries_[i].parents;
    const vector<int>& regexps = entries_[i].regexps;
    VLOG(10) << "EntryId: " << i
            << " N: " << parents->size() << " R: " << regexps.size();
    for (StdIntMap::iterator it = parents->begin(); it != parents->end(); ++it)
      VLOG(10) << it->first;
  }
  VLOG(10) << "Map:";
  for (map<string, Prefilter*>::const_iterator iter = node_map_.begin();
       iter != node_map_.end(); ++iter)
    VLOG(10) << "NodeId: " << (*iter).second->unique_id()
            << " Str: " << (*iter).first;
}

string PrefilterTree::DebugNodeString(Prefilter* node) const {
  string node_string = "";

  if (node->op() == Prefilter::ATOM) {
    DCHECK(!node->atom().empty());
    node_string += node->atom();
  } else {
    // Adding the operation disambiguates AND and OR nodes.
    node_string +=  node->op() == Prefilter::AND ? "AND" : "OR";
    node_string += "(";
    for (size_t i = 0; i < node->subs()->size(); i++) {
      if (i > 0)
        node_string += ',';
      node_string += Itoa((*node->subs())[i]->unique_id());
      node_string += ":";
      node_string += DebugNodeString((*node->subs())[i]);
    }
    node_string += ")";
  }
  return node_string;
}

}  // namespace re2


text:
#import <CoreGraphics/CGShading.h>
#import <Onyx2D/O2Shading.h>

CGShadingRef CGShadingRetain(CGShadingRef self) {
   return (CGShadingRef)O2ShadingRetain((O2ShadingRef)self);
}

void CGShadingRelease(CGShadingRef self) {
   O2ShadingRelease((O2ShadingRef)self);
}

CGShadingRef CGShadingCreateAxial(CGColorSpaceRef colorSpace,CGPoint startPoint,CGPoint endPoint,CGFunctionRef function,bool extendStart,bool extendEnd) {
   return (CGShadingRef)O2ShadingCreateAxial((O2ColorSpaceRef)colorSpace,startPoint,endPoint,(O2FunctionRef)function,extendStart,extendEnd);
}

CGShadingRef CGShadingCreateRadial(CGColorSpaceRef colorSpace,CGPoint startPoint,float startRadius,CGPoint endPoint,float endRadius,CGFunctionRef function,bool extendStart,bool extendEnd) {
   return (CGShadingRef)O2ShadingCreateRadial((O2ColorSpaceRef)colorSpace,startPoint,startRadius,endPoint,endRadius,(O2FunctionRef)function,extendStart,extendEnd);
}

redpajama_set_name: RedPajamaGithub


text:
module.exports.tasks = {
    push: {
        options: {
            npmTag: 'latest',
            updateConfigs: ['pkg'] // we use `pkg` variable in docs generation
        }
    }
};


text:
<?php

final class PhabricatorAuthLoginMessageType
  extends PhabricatorAuthMessageType {

  const MESSAGEKEY = 'auth.login';

  public function getDisplayName() {
    return pht('Login Screen Instructions');
  }

  public function getShortDescription() {
    return pht(
      'Guidance shown on the main login screen before users log in or '.
      'register.');
  }

}


text:
package collector

import (
	"fmt"
	"os"
	"strconv"

	"github.com/godbus/dbus"
	"github.com/prometheus/client_golang/prometheus"
)

const (
	logindSubsystem = "logind"
	dbusObject      = "org.freedesktop.login1"
	dbusPath        = "/org/freedesktop/login1"
)

var (
	// Taken from logind as of systemd v229.
	// "other" is the fallback value for unknown values (in case logind gets extended in the future).
	attrRemoteValues = []string{"true", "false"}
	attrTypeValues   = []string{"other", "unspecified", "tty", "x11", "wayland", "mir", "web"}
	attrClassValues  = []string{"other", "user", "greeter", "lock-screen", "background"}

	sessionsDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, logindSubsystem, "sessions"),
		"Number of sessions registered in logind.", []string{"seat", "remote", "type", "class"}, nil,
	)
)

type logindCollector struct{}

type logindDbus struct {
	conn   *dbus.Conn
	object dbus.BusObject
}

type logindInterface interface {
	listSeats() ([]string, error)
	listSessions() ([]logindSessionEntry, error)
	getSession(logindSessionEntry) *logindSession
}

type logindSession struct {
	seat        string
	remote      string
	sessionType string
	class       string
}

// Struct elements must be public for the reflection magic of godbus to work.
type logindSessionEntry struct {
	SessionID         string
	UserID            uint32
	UserName          string
	SeatID            string
	SessionObjectPath dbus.ObjectPath
}

type logindSeatEntry struct {
	SeatID         string
	SeatObjectPath dbus.ObjectPath
}

func init() {
	registerCollector("logind", defaultDisabled, NewLogindCollector)
}

// NewLogindCollector returns a new Collector exposing logind statistics.
func NewLogindCollector() (Collector, error) {
	return &logindCollector{}, nil
}

func (lc *logindCollector) Update(ch chan<- prometheus.Metric) error {
	c, err := newDbus()
	if err != nil {
		return fmt.Errorf("unable to connect to dbus: %s", err)
	}
	defer c.conn.Close()

	return collectMetrics(ch, c)
}

func collectMetrics(ch chan<- prometheus.Metric, c logindInterface) error {
	seats, err := c.listSeats()
	if err != nil {
		return fmt.Errorf("unable to get seats: %s", err)
	}

	sessionList, err := c.listSessions()
	if err != nil {
		return fmt.Errorf("unable to get sessions: %s", err)
	}

	sessions := make(map[logindSession]float64)

	for _, s := range sessionList {
		session := c.getSession(s)
		if session != nil {
			sessions[*session]++
		}
	}

	for _, remote := range attrRemoteValues {
		for _, sessionType := range attrTypeValues {
			for _, class := range attrClassValues {
				for _, seat := range seats {
					count := sessions[logindSession{seat, remote, sessionType, class}]

					ch <- prometheus.MustNewConstMetric(
						sessionsDesc, prometheus.GaugeValue, count,
						seat, remote, sessionType, class)
				}
			}
		}
	}

	return nil
}

func knownStringOrOther(value string, known []string) string {
	for i := range known {
		if value == known[i] {
			return value
		}
	}

	return "other"
}

func newDbus() (*logindDbus, error) {
	conn, err := dbus.SystemBusPrivate()
	if err != nil {
		return nil, err
	}

	methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}

	err = conn.Auth(methods)
	if err != nil {
		conn.Close()
		return nil, err
	}

	err = conn.Hello()
	if err != nil {
		conn.Close()
		return nil, err
	}

	object := conn.Object(dbusObject, dbus.ObjectPath(dbusPath))

	return &logindDbus{
		conn:   conn,
		object: object,
	}, nil
}

func (c *logindDbus) listSeats() ([]string, error) {
	var result [][]interface{}
	err := c.object.Call(dbusObject+".Manager.ListSeats", 0).Store(&result)
	if err != nil {
		return nil, err
	}

	resultInterface := make([]interface{}, len(result))
	for i := range result {
		resultInterface[i] = result[i]
	}

	seats := make([]logindSeatEntry, len(result))
	seatsInterface := make([]interface{}, len(seats))
	for i := range seats {
		seatsInterface[i] = &seats[i]
	}

	err = dbus.Store(resultInterface, seatsInterface...)
	if err != nil {
		return nil, err
	}

	ret := make([]string, len(seats)+1)
	for i := range seats {
		ret[i] = seats[i].SeatID
	}
	// Always add the empty seat, which is used for remote sessions like SSH
	ret[len(seats)] = ""

	return ret, nil
}

func (c *logindDbus) listSessions() ([]logindSessionEntry, error) {
	var result [][]interface{}
	err := c.object.Call(dbusObject+".Manager.ListSessions", 0).Store(&result)
	if err != nil {
		return nil, err
	}

	resultInterface := make([]interface{}, len(result))
	for i := range result {
		resultInterface[i] = result[i]
	}

	sessions := make([]logindSessionEntry, len(result))
	sessionsInterface := make([]interface{}, len(sessions))
	for i := range sessions {
		sessionsInterface[i] = &sessions[i]
	}

	err = dbus.Store(resultInterface, sessionsInterface...)
	if err != nil {
		return nil, err
	}

	return sessions, nil
}

func (c *logindDbus) getSession(session logindSessionEntry) *logindSession {
	object := c.conn.Object(dbusObject, session.SessionObjectPath)

	remote, err := object.GetProperty(dbusObject + ".Session.Remote")
	if err != nil {
		return nil
	}

	sessionType, err := object.GetProperty(dbusObject + ".Session.Type")
	if err != nil {
		return nil
	}

	sessionTypeStr, ok := sessionType.Value().(string)
	if !ok {
		return nil
	}

	class, err := object.GetProperty(dbusObject + ".Session.Class")
	if err != nil {
		return nil
	}

	classStr, ok := class.Value().(string)
	if !ok {
		return nil
	}

	return &logindSession{
		seat:        session.SeatID,
		remote:      remote.String(),
		sessionType: knownStringOrOther(sessionTypeStr, attrTypeValues),
		class:       knownStringOrOther(classStr, attrClassValues),
	}
}


text:
package net.robig.stlab.gui;

import javax.swing.JOptionPane;
import net.robig.logging.ILogAppender;
import net.robig.logging.Level;
import net.robig.logging.LogEntry;
import net.robig.logging.Logger;
import net.robig.stlab.model.DeviceInfo;
import net.robig.stlab.model.StPreset;

/**
 * layer between GUI and device controller to catch errors from the GUI
 * @author robig
 *
 */
public class GuiDeviceController implements IDeviceController,ILogAppender,IDeviceListener{

	private static GuiDeviceController instance=null;
	public static GuiDeviceController getInstance() { return instance; }

	private Logger log=new Logger(this.getClass());
	private boolean connected=false;
	private IDeviceController device=null;
	private StPreset preset=null;
	private DeviceFrame gui=null;

	public GuiDeviceController(IDeviceController deviceController,DeviceFrame gui) {
		instance=this;
		device=deviceController;
		this.gui=gui;
		//Also collect ERRORs from logging Framework
		Logger.addAppender(this);
	}

	/** @returns if the we're connected to the device */
	public synchronized boolean isConnected() {
		return connected;
	}

	/** Activate preset parameters on the device */
	public synchronized void activateParameters(StPreset preset) {
		try {
			device.activateParameters(preset);
		} catch (Exception e) {
			log.error("Error activating parameters! "+e.getMessage());
			e.printStackTrace(log.getDebugPrintWriter());
		}
	}

	/** Find and connect to the VOX device */
	public void findAndConnect()  {
		try {
			device.findAndConnect();
			connected=true;
		} catch (Exception e) {
			log.error("Cannot find VOX device!");
			e.printStackTrace(log.getWarnPrintWriter());
		}
	}

	/** Get the parameters of a preset */
	public StPreset getPresetParameters(int number){
		try {
			StPreset p=device.getPresetParameters(number);
			return p;
		} catch (Exception e) {
			log.error("Error preset from device! "+e.getMessage());
			e.printStackTrace(log.getWarnPrintWriter());
		}
		return new StPreset();
	}

	/** Get current activated parameters on the device */
	public synchronized StPreset getCurrentParameters()  {
		try {
			preset=device.getCurrentParameters();
			return preset;
		} catch (Exception e) {
			log.error("Error getting current parameters from device! "+e.getMessage());
			e.printStackTrace(log.getWarnPrintWriter());
		}
		return new StPreset();
	}

	/** Initialize the device and gets active parameters */
	public StPreset initialize() {
		try {
			preset=device.initialize();
		} catch (Exception e) {
			log.error("Error initializing Gui Controller!"+e.getMessage());
			e.printStackTrace(log.getDebugPrintWriter());
			preset = new StPreset();
		}
		//Listen for commands from device
		addDeviceListener(this);
		return preset;
	}

	/** Switch to the next preset */
	public synchronized void nextPreset() {
		try {
			selectPreset(preset.getNumber()+1);
		} catch (Exception e) {
			e.printStackTrace(log.getDebugPrintWriter());
		}
	}

	/** Switch to the previous preset */
	public synchronized void prevPreset() {
		try {
			selectPreset(preset.getNumber()-1);
		} catch (Exception e) {
			e.printStackTrace(log.getDebugPrintWriter());
		}
	}

	/**
	 * switch to a preset by number
	 */
	@Override
	public synchronized void selectPreset(int i)  {
//		if(i<0)i=99;
//		if(i>99)i=0;
		try {
			// send to device:
			device.selectPreset(i);
			// get parameters:
			//getCurrentParameters();
		} catch (Exception e) {
			log.error("Error setting Preset! "+e.getMessage());
			e.printStackTrace(log.getDebugPrintWriter());
		}
	}

	/** transfer a preset onto the device */
	public synchronized void savePreset(StPreset preset, int pid) {
		try {
			device.savePreset(preset, pid);
		} catch (Exception e) {
			criticalError("Preset coult not be saved! error text: "+e.getMessage());
			e.printStackTrace(log.getWarnPrintWriter());
		}
	}

	/** disconnect */
	public void disconnect() {
		device.disconnect();
		connected=false;
	}

	private void criticalError(String message){
		JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * from LogAppender to fetch all ERROR messages and output in the gui log
	 */
	@Override
	public void append(String formatedMessage, LogEntry log) {
		if(log.level.equals(Level.ERROR)){
			gui.outputError(log.level+": "+log.message);
		}
	}

	@Override
	public void init() throws Exception {
		// nothing to initialize for logging
	}

	/*     ============ from IDeviceListener */
	@Override
	public void presetSaved(StPreset preset, int presetNumber) {
		// nothing to do here
		log.info("Got DeviceListener event: savePreset: "+presetNumber);
	}

	/**
	 * Got a preset switch from the device, send parameters to the GUI
	 */
	@Override
	public void presetSwitched(int p) {
		log.debug("Got DeviceListener event: preset Switch to "+p);
		gui.setCurrentPreset(getPresetParameters(p));
	}

	/** add other device listeners */
	@Override
	public void addDeviceListener(IDeviceListener l) {
		device.addDeviceListener(l);
	}

	/** get informations about the device */
	@Override
	public DeviceInfo getDeviceInfo() {
		return device.getDeviceInfo();
	}

}


text:
Getting Started
################

*********
Overview
*********

This brief guide describes how to start the GUI, begin collecting extracellular electrophysiological data, and use some of the online spike sorting tools. Additional more comprehensive documentation can be found in later sections.

*****************
Connecting Intan
*****************

**************
Creating GUI
**************

Start the Julia terminal.Then load the Intan package:

.. code-block:: julia

	using Intan

The GUI can be started with the following line of code:

.. code-block:: julia

	Intan_GUI()

This will create a GUI with the default configuration file. The configuration file specifies how many evaluation boards and headstages are connected, what behavioral task is to be run, how data is to be saved, etc. The default assumes that a 64 channel RHD2164 headstage is connected to the Port A1 of the Intan Evaluation board.

These files are simple and typically only a few lines of code. The user can create their own and then load it passing the path to the file as an argument to Intan_GUI:

.. code-block:: julia

	Intan_GUI("/path/to/your/configuration/file.jl")

More documentation on designing the appropriate configuration can be found in its own section of this guide.

*******************
Interface Overview
*******************

Now the interface should appear. The GUI is divided into several regions by default:

.. image:: GUI.png

The far left pane contains the most commonly used buttons for online spike sorting and data visualization. This pane also contains the buttons that start the data acquisition at the top.

The upper left pane shows a magnified view of a single channel. By default this shows the snippet of voltage surrounding a threshold crossing. The slider to set that threshold crossing is located on the left hand side. In this view, waveforms assigned to particular clusters (single units) will be assigned different colors.

The lower left pane shows spike sorting specific visualizations from the single channel highlighted above. These include the templates used for online template matching, and the color coded spike rasters for each individual unit.

The right pane is used for additional visualizations of incoming data. Some of these include 1) multiple channel displays, 2) multiple channel spike rasters, 3) digital oscilloscope and 4) digital events and analog signals from data given to the TTL and ADC inputs to the Intan evaluation board. One the right side of this pane are the buttons used to select which of these are displayed.

Finally, the top menubar has additional options, such as saving and loading sorting parameters, changing sorting options, and defining reference configurations.

*****************
Data Acquisition
*****************

The buttons used to start acquisition are located in the top right of the GUI. To begin data acquisition, first communication with the evaluation board and headstages must be established. This is done by clicking on the "Init" button. The output of the Julia terminal should indicate if the board is found and initialized correctly.

The "Run" button will begin acquisition with the evaluation board. After clicking the run button, the experimental timer should start climbing on the top right of the GUI. You will see that the "Calibrate button" is checked at this point, and data is not being displayed. At first, the data is being used by the software to start to find optimum threshold and sorting values. This calibration period only needs to last a second or so. To start data visualization, uncheck the "calibrate" box.

.. only:: html

   .. figure:: pics/GUI_control.gif

*******************
Data Visualization
*******************

Now waveforms should start to appear in the single channel and multi channel displays. Only waveforms (snippets of the raw voltage signal from a channel) crossing a threshold value are displayed. The user can right-click in this window at any time to refresh the display.

===================
Threshold and Gain
===================

The user can manipulate this signal in two important ways: 1) changing the threshold value necessary for a waveform to be display, and 2) changing the gain of the incoming voltage signal. The current threshold and gain values are displayed to the left of the single channel display. The user can change the gain value (make the signal larger or smaller) by changing the value in the box to the left of the display. The threshold can be adjusted by dragging the threshold slider, located immediately to the left of the display.

The gain can be adjusted in multiples of 10 by selecting the x10 box. Additionally, the gain for every channel, not just the one displayed, can be modified by first selecting the "all channels" box under gain (remember to turn this off when you are done using it!)

The threshold can be displayed as a line across the single channel display by checking the "show" box in the threshold pain. Additionally, the threshold for all channels can be adjusted by selecting the "all channels" box under threshold (remember to turn this off when you are done using it!)

============================
Selecting different channels
============================

You can change the channel that is displayed in the single channel display by 1) left-clicking on the channel in the multi-channel display or 2) dragging the slider under the left pane to the desired channel value. Either way, the single channel that is displayed should change, as indicated by the number displayed in the top left of the single channel display, and by the purple box drawn around the selected channel in the mutli-channel display. Note that the slider under the left pane only allows you to select channels visble on the multi-channel display to the left. For instance, if there are 32 channels total, but you are only using the 16-channel display, you can only select channels 1-16. To see the second 16 channels (17-32), you can move the slider located under the multichannel display to change which channels are visualized.

===============
Other displays
===============

The buttons on the right side of the right display allow the user to change which additional visualizations are available. Depending on their size, multiple can be shown at once.

--------------------------------
16, 32, and 64 channel displays
--------------------------------

Waveforms from 16, 32, or 64 channels can be displayed simultaneously. These work the same as the 16 channel display in that the selected single channel is highlighted in purple, and you can select a single channel by clicking on it. If a channel is not needed to be visualized, the user can right-click on that channel and selected "disable".

-------------------------------
16, 32, and 64 channel rasters
-------------------------------

Raster plots are temporal event plots, where each event (a waveform detected on that channel) is displayed as a vertical bar at approximately the time relative to when the screen refreshed. Each raster displays about ~10 seconds worth spikes. Each spike will be color coded based on the unit it is assigned to during spike sorting.

-----------
Soft Scope
-----------

This is a digital oscilloscope that shows the raw voltage trace for the channel that is displayed in the single channel window. By right-clicking, the user can change the voltage-gain, time divisions, and whether or not the threshold will also be displayed. Asterisks are shown at the bottom of the soft scope to indicate signals that were identified as threshold crossings.

-------
Events
-------

This display can be used to visualize data that is received on either the analog-to-digital convertor on the Intan evaluation board, or as a TTL event on the evaluation board. Up to 6 different channels can be displayed at once. To display an event, right click on the section of the plot wher eyou would like that signal to be displayed and select the channel from the dialogue box.

**************
Spike Sorting
**************

The general technique used by Intan.jl for spike sorting is 1) selecting waveforms thought to belong to an individual neuron 2) building a template from these waveforms, and 3) performing template matching with this template, and 4) if it is a match, assigning that waveform as belonging to that individual neuron. The user can create as many separate templates as necessary for a single channel.

The "cluster" dialogue box at the bottom left indicates which cluster, or unit, is currently selected. By default, a channel will only have the 0 cluster, which indicates that there are no units and consequently no template matching that will be performed. As you add units, this list will be populated with more units (1, 2, 3 etc). You can click on each unit to make it the "active unit."

===================
Selecting Waveforms
===================

At any time, you can left-click in the single channel display, hold, and drag. You will see a rubberband created while doing this. Any units that cross this rubber band when you let go of the left-click will be assigned to the currently active cluster, and a template will be generated from those waveforms. Right now, selecting units with the 0 cluster selected should do nothing.

=====================
Collecting Templates
=====================

By default, the single display will be continuously updated as new waveforms stream in, and will automatically refresh about every 10 seconds. This can make unit selection difficult; therefore, you can select the "Collect Templates" button to refresh the display followed by more waveforms continuing to be plotted in real time. The "collect templates" button will now read "stop collection". Once "stop collection" is selected, the single display will freeze. While data will continue to stream in, the user can manipulate these units on the display.

In the "collect units" mode, the right-click now will also generate a rubberband if the user clicks, holds and drags. Any units that cross this rubber band when it is released will be "masked" and disappear from the display. This can be used to clear obvious noise from the display before moving onto template generation. This mask feature works when the "0" cluster is selected.

=============
Adding Units
=============

--------------------
Selecting Waveforms
--------------------

To create a new unit, first click the "add unit" button. In the cluster list, you should see a new unit appear with the number 1, and it will be automatically selected. Now any units that are selected with the left click rubber band will be assigned to that unit. Left-click, drag and release to select a group of units, and you will see the waveforms turn the same color as the new cluster (yellow for cluster 1). Of note, the user should also see each unit turn that color in real time, so that the user has real time feedback about which units will be selected.

----------------------
Deselecting Waveforms
----------------------

The user can also use the right-click rubberband to remove units from the display. If unit 0 is selected, these units will be removed from the display. However, if the current unit is selected waveforms not belonging to that unit will be removed from the display, but waveforms that were assigned to that unit will be removed from the display and the template will be recalculated with those units subtracted. In this way, the user can always be generous in their first selection and "prune" away unwanted waveforms to create the best template.

=================
Resuming Display
=================

================
Deleting Units
================

=========================
Modifying Template Bounds
=========================


text:
void STLMapHandler::createSizeFunction() {

    // Check if there already is an _Rb_tree_iterator type defined
    StructType *Rb_tree_it_type = M->getTypeByName(
        "struct.std::_Rb_tree_iterator"
    );

    // If not found, create one
    if (Rb_tree_it_type == NULL) {
        errs() << "Creation of _Rb_tree_iterator not yet implemented.\n";
        assert(0);
    }

    // Allocate space for size
    auto *size_alloc = builder->CreateAlloca(
        IntegerType::get(M->getContext(), 64),
        0,
        "size_sum"
    );
    size_alloc->setAlignment(8);

    // Initialize size sum
    auto *size_sum_store_init = builder->CreateStore(
        ConstantInt::get(IntegerType::getInt64Ty(M->getContext()), 0),
        size_alloc
    );
    size_sum_store_init->setAlignment(8);

    // Create a iterator
    auto *map_it_alloc = builder->CreateAlloca(
        Rb_tree_it_type, 0, "map_it"
    );
    map_it_alloc->setAlignment(8);

    // Create a iterator
    auto *map_it_t1_alloc = builder->CreateAlloca(
        Rb_tree_it_type, 0, "map_it_tmp1"
    );
    map_it_t1_alloc->setAlignment(8);

    // Create a iterator
    auto *map_it_t2_alloc = builder->CreateAlloca(
        Rb_tree_it_type, 0, "map_it_tmp2"
    );
    map_it_t2_alloc->setAlignment(8);

    // Initialize it
    STLMapHandler_ElementIterator ei(this);
    Function *tree_map_iter_fun = ei.getSizeFunction();
    ei.CreateSizeFunctionFromPrototype(tree_map_iter_fun);
    builder->CreateCall(tree_map_iter_fun, map_it_alloc);

    // Function for std::map<K,V>::begin
    STLMapHandler_TreeIteratorBeginOrEnd TreeItBegin(this, true);
    Function *tree_map_iter_begin_fun = TreeItBegin.getSizeFunction();
    TreeItBegin.CreateSizeFunctionFromPrototype(tree_map_iter_begin_fun);

    auto *map_it_begin = builder->CreateCall(tree_map_iter_begin_fun, f_arg);

    auto *rb_tree_it_t1_gep = builder->CreateConstInBoundsGEP2_32(
        map_it_t1_alloc, 0, 0
    );
    builder->CreateStore(map_it_begin, rb_tree_it_t1_gep);

    auto *map_it_cast_to_i8 = builder->CreateBitCast(
        map_it_alloc,
        PointerType::getInt8PtrTy(M->getContext())
    );

    auto *map_it_t1_cast_to_i8 = builder->CreateBitCast(
        map_it_t1_alloc,
        PointerType::getInt8PtrTy(M->getContext())
    );

    builder->CreateMemCpy(
        map_it_cast_to_i8,
        map_it_t1_cast_to_i8,
        8,
        8,
        false
    );

    BasicBlock *main_loop = BasicBlock::Create(
        M->getContext(), "main_loop", f
    );

    builder->CreateBr(main_loop);

    builder->SetInsertPoint(main_loop);

    // Function for std::map<K,V>::end
    STLMapHandler_TreeIteratorBeginOrEnd TreeItEnd(this, false);
    Function *tree_map_iter_end_fun = TreeItEnd.getSizeFunction();
    TreeItEnd.CreateSizeFunctionFromPrototype(tree_map_iter_end_fun);

    auto *map_it_end = builder->CreateCall(tree_map_iter_end_fun, f_arg);

    auto *rb_tree_it_t2_gep = builder->CreateConstInBoundsGEP2_32(
        map_it_t2_alloc, 0, 0
    );
    builder->CreateStore(map_it_end, rb_tree_it_t2_gep);

    STLMapHandler_TreeIteratorCmp TreeItCmp(
        this,
        PointerType::get(Rb_tree_it_type, 0)
    );
    TreeItCmp.CreateSizeFunctionFromPrototype(TreeItCmp.getSizeFunction());
    auto *tree_map_it_cmp = builder->CreateCall2(
        TreeItCmp.getSizeFunction(),
        map_it_alloc,
        map_it_t2_alloc
    );

    BasicBlock *ret_true_BB = BasicBlock::Create(
        M->getContext(), "cmp_true", f
    );
    BasicBlock *ret_false_BB = BasicBlock::Create(
        M->getContext(), "cmp_false", f
    );

    builder->CreateCondBr(tree_map_it_cmp, ret_true_BB, ret_false_BB);

    builder->SetInsertPoint(ret_true_BB);

    //StructType *node_type = argi.getMapNodeType();
    StructType *node_type = v->second.MapNodeType;

    STLMapHandler_TreeIteratorAccess TreeItAccess(
        this, node_type, PointerType::get(Rb_tree_it_type, 0)
    );
    Function *map_access_pair_fun = TreeItAccess.getSizeFunction();
    TreeItAccess.CreateSizeFunctionFromPrototype(map_access_pair_fun);
    auto *map_pair = builder->CreateCall(
        map_access_pair_fun, map_it_alloc
    );

    auto *map_pair_first_gep = builder->CreateConstInBoundsGEP2_32(
        map_pair, 0, 0
    );

    // PLACE CALL TO SIZE FOR FIRST TYPE HERE

    // Call the size function
    auto outEdges = g->outEdges(v);

    // Must be two edges
    assert(!(outEdges.size() != 2));

    // Select the edge with idx = 0
    TG_edgeIterator edge1, edge2;
    if (outEdges[0]->second.index == 0) {
        edge1 = outEdges[0]; edge2 = outEdges[1];
    }

    if (outEdges[1]->second.index == 0) {
        edge1 = outEdges[1]; edge2 = outEdges[0];
    }

    auto target_val_fun = BTH->runOnGraphEdge(edge1);

    auto *size_call_1 = builder->CreateCall(
        target_val_fun, ArrayRef<Value*>(map_pair_first_gep)
    );

    // Add result to size sum
    auto *size_sum_load = builder->CreateLoad(size_alloc);
          size_sum_load->setAlignment(8);

    auto *size_sum_add = builder->CreateNUWAdd(size_call_1, size_sum_load);

    // Store
    auto *size_sum_store = builder->CreateStore(size_sum_add, size_alloc);
          size_sum_store->setAlignment(8);

    map_pair = builder->CreateCall(map_access_pair_fun, map_it_alloc);
    auto *map_pair_second_gep = builder->CreateConstInBoundsGEP2_32(
        map_pair, 0, 1
    );

    // PLACE CALL TO SIZE FOR SECOND TYPE HERE
    target_val_fun = BTH->runOnGraphEdge(edge2);

    auto *size_call_2 = builder->CreateCall(
        target_val_fun, ArrayRef<Value*>(map_pair_second_gep)
    );

    // Add result to size sum
    size_sum_load = builder->CreateLoad(size_alloc);
    size_sum_load->setAlignment(8);

    size_sum_add = builder->CreateNUWAdd(size_call_2, size_sum_load);

    // Store
    size_sum_store = builder->CreateStore(size_sum_add, size_alloc);
    size_sum_store->setAlignment(8);

    STLMapHandler_ElementIteratorInc IterInc(
        this, PointerType::get(Rb_tree_it_type, 0)
    );
    Function *map_it_inc_fun = IterInc.getSizeFunction();
    IterInc.CreateSizeFunctionFromPrototype(map_it_inc_fun);
    builder->CreateCall(map_it_inc_fun, map_it_alloc);

    builder->CreateBr(main_loop);

    builder->SetInsertPoint(ret_false_BB);

    // Return the cumulated size
    auto *size_sum_ret_load = builder->CreateLoad(size_alloc);
          size_sum_ret_load->setAlignment(8);

    builder->CreateRet(size_sum_ret_load);

}

void STLMapHandler_ElementIterator::createSizeFunction() {

    // Check if there already is an _Rb_tree_iterator type defined
    StructType *Rb_tree_it_type = M->getTypeByName(
        "struct.std::_Rb_tree_iterator"
    );
    PointerType *t = PointerType::get(Rb_tree_it_type, 0);

    auto *iter_alloc = builder->CreateAlloca(t);
    iter_alloc->setAlignment(8);

    auto *iter_store = builder->CreateStore(f_arg, iter_alloc);
    iter_store->setAlignment(8);

    auto *iter_load = builder->CreateLoad(iter_alloc);

    auto *iter_gep = builder->CreateConstInBoundsGEP2_32(iter_load, 0, 0);

    // Let the iterator point to _Rb_tree_node_base
    builder->CreateStore(
        ConstantPointerNull::get(
            cast<PointerType>(Rb_tree_it_type->getContainedType(0))
        ), iter_gep
    );

    builder->CreateRetVoid();

}

void STLMapHandler_TreeIteratorBeginOrEndL2::createSizeFunction() {

    StructType *Rb_tree_it_type = M->getTypeByName(
        "struct.std::_Rb_tree_iterator"
    );
    auto *it_alloc = builder->CreateAlloca(Rb_tree_it_type);
    it_alloc->setAlignment(8);

    auto *tree_alloc = builder->CreateAlloca(t);
    tree_alloc->setAlignment(8);

    auto *tree_store = builder->CreateStore(f_arg, tree_alloc);
    tree_store->setAlignment(8);

    auto *tree_load = builder->CreateLoad(tree_alloc);

    auto *tree_gep = builder->CreateConstInBoundsGEP2_32(tree_load, 0, 0);
    tree_gep = builder->CreateConstInBoundsGEP2_32(tree_gep, 0, 1);

    //StructType *node_type = arg.getMapNodeType();
    StructType *node_type = v->second.MapNodeType;

    Value *tree_base_to_node_cast = NULL;

    if (begin) {

        tree_gep = builder->CreateConstInBoundsGEP2_32(tree_gep, 0, 2);

        auto *tree_base_load = builder->CreateLoad(tree_gep);
        tree_base_load->setAlignment(8);

        tree_base_to_node_cast = builder->CreateBitCast(
            tree_base_load,
            PointerType::get(node_type, 0)
        );

    } else {

        tree_base_to_node_cast = builder->CreateBitCast(
            tree_gep,
            PointerType::get(node_type, 0)
        );

    }

    STLMapHandler_CreateRbTreeIterator CreateRbTreeIter(
        this, it_alloc->getType(), PointerType::get(node_type, 0)
    );
    Function *size_fun = CreateRbTreeIter.getSizeFunction();
    CreateRbTreeIter.CreateSizeFunctionFromPrototype(size_fun);
    builder->CreateCall2(
        size_fun, it_alloc, tree_base_to_node_cast
    );

    auto *rb_tree_it_gep = builder->CreateConstInBoundsGEP2_32(it_alloc, 0, 0);

    auto *rb_tree_base_load = builder->CreateLoad(rb_tree_it_gep);

    builder->CreateRet(rb_tree_base_load);

}

void STLMapHandler_CreateRbTreeIterator::createSizeFunction() {

    // Name first argument as "this"
    auto arg_it = f->arg_begin();
    arg_it->setName("it");

    auto arg_tree_node = ++(f->arg_begin());
    arg_tree_node->setName("tree_node");

    auto *it_alloc = builder->CreateAlloca(it_ty);
    it_alloc->setAlignment(8);

    auto *tree_node_alloc = builder->CreateAlloca(node_ty);
    tree_node_alloc->setAlignment(8);

    auto *it_store = builder->CreateStore(arg_it, it_alloc);
    it_store->setAlignment(8);

    auto *tree_node_store = builder->CreateStore(
        arg_tree_node, tree_node_alloc
    );
    tree_node_store->setAlignment(8);

    auto *it_load = builder->CreateLoad(it_alloc);

    auto *it_gep = builder->CreateConstInBoundsGEP2_32(it_load, 0, 0);

    auto *tree_node_load = builder->CreateLoad(tree_node_alloc);
    tree_node_load->setAlignment(8);

    auto *tree_node_to_base_cast = builder->CreateBitCast(
        tree_node_load,
        it_gep->getType()->getContainedType(0)
    );

    auto *tree_node_base_store = builder->CreateStore(
        tree_node_to_base_cast, it_gep
    );
    tree_node_base_store->setAlignment(8);

    builder->CreateRetVoid();

}

void STLMapHandler_TreeIteratorBeginOrEnd::createSizeFunction() {

    StructType *Rb_tree_node_base_type = M->getTypeByName(
        "struct.std::_Rb_tree_node_base"
    );
    if (Rb_tree_node_base_type == NULL) {
        errs() << "Rb_tree_node_base_type not found!\n";
        assert(0);
    }

    PointerType *Rb_tree_node_base_ptr_type = PointerType::get(
        Rb_tree_node_base_type, 0
    );

    StructType *Rb_tree_it_type = M->getTypeByName(
        "struct.std::_Rb_tree_iterator"
    );

    auto *it_alloc = builder->CreateAlloca(Rb_tree_it_type);
    it_alloc->setAlignment(8);

    auto *map_alloc = builder->CreateAlloca(t);
    map_alloc->setAlignment(8);

    auto *map_store = builder->CreateStore(f_arg, map_alloc);
    map_store->setAlignment(8);

    auto *map_load = builder->CreateLoad(map_alloc);

    auto *map_gep = builder->CreateConstInBoundsGEP2_32(map_load, 0, 0);

    STLMapHandler_TreeIteratorBeginOrEndL2 TreeIterBeginOrEndL2(
       this, begin,
       Rb_tree_node_base_ptr_type,
       cast<PointerType>(map_gep->getType())
    );

    Function *tree_iter_begin_or_end_l2_fun = TreeIterBeginOrEndL2.getSizeFunction();
    TreeIterBeginOrEndL2.CreateSizeFunctionFromPrototype(tree_iter_begin_or_end_l2_fun);

    auto *tree_map_it_2nd = builder->CreateCall(
        tree_iter_begin_or_end_l2_fun,
        map_gep
    );

    auto *rb_tree_it_gep = builder->CreateConstInBoundsGEP2_32(it_alloc, 0, 0);

    builder->CreateStore(tree_map_it_2nd, rb_tree_it_gep);

    rb_tree_it_gep = builder->CreateConstInBoundsGEP2_32(it_alloc, 0, 0);

    auto *rb_tree_node_base_load = builder->CreateLoad(rb_tree_it_gep);

    builder->CreateRet(rb_tree_node_base_load);

}

void STLMapHandler_MapSize::createSizeFunction() {

    auto *map_alloc = builder->CreateAlloca(t);
    map_alloc->setAlignment(8);

    auto *map_store = builder->CreateStore(f_arg, map_alloc);
    map_store->setAlignment(8);

    auto *map_load = builder->CreateLoad(map_alloc);

    auto *rb_tree_gep = builder->CreateConstInBoundsGEP2_32(map_load, 0, 0);

    auto *rb_tree_alloc = builder->CreateAlloca(rb_tree_gep->getType());
    rb_tree_alloc->setAlignment(8);

    auto *rb_tree_store = builder->CreateStore(rb_tree_gep, rb_tree_alloc);
    rb_tree_store->setAlignment(8);

    auto *rb_tree_load = builder->CreateLoad(rb_tree_alloc);

    rb_tree_gep = builder->CreateConstInBoundsGEP2_32(rb_tree_load, 0, 0);
    rb_tree_gep = builder->CreateConstInBoundsGEP2_32(rb_tree_gep, 0, 2);

    auto *rb_size_load = builder->CreateLoad(rb_tree_gep);
    rb_size_load->setAlignment(8);

    // Return the size
    builder->CreateRet(rb_size_load);

}

void STLMapHandler_TreeIteratorCmp::createSizeFunction() {

    // Name first argument as "this"
    auto arg_it1 = f->arg_begin();
    arg_it1->setName("it1");

    auto arg_it2 = ++(f->arg_begin());
    arg_it2->setName("it2");

    auto *it1_alloc = builder->CreateAlloca(t);
    it1_alloc->setAlignment(8);

    auto *it2_alloc = builder->CreateAlloca(t);
    it2_alloc->setAlignment(8);

    auto *it1_store = builder->CreateStore(arg_it1, it1_alloc);
    it1_store->setAlignment(8);

    auto *it2_store = builder->CreateStore(arg_it2, it2_alloc);
    it2_store->setAlignment(8);

    auto *it1_load = builder->CreateLoad(it1_alloc);

    auto *it1_gep = builder->CreateConstInBoundsGEP2_32(it1_load, 0, 0);

    auto *tree_node_base_1_load = builder->CreateLoad(it1_gep);
    tree_node_base_1_load->setAlignment(8);

    auto *it2_load = builder->CreateLoad(it2_alloc);

    auto *it2_gep = builder->CreateConstInBoundsGEP2_32(it2_load, 0, 0);

    auto *tree_node_base_2_load = builder->CreateLoad(it2_gep);
    tree_node_base_2_load->setAlignment(8);

    auto *it_cmp = builder->CreateICmpNE(
        tree_node_base_1_load,
        tree_node_base_2_load
    );

    builder->CreateRet(it_cmp);

}

void STLMapHandler_TreeIteratorAccess::createSizeFunction() {

    auto *it_alloc = builder->CreateAlloca(it_ty);
    it_alloc->setAlignment(8);

    auto *it_store = builder->CreateStore(f_arg, it_alloc);
    it_store->setAlignment(8);

    auto *it_load = builder->CreateLoad(it_alloc);

    auto *it_gep = builder->CreateConstInBoundsGEP2_32(it_load, 0, 0);

    auto *tree_node_base_load = builder->CreateLoad(it_gep);
    tree_node_base_load->setAlignment(8);

    auto *tree_node_base_to_tree_node_cast = builder->CreateBitCast(
        tree_node_base_load,
        PointerType::get(node_ty, 0)
    );

    auto *tree_node_gep = builder->CreateConstInBoundsGEP2_32(
        tree_node_base_to_tree_node_cast,
        0,
        1
    );

    builder->CreateRet(tree_node_gep);

}

void STLMapHandler_ElementIteratorInc::createSizeFunction() {

    auto *it_alloc = builder->CreateAlloca(t);
    it_alloc->setAlignment(8);

    auto *it_store = builder->CreateStore(f_arg, it_alloc);
    it_store->setAlignment(8);

    auto *it_load = builder->CreateLoad(it_alloc);

    auto *it_gep = builder->CreateConstInBoundsGEP2_32(it_load, 0, 0);

    auto *tree_node_base_load = builder->CreateLoad(it_gep);
    tree_node_base_load->setAlignment(8);

    Function *tree_inc_fun = cast<Function>(M->getOrInsertFunction(
        "_ZSt18_Rb_tree_incrementPSt18_Rb_tree_node_base",
        tree_node_base_load->getType(),
        tree_node_base_load->getType(),
        NULL
    ));
    auto *tree_inc = builder->CreateCall(tree_inc_fun, tree_node_base_load);

    it_gep = builder->CreateConstInBoundsGEP2_32(it_load, 0, 0);

    auto *tree_node_base_store = builder->CreateStore(tree_inc, it_gep);
    tree_node_base_store->setAlignment(8);

    builder->CreateRet(it_load);

}

RegisterTypeHandler<STLMapHandler> STLMapHandler::reg(
    Types::STL_CONTAINER_MAP
);


text:
package javax.print;

import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import javax.print.attribute.DocAttributeSet;

import org.apache.harmony.print.internal.nls.Messages;

public final class SimpleDoc implements Doc {
    private Object printdata;

    private DocFlavor flavor;

    private DocAttributeSet attributes;

    private Reader reader;

    private InputStream instream;

    public SimpleDoc(Object printData, DocFlavor docflavor, DocAttributeSet docattributes) {
        /*
         * IllegalArgumentException - if flavor or printData is null, or the
         * printData does not correspond to the specified doc flavor--for
         * example, the data is not of the type specified as the representation
         * in the DocFlavor.
         */
        if (docflavor == null || printData == null) {

            //print.00= Argument is null
            throw new IllegalArgumentException(Messages.getString("print.00")); //$NON-NLS-1$
        }
        try {
            Class<?> clazz = Class.forName(docflavor.getRepresentationClassName());
            if (!clazz.isInstance(printData)) {
                throw new IllegalArgumentException("");
            }
        } catch (Exception e) {
            //print.01= Wrong type of print data
            throw new IllegalArgumentException(Messages.getString("print.01")); //$NON-NLS-1$
            }
        this.printdata = printData;
        this.flavor = docflavor;
        this.attributes = docattributes;
        this.reader = null;
        this.instream = null;
    }

    public DocAttributeSet getAttributes() {
        return attributes;
    }

    public DocFlavor getDocFlavor() {
        return flavor;
    }

    public Object getPrintData() throws IOException {
        return printdata;
    }

    public Reader getReaderForText() throws IOException {
        synchronized (this) {
            if (reader != null) {
                return reader;
            }
            if (printdata instanceof Reader) {
                reader = (Reader) printdata;
            } else if (printdata instanceof char[]) {
                reader = new CharArrayReader((char[]) printdata);
            } else if (printdata instanceof String) {
                reader = new StringReader((String) printdata);
            }
        }
        return reader;
    }

    public InputStream getStreamForBytes() throws IOException {
        synchronized (this) {
            if (instream != null) {
                return instream;
            }
            if (printdata instanceof InputStream) {
                instream = (InputStream) printdata;
            } else if (printdata instanceof byte[]) {
                instream = new ByteArrayInputStream((byte[]) printdata);
            }
        }
        return instream;
    }
}


text:
from __future__ import unicode_literals

import django.contrib.postgres.fields
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0005_remove_information_photos'),
    ]

    operations = [
        migrations.AddField(
            model_name='information',
            name='photos',
            field=django.contrib.postgres.fields.ArrayField(base_field=models.FileField(upload_to=b''), null=True, size=None),
        ),
    ]


text:
import Enum from '../../lib/Enum';

export default new Enum([
  'noToNumber',
  'noAreaCode',
  'specialNumber',
  'connectFailed',
  'internalError',
  'notAnExtension',
  'networkError',
  'noRingoutEnable',
], 'callErrors');


text:
<?php

class Ess_M2ePro_Model_Cron_Task_Walmart_Listing_Product_Channel_SynchronizeData_Blocked
    extends Ess_M2ePro_Model_Cron_Task_Abstract
{
    const NICK = 'walmart/listing/product/channel/synchronize_data/blocked';

    //####################################

    public function isPossibleToRun()
    {
        if (Mage::helper('M2ePro/Server_Maintenance')->isNow()) {
            return false;
        }

        return parent::isPossibleToRun();
    }

    //########################################

    /**
     * @return Ess_M2ePro_Model_Synchronization_Log
     */
    protected function getSynchronizationLog()
    {
        $synchronizationLog = parent::getSynchronizationLog();

        $synchronizationLog->setComponentMode(Ess_M2ePro_Helper_Component_Walmart::NICK);
        $synchronizationLog->setSynchronizationTask(Ess_M2ePro_Model_Synchronization_Log::TASK_LISTINGS);

        return $synchronizationLog;
    }

    //########################################

    protected function performActions()
    {
        $accounts = Mage::helper('M2ePro/Component_Walmart')->getCollection('Account')->getItems();

        if (empty($accounts)) {
            return;
        }

        foreach ($accounts as $account) {

            /** @var $account Ess_M2ePro_Model_Account **/

            $this->getOperationHistory()->addText('Starting Account "'.$account->getTitle().'"');

            $this->getOperationHistory()->addTimePoint(
                __METHOD__.'process'.$account->getId(),
                'Process Account '.$account->getTitle()
            );

            try {
                $this->processAccount($account);
            } catch (Exception $exception) {
                // M2ePro_TRANSLATIONS
                // The "Update Blocked Listings Products" Action for Walmart Account: "%account%"
                // was completed with error.
                $message = 'The "Update Blocked Listings Products" Action for Walmart Account "%account%"';
                $message .= ' was completed with error.';
                $message = Mage::helper('M2ePro')->__($message, $account->getTitle());

                $this->processTaskAccountException($message, __FILE__, __LINE__);
                $this->processTaskException($exception);
            }

            $this->getOperationHistory()->saveTimePoint(__METHOD__.'process'.$account->getId());

            $this->getLockItemManager()->activate();
        }
    }

    //########################################

    protected function processAccount(Ess_M2ePro_Model_Account $account)
    {
        /** @var $collection Mage_Core_Model_Resource_Db_Collection_Abstract */
        $collection = Mage::getModel('M2ePro/Listing')->getCollection();
        $collection->addFieldToFilter('component_mode', Ess_M2ePro_Helper_Component_Walmart::NICK);
        $collection->addFieldToFilter('account_id', (int)$account->getId());

        if (!$collection->getSize()) {
            return;
        }

        $dispatcher = Mage::getModel('M2ePro/Walmart_Connector_Dispatcher');
        $connector = $dispatcher->getVirtualConnector('inventory', 'get', 'wpidsItems', array(), 'data', $account);
        $dispatcher->process($connector);

        $wpids = $connector->getResponseData();

        /** @var $connRead Varien_Db_Adapter_Pdo_Mysql */
        $connRead = Mage::getSingleton('core/resource')->getConnection('core_read');

        /** @var $stmtTemp Zend_Db_Statement_Pdo */
        $stmtTemp = $connRead->query($this->getPdoStatementExistingListings($account));

        $tempLog = Mage::getModel('M2ePro/Listing_Log');
        $tempLog->setComponentMode(Ess_M2ePro_Helper_Component_Walmart::NICK);

        $logsActionId = Mage::getResourceModel('M2ePro/Listing_Log')->getNextActionId();

        $notReceivedIds = array();
        while ($existingItem = $stmtTemp->fetch()) {
            if (in_array($existingItem['wpid'], $wpids)) {
                continue;
            }

            $notReceivedItem = $existingItem;

            if (!in_array((int)$notReceivedItem['id'], $notReceivedIds)) {
                $statusChangedFrom = Mage::helper('M2ePro/Component_Walmart')
                    ->getHumanTitleByListingProductStatus($notReceivedItem['status']);
                $statusChangedTo = Mage::helper('M2ePro/Component_Walmart')
                    ->getHumanTitleByListingProductStatus(Ess_M2ePro_Model_Listing_Product::STATUS_BLOCKED);

                // M2ePro_TRANSLATIONS
                // Item Status was successfully changed from "%from%" to "%to%" .
                $tempLogMessage = Mage::helper('M2ePro')->__(
                    'Item Status was successfully changed from "%from%" to "%to%" .',
                    $statusChangedFrom,
                    $statusChangedTo
                );

                $tempLog->addProductMessage(
                    $notReceivedItem['listing_id'],
                    $notReceivedItem['product_id'],
                    $notReceivedItem['id'],
                    Ess_M2ePro_Helper_Data::INITIATOR_EXTENSION,
                    $logsActionId,
                    Ess_M2ePro_Model_Listing_Log::ACTION_CHANNEL_CHANGE,
                    $tempLogMessage,
                    Ess_M2ePro_Model_Log_Abstract::TYPE_SUCCESS,
                    Ess_M2ePro_Model_Log_Abstract::PRIORITY_LOW
                );

                if (!empty($notReceivedItem['is_variation_product']) &&
                    !empty($notReceivedItem['variation_parent_id'])
                ) {
                    $parentIdsForProcessing[] = $notReceivedItem['variation_parent_id'];
                }
            }

            $notReceivedIds[] = (int)$notReceivedItem['id'];
        }

        $notReceivedIds = array_unique($notReceivedIds);

        $mainBind = array(
            'status'         => Ess_M2ePro_Model_Listing_Product::STATUS_BLOCKED,
            'status_changer' => Ess_M2ePro_Model_Listing_Product::STATUS_CHANGER_COMPONENT,
        );

        $childBind = array(
            'is_missed_on_channel' => 1,
        );

        /** @var $connWrite Varien_Db_Adapter_Pdo_Mysql */
        $connWrite = Mage::getSingleton('core/resource')->getConnection('core_write');

        $listingProductMainTable = Mage::getResourceModel('M2ePro/Listing_Product')->getMainTable();
        $listingProductChildTable = Mage::getResourceModel('M2ePro/Walmart_Listing_Product')->getMainTable();

        $chunckedIds = array_chunk($notReceivedIds, 1000);
        foreach ($chunckedIds as $partIds) {
            $where = '`id` IN ('.implode(',', $partIds).')';
            $connWrite->update($listingProductMainTable, $mainBind, $where);

            $where = '`listing_product_id` IN ('.implode(',', $partIds).')';
            $connWrite->update($listingProductChildTable, $childBind, $where);
        }

        if (!empty($parentIdsForProcessing)) {
            $this->processParentProcessors($parentIdsForProcessing);
        }
    }

    protected function getPdoStatementExistingListings(Ess_M2ePro_Model_Account $account)
    {
        /** @var $collection Mage_Core_Model_Resource_Db_Collection_Abstract */
        $collection = Mage::helper('M2ePro/Component_Walmart')->getCollection('Listing_Product');
        $collection->getSelect()->join(
            array('l' => Mage::getResourceModel('M2ePro/Listing')->getMainTable()),
            'main_table.listing_id = l.id',
            array()
        );

        $collection->addFieldToFilter('l.account_id', (int)$account->getId());
        $collection->addFieldToFilter(
            'status', array('nin' => array(
            Ess_M2ePro_Model_Listing_Product::STATUS_BLOCKED,
            Ess_M2ePro_Model_Listing_Product::STATUS_NOT_LISTED
            ))
        );
        $collection->addFieldToFilter('is_variation_parent', array('neq' => 1));
        $collection->addFieldToFilter('is_missed_on_channel', array('neq' => 1));

        /**
         * Wait for 24 hours before the newly listed item can be marked as inactive blocked
         */
        $borderDate = new DateTime('now', new \DateTimeZone('UTC'));
        $borderDate->modify('- 24 hours');
        $collection->addFieldToFilter(
            new \Zend_Db_Expr('list_date IS NULL OR list_date'), array('lt' => $borderDate->format('Y-m-d H:i:s'))
        );

        $collection->getSelect()
            ->reset(Zend_Db_Select::COLUMNS)
            ->columns(
                array(
                 'main_table.id',
                 'main_table.status',
                 'main_table.listing_id',
                 'main_table.product_id',
                 'second_table.wpid',
                 'second_table.is_variation_product',
                 'second_table.variation_parent_id'
                )
            );

        return $collection->getSelect()->__toString();
    }

    //########################################

    protected function processParentProcessors(array $parentIds)
    {
        if (empty($parentIds)) {
            return;
        }

        /** @var Ess_M2ePro_Model_Resource_Listing_Product_Collection $parentListingProductCollection */
        $parentListingProductCollection = Mage::helper('M2ePro/Component_Walmart')->getCollection('Listing_Product');
        $parentListingProductCollection->addFieldToFilter('id', array('in' => array_unique($parentIds)));

        $parentListingsProducts = $parentListingProductCollection->getItems();
        if (empty($parentListingsProducts)) {
            return;
        }

        $massProcessor = Mage::getModel(
            'M2ePro/Walmart_Listing_Product_Variation_Manager_Type_Relation_Parent_Processor_Mass'
        );
        $massProcessor->setListingsProducts($parentListingsProducts);
        $massProcessor->setForceExecuting(false);

        $massProcessor->execute();
    }

    //########################################
}


text:
function [boreHours, boreEndTime, tempDiffMean, tempDiffSurface] = boreInfo(time)
% boreInfo
% 3/14/2018

%% load data
C = load('D:\Data\ISDRI\SupportData\MacMahan\ptsal_tchain_STR3_C');  % Most onshore

tC = C.TCHAIN.time_dnum;
tempC = C.TCHAIN.TEMP';
zBedC = C.TCHAIN.ZBEDT;
zBedC(1) = zBedC(2) + (zBedC(2)-zBedC(3));

%% Redefine time vectors in UTC
dvPDT = datevec(tC);    % tA tB tC and tE are the same
dvUTC = dvPDT;
dvUTC(:,4) = dvPDT(:,4)+7;  % add 7 hours to convert from PDT to UTC
dnUTC = datenum(dvUTC);
dvUTC = datevec(dnUTC);
clear tC

%% find time index
hours = 24;
[~,timeIdx] = min(abs(dnUTC - time));
timeClippedIdx = (timeIdx - hours*3600):timeIdx; % 24 hours before
timeClipped = dnUTC(timeClippedIdx);

%% find differences between mean temp and bore temp
tBottomSmoothed = movmean(tempC(6,timeClippedIdx),5000);
tNBSmoothed = movmean(tempC(5,timeClippedIdx),5000);
tTopSmoothed = movmean(tempC(1,timeClippedIdx),5000);
tAllSmoothed = movmean(mean(tempC(:,timeClippedIdx)),5000);

diffTempAllBottom = tAllSmoothed - tBottomSmoothed;
diffTempSurfaceBottom = tTopSmoothed - tBottomSmoothed;
diffTAB_demeaned = diffTempAllBottom - mean(diffTempAllBottom);

%% find locations of upcrossings and downcrossings
for i = 1:(length(diffTAB_demeaned)-1)
    upcrossing(i) = diffTAB_demeaned(i+1) > 0 && diffTAB_demeaned(i) < 0;
    downcrossing(i) = diffTAB_demeaned(i+1) < 0 && diffTAB_demeaned(i) > 0;
end
idxUpcrossing = find(upcrossing == 1);
idxDowncrossing = find(downcrossing == 1);

%% find end of bore
% check if last zero crossing is a downcrossing (meaning current time is
% between bores)
if idxUpcrossing(end) < idxDowncrossing(end)
    diffFlipped = fliplr(diffTAB_demeaned(idxUpcrossing(end):idxDowncrossing(end)));
    diffdiffFlipped = movmean(diff(diffFlipped),100);
    idx = find(diffdiffFlipped < 0, 1, 'first');
    idxBoreEnd = idxUpcrossing(end) + length(diffFlipped) - idx;

    tempDiffMean = mean(diffTempAllBottom(idxUpcrossing(end):idxDowncrossing(end)));
    tempDiffSurface = mean(diffTempSurfaceBottom(idxUpcrossing(end):idxDowncrossing(end)));
    boreEndTime = timeClipped(idxBoreEnd);
    boreHours = (timeClipped(idxDowncrossing(end)) - timeClipped(idxUpcrossing(end)))*24;
elseif idxUpcrossing(end) >= idxDowncrossing(end)
    tempDiffMean = mean(diffTempAllBottom(idxUpcrossing(end):end));
    tempDiffSurface = mean(diffTempSurfaceBottom(idxUpcrossing(end):end));
    boreEndTime = [];
    boreHours = [];
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. mens. Soc. linn. Lyon 7: 211 (1938)

#### Original name
Collybia trigonospora (Bres.) Mussat, 1900

### Remarks
null


text:
package net.uncontended.precipice.pattern;

import net.uncontended.precipice.GuardRail;
import net.uncontended.precipice.Precipice;
import net.uncontended.precipice.metrics.counts.WritableCounts;
import net.uncontended.precipice.rejected.Rejected;
import net.uncontended.precipice.result.TimeoutableResult;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class PatternTest {

    @Mock
    private PatternStrategy strategy;
    @Mock
    private Precipice<TimeoutableResult, Rejected> precipice1;
    @Mock
    private Precipice<TimeoutableResult, Rejected> precipice2;
    @Mock
    private Precipice<TimeoutableResult, Rejected> precipice3;
    @Mock
    private GuardRail<TimeoutableResult, Rejected> guardRail1;
    @Mock
    private GuardRail<TimeoutableResult, Rejected> guardRail2;
    @Mock
    private GuardRail<TimeoutableResult, Rejected> guardRail3;

    private Pattern<TimeoutableResult, Precipice<TimeoutableResult, Rejected>> pattern;
    private long nanoTime = 10L;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        List<Precipice<TimeoutableResult, Rejected>> controllables = Arrays.asList(precipice1, precipice2, precipice3);
        pattern = new Pattern<>(controllables, strategy);

        int submissionCount = 2;
        when(strategy.acquireCount()).thenReturn(submissionCount);
        when(precipice1.guardRail()).thenReturn(guardRail1);
        when(precipice2.guardRail()).thenReturn(guardRail2);
        when(precipice3.guardRail()).thenReturn(guardRail3);
    }

    @Test
    public void getAllReturnsAListOfAllTheChildPrecipicesInOrder() {
        List<Precipice<TimeoutableResult, Rejected>> all = pattern.getAllPrecipices();
        assertEquals(3, all.size());
        assertEquals(precipice1, all.get(0));
        assertEquals(precipice2, all.get(1));
        assertEquals(precipice3, all.get(2));
    }

    @Test
    public void getReturnsCorrectPrecipices() {
        Integer[] indices = {0, 1, 2};
        SingleReaderArrayIterable iterable = getIterable(indices);

        when(strategy.nextIndices()).thenReturn(iterable);
        when(guardRail1.acquirePermits(1L, nanoTime)).thenReturn(null);
        when(guardRail2.acquirePermits(1L, nanoTime)).thenReturn(null);
        Sequence<Precipice<TimeoutableResult, Rejected>> all = pattern.getPrecipices(1L, nanoTime);

        List<Precipice<TimeoutableResult, Rejected>> controllableList = new ArrayList<>();
        for (Precipice<TimeoutableResult, Rejected> item : all) {
            controllableList.add(item);
        }

        verifyZeroInteractions(precipice3);
        verifyZeroInteractions(guardRail3);

        assertEquals(2, controllableList.size());
        assertSame(precipice1, controllableList.get(0));
        assertSame(precipice2, controllableList.get(1));
    }

    @Test
    public void getAcquiresPermitsInTheCorrectOrder() {
        Integer[] indices = {2, 0, 1};
        WritableCounts<Rejected> metrics = mock(WritableCounts.class);

        when(strategy.nextIndices()).thenReturn(getIterable(indices));
        when(guardRail3.acquirePermits(1L, nanoTime)).thenReturn(null);
        when(guardRail1.acquirePermits(1L, nanoTime)).thenReturn(Rejected.CIRCUIT_OPEN);
        when(guardRail2.acquirePermits(1L, nanoTime)).thenReturn(null);
        when(guardRail1.getRejectedCounts()).thenReturn(metrics);

        Sequence<Precipice<TimeoutableResult, Rejected>> all = pattern.getPrecipices(1L, nanoTime);

        List<Precipice<TimeoutableResult, Rejected>> controllableList = new ArrayList<>();
        for (Precipice<TimeoutableResult, Rejected> item : all) {
            controllableList.add(item);
        }

        assertEquals(2, controllableList.size());
        assertSame(precipice3, controllableList.get(0));
        assertSame(precipice2, controllableList.get(1));
    }

    @Test
    public void getOnlyReturnsTheNumberOfPrecipicesThatAreAvailable() {
        Integer[] indices = {2, 0, 1};

        when(strategy.nextIndices()).thenReturn(getIterable(indices));
        when(guardRail3.acquirePermits(1L, nanoTime)).thenReturn(Rejected.MAX_CONCURRENCY_LEVEL_EXCEEDED);
        when(guardRail1.acquirePermits(1L, nanoTime)).thenReturn(Rejected.CIRCUIT_OPEN);
        when(guardRail2.acquirePermits(1L, nanoTime)).thenReturn(null);

        Sequence<Precipice<TimeoutableResult, Rejected>> all = pattern.getPrecipices(1L, nanoTime);

        List<Precipice<TimeoutableResult, Rejected>> controllableList = new ArrayList<>();
        for (Precipice<TimeoutableResult, Rejected> item : all) {
            controllableList.add(item);
        }

        assertEquals(1, controllableList.size());
        assertSame(precipice2, controllableList.get(0));
    }

    @Test
    public void threadLocalFactoryMeansIteratorIsReusedAndThreadLocal() throws Exception {
        List<Precipice<TimeoutableResult, Rejected>> controllables = Arrays.asList(precipice1, precipice2, precipice3);

        pattern = new Pattern<>(controllables, strategy, new ThreadLocalSequenceFactory<Precipice<TimeoutableResult, Rejected>>());

        final Integer[] indices = {2, 0, 1};
        Executor executor = Executors.newCachedThreadPool();

        when(strategy.nextIndices()).thenAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return getIterable(indices);
            }
        });
        when(guardRail3.acquirePermits(1L, nanoTime)).thenReturn(null);
        when(guardRail1.acquirePermits(1L, nanoTime)).thenReturn(null);
        when(guardRail2.acquirePermits(1L, nanoTime)).thenReturn(null);

        final Sequence<Precipice<TimeoutableResult, Rejected>> firstSequence = pattern.getPrecipices(1L, nanoTime);
        for (int i = 0; i < 10; ++i) {
            Sequence<Precipice<TimeoutableResult, Rejected>> sequence = pattern.getPrecipices(1L, nanoTime);
            assertSame("Should be the same reference.", firstSequence, sequence);
        }

        final ConcurrentHashMap<Sequence<Precipice<TimeoutableResult, Rejected>>, AtomicInteger> sequenceMap = new ConcurrentHashMap<>();
        final CountDownLatch latch = new CountDownLatch(5);
        final CountDownLatch doneLatch = new CountDownLatch(5);

        for (int i = 0; i < 5; ++i) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    Sequence<Precipice<TimeoutableResult, Rejected>> first = pattern.getPrecipices(1L, nanoTime);
                    if (sequenceMap.containsKey(first)) {
                        fail("Set should not already contain this sequence.");
                    }
                    sequenceMap.put(first, new AtomicInteger(0));

                    latch.countDown();
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    for (int i = 0; i < 10; ++i) {
                        Sequence<Precipice<TimeoutableResult, Rejected>> sequence = pattern.getPrecipices(1L, nanoTime);
                        sequenceMap.get(sequence).incrementAndGet();
                        assertSame("Should be the same reference.", first, sequence);
                    }
                    doneLatch.countDown();
                }
            });
        }

        doneLatch.await();

        assertEquals(5, sequenceMap.size());
        for (AtomicInteger count : sequenceMap.values()) {
            assertEquals(10, count.get());
        }
    }

    private static SingleReaderArrayIterable getIterable(Integer[] indices) {
        SingleReaderArrayIterable iterable = new SingleReaderArrayIterable(indices.length);
        Integer[] indices1 = iterable.getIndices();
        System.arraycopy(indices, 0, indices1, 0, indices.length);
        return iterable;
    }
}


text:
using UnityEngine;
using System.Collections;

namespace NewtonVR
{
    public class NVRHead : MonoBehaviour
    {
        public virtual void Initialize()
        {

        }
    }
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js Test Suite        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */
package org.scalajs.testsuite.javalib

import java.{util => ju, lang => jl}

import org.scalajs.jasminetest.JasmineTest
import scala.collection.JavaConversions._

trait CollectionTest extends JasmineTest with ExpectExceptions {

  def testCollectionApi(factory: CollectionFactory): Unit = {
    it("should store strings") {
      val coll = factory.empty[String]

      expect(coll.size()).toEqual(0)
      coll.add("one")
      expect(coll.size()).toEqual(1)

      coll.clear()
      expect(coll.size()).toEqual(0)
      expect(coll.addAll(Seq.empty[String])).toBeFalsy
      expect(coll.size()).toEqual(0)

      expect(coll.addAll(Seq("one"))).toBeTruthy
      expect(coll.size()).toEqual(1)

      coll.clear()
      expect(coll.addAll(Seq("one", "two", "one"))).toBeTruthy
      expect(coll.size() >= 1).toBeTruthy
    }

    it("should store integers") {
      val coll = factory.empty[Int]

      expect(coll.size()).toEqual(0)
      coll.add(1)
      expect(coll.size()).toEqual(1)

      coll.clear()
      expect(coll.size()).toEqual(0)
      expect(coll.addAll(Seq.empty[Int])).toBeFalsy
      expect(coll.size()).toEqual(0)

      expect(coll.addAll(Seq(1))).toBeTruthy
      expect(coll.size()).toEqual(1)

      coll.clear()
      expect(coll.addAll(Seq(1, 2, 1))).toBeTruthy
      expect(coll.size() >= 1).toBeTruthy
    }

    it("should store doubles") {
      val coll = factory.empty[Double]

      expect(coll.size()).toEqual(0)
      coll.add(1.234)
      expect(coll.size()).toEqual(1)

      coll.clear()
      expect(coll.size()).toEqual(0)
      expect(coll.addAll(Seq.empty[Double])).toBeFalsy
      expect(coll.size()).toEqual(0)

      expect(coll.addAll(Seq(1.234))).toBeTruthy
      expect(coll.size()).toEqual(1)

      coll.clear()
      expect(coll.addAll(Seq(1.234, 2.345, 1.234))).toBeTruthy
      expect(coll.size() >= 1).toBeTruthy

      coll.clear()
      coll.add(+0.0)
      expect(coll.contains(+0.0)).toBeTruthy
      expect(coll.contains(-0.0)).toBeFalsy

      coll.clear()
      coll.add(-0.0)
      expect(coll.contains(+0.0)).toBeFalsy
      expect(coll.contains(-0.0)).toBeTruthy

      coll.clear()
      coll.add(Double.NaN)
      expect(coll.size()).toEqual(1)
      expect(coll.contains(Double.NaN)).toBeTruthy
    }

    it("should store custom objects") {
      case class TestObj(num: Int) extends jl.Comparable[TestObj] {
        def compareTo(o: TestObj): Int =
          o.num.compareTo(num)
      }

      val coll = factory.empty[TestObj]

      coll.add(TestObj(100))
      expect(coll.size()).toEqual(1)
      expect(coll.contains(TestObj(100))).toBeTruthy
      expect(coll.contains(TestObj(200))).toBeFalsy
    }

    it("should remove stored elements") {
      val coll = factory.empty[String]

      coll.add("one")
      coll.add("two")
      coll.add("three")
      coll.add("two")

      val initialSize = coll.size()
      expect(coll.remove("four")).toBeFalsy
      expect(coll.size()).toEqual(initialSize)
      expect(coll.remove("two")).toBeTruthy
      expect(coll.size()).toEqual(initialSize - 1)
      expect(coll.remove("one")).toBeTruthy
      expect(coll.size()).toEqual(initialSize - 2)
    }

    it("should remove stored elements on double corner cases") {
      val coll = factory.empty[Double]

      coll.add(1.234)
      coll.add(2.345)
      coll.add(Double.NaN)
      coll.add(+0.0)
      coll.add(-0.0)

      // coll == ArrayCollection(1.234, 2.345, NaN, +0.0, -0.0)
      expect(coll.remove(Double.NaN)).toBeTruthy
      // coll == ArrayCollection(1.234, 2.345, +0.0, -0.0)
      expect(coll.size()).toEqual(4)
      expect(coll.remove(2.345)).toBeTruthy
      // coll == ArrayCollection(1.234, +0.0, -0.0)
      expect(coll.size()).toEqual(3)
      expect(coll.remove(1.234)).toBeTruthy
      // coll == ArrayCollection(+0.0, -0.0)
      expect(coll.size()).toEqual(2)
      expect(coll.remove(-0.0)).toBeTruthy
      // coll == ArrayCollection(NaN, +0.0)
      expect(coll.size()).toEqual(1)

      coll.clear()

      expect(coll.isEmpty).toBeTruthy
    }

    it("should be cleared with one operation") {
      val coll = factory.empty[String]

      coll.add("one")
      coll.add("two")
      expect(coll.size).toEqual(2)
      coll.clear()
      expect(coll.size).toEqual(0)
    }

    it("should check contained presence") {
      val coll = factory.empty[String]

      coll.add("one")
      expect(coll.contains("one")).toBeTruthy
      expect(coll.contains("two")).toBeFalsy
      if (factory.allowsNullElementQuery)
        expect(coll.contains(null)).toBeFalsy
      else
        expectThrows[Exception](coll.contains(null))
    }

    it("should check contained presence for double corner cases") {
      val coll = factory.empty[Double]

      coll.add(-0.0)
      expect(coll.contains(-0.0)).toBeTruthy
      expect(coll.contains(+0.0)).toBeFalsy

      coll.clear()

      coll.add(+0.0)
      expect(coll.contains(-0.0)).toBeFalsy
      expect(coll.contains(+0.0)).toBeTruthy
    }

    it("should give proper iterator over elements") {
      val coll = factory.empty[String]
      coll.add("one")
      coll.add("two")
      coll.add("three")
      coll.add("three")
      coll.add("three")

      expect(Set("one", "two", "three") == coll.iterator().toSet).toBeTruthy
    }

  }
}

object CollectionFactory {
  def allFactories: Iterator[CollectionFactory] =
    ListFactory.allFactories ++ SetFactory.allFactories
}

trait CollectionFactory {
  def implementationName: String
  def empty[E]: ju.Collection[E]
  def allowsMutationThroughIterator: Boolean = true
  def allowsNullElementQuery: Boolean = true
}


text:
package iterator_test

import (
	"errors"
	"testing"

	"github.com/kezhuw/leveldb/internal/iterator"
	"github.com/stretchr/testify/suite"
)

func okCleanup() error {
	return nil
}

func newErrorCleanup(err error) func() error {
	return func() error {
		return err
	}
}

type WrappedOkIteratorTestSuite struct {
	suite.Suite
	wrappedIterator iterator.Iterator
}

var _ suite.SetupTestSuite = (*WrappedOkIteratorTestSuite)(nil)

func (suite *WrappedOkIteratorTestSuite) SetupTest() {
	suite.wrappedIterator = iterator.Empty()
}

func (suite *WrappedOkIteratorTestSuite) TestNilCleanup() {
	require := suite.Require()
	it := iterator.WithCleanup(suite.wrappedIterator, nil)
	require.Same(suite.wrappedIterator, it)
}

func (suite *WrappedOkIteratorTestSuite) TestOkCleanup() {
	require := suite.Require()
	it := iterator.WithCleanup(suite.wrappedIterator, okCleanup)
	require.NoError(it.Close())
}

func (suite *WrappedOkIteratorTestSuite) TestErrorCleanup() {
	require := suite.Require()
	err := errors.New("cleanup error")
	it := iterator.WithCleanup(suite.wrappedIterator, newErrorCleanup(err))
	require.Same(err, it.Close())
}

func TestCleanupIteratorWrappedOkIterator(t *testing.T) {
	suite.Run(t, new(WrappedOkIteratorTestSuite))
}

type WrappedErrorIteratorTestSuite struct {
	suite.Suite
	err             error
	wrappedIterator iterator.Iterator
}

var _ suite.SetupTestSuite = (*WrappedErrorIteratorTestSuite)(nil)

func (suite *WrappedErrorIteratorTestSuite) SetupTest() {
	suite.err = errors.New("wrapped error")
	suite.wrappedIterator = iterator.Error(suite.err)
}

func (suite *WrappedErrorIteratorTestSuite) TestNilCleanup() {
	require := suite.Require()
	it := iterator.WithCleanup(suite.wrappedIterator, nil)
	require.Same(suite.wrappedIterator, it)
}

func (suite *WrappedErrorIteratorTestSuite) TestOkCleanup() {
	require := suite.Require()
	it := iterator.WithCleanup(suite.wrappedIterator, okCleanup)
	require.Same(suite.err, it.Close())
}

func (suite *WrappedErrorIteratorTestSuite) TestErrorCleanup() {
	require := suite.Require()
	err := errors.New("cleanup error")
	it := iterator.WithCleanup(suite.wrappedIterator, newErrorCleanup(err))
	require.Same(suite.err, it.Close())
}

func TestCleanupIteratorWrappedErrorIterator(t *testing.T) {
	suite.Run(t, new(WrappedErrorIteratorTestSuite))
}


text:
import os
from setuptools import setup, find_packages

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-richcontentblocks',
    version='0.4.4',
    packages=['richcontentblocks'],
    include_package_data=True,
    license='MIT License',
    description='Simple (rich) content blocks for use on front end templates. With admin tool.',
    long_description=README,
    author='Django Radonich-Camp',
    author_email='django@emergeinteractive.com',
    url = 'https://github.com/django-emerge/django-richcontentblocks',
    download_url = 'https://github.com/django-emerge/django-richcontentblocks/tarball/0.4.4',
    install_requires=[
        'django-ckeditor>=4.5.1'
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


text:
package com.baidubce.services.moladb.model;

import com.baidubce.auth.BceCredentials;
import com.baidubce.model.AbstractBceRequest;

/**
 * Represents the input of a ListTables operation.
 */
public class ListTablesRequest extends AbstractBceRequest {
    /**
     * Constructs a new ListTablesRequest object.
     * Callers should use the setter or fluent setter (with...) methods to
     * initialize any additional object members.
     */
    public ListTablesRequest() {
    }

    public ListTablesRequest withRequestCredentials(BceCredentials credentials) {
        this.setRequestCredentials(credentials);
        return this;
    }
}


text:
import mock
from mock import patch
import unittest
from vnc_api.vnc_api import *
from svc_monitor.instance_manager import NetworkNamespaceManager
from svc_monitor.config_db import *
import test_common_utils as test_utils

class SnatInstanceManager(unittest.TestCase):
    def setUp(self):
        InstanceIpSM._cassandra = mock.MagicMock()
        InstanceIpSM._cassandra.object_read = test_utils.iip_db_read
        VirtualMachineInterfaceSM._cassandra = mock.MagicMock()
        VirtualMachineInterfaceSM._cassandra.object_read = test_utils.vmi_db_read
        VirtualMachineSM._cassandra = mock.MagicMock()
        VirtualMachineSM._cassandra.object_read = test_utils.vm_db_read
        VirtualRouterSM._cassandra = mock.MagicMock()
        VirtualRouterSM._cassandra.object_read = test_utils.vr_db_read
        VirtualNetworkSM._cassandra = mock.MagicMock()
        VirtualNetworkSM._cassandra.object_read = test_utils.vn_db_read

        self.mocked_vnc = mock.MagicMock()
        self.mocked_vnc.fq_name_to_id = test_utils.get_vn_id_for_fq_name
        self.mocked_vnc.virtual_machine_interface_create = test_utils.vmi_create
        self.mocked_vnc.virtual_network_create = test_utils.vn_create
        self.mocked_vnc.instance_ip_create = test_utils.iip_create

        self.mocked_scheduler = mock.MagicMock()
        self.mocked_scheduler.schedule = mock.Mock(return_value=('fake-virtual-router'))

        self.nova_mock = mock.MagicMock()
        self.mocked_db = mock.MagicMock()

        self.mocked_args = mock.MagicMock()
        self.mocked_args.availability_zone = None

        self.mocked_manager = mock.MagicMock()

        self.netns_manager = NetworkNamespaceManager(
            db=self.mocked_db, logger=mock.MagicMock(),
            vnc_lib=self.mocked_vnc, vrouter_scheduler=self.mocked_scheduler,
            nova_client=self.nova_mock, agent_manager=self.mocked_manager,
            args=self.mocked_args)

    def tearDown(self):
        ServiceTemplateSM.reset()
        ServiceInstanceSM.reset()
        InstanceIpSM.reset()
        del InstanceIpSM._cassandra
        VirtualMachineInterfaceSM.reset()
        del VirtualMachineInterfaceSM._cassandra
        VirtualMachineSM.reset()
        del VirtualMachineSM._cassandra
        VirtualRouterSM.reset()
        del VirtualRouterSM._cassandra
        VirtualNetworkSM.reset()
        del VirtualNetworkSM._cassandra

    def test_snat_instance_create(self):
        test_utils.create_test_project('fake-domain:fake-project')
        test_utils.create_test_virtual_network('fake-domain:fake-project:public-vn')
        test_utils.create_test_virtual_network('fake-domain:fake-project:fake-vn-uuid')
        test_utils.create_test_security_group('fake-domain:fake-project:default')
        test_utils.create_test_virtual_router('fake-virtual-router')

        st = test_utils.create_test_st(name='snat-template',
            virt_type='network-namespace',
            intf_list=[['right', True], ['left', True]])
        si = test_utils.create_test_si(name='snat-instance', count=2,
            intf_list=['public-vn', 'fake-vn-uuid'])

        self.netns_manager.create_service(st, si)
        self.mocked_vnc.virtual_machine_create.assert_any_call(test_utils.VMObjMatcher(1))
        self.mocked_vnc.virtual_machine_create.assert_any_call(test_utils.VMObjMatcher(2))
        self.assertEqual(si.vn_info[1]['net-id'], 'fake-domain:fake-project:fake-vn-uuid')

    def test_snat_instance_delete(self):
        def create_fake_virtual_machine(fq_name_str):
            vm_obj = {}
            vm_obj['fq_name'] = fq_name_str.split(':')
            vm_obj['uuid'] = fq_name_str
            vm_obj['display_name'] = fq_name_str
            vm = VirtualMachineSM.locate(vm_obj['uuid'], vm_obj)
            vm.proj_fq_name = ['fake-domain', 'fake-project']
            vm.virtual_machine_interfaces = set(['fake-vmi-uuid1', 'fake-vmi-uuid2', 'fake-vmi-uuid3'])
            vm.virtual_router = 'fake-vr-uuid'
            return vm

        mocked_vr = mock.MagicMock()
        mocked_vr.uuid = 'fake-vr-uuid'

        self.netns_manager._vnc_lib.virtual_router_read.\
            return_value = mocked_vr

        vm = create_fake_virtual_machine('fake-vm-uuid')
        self.netns_manager.delete_service(vm)

        self.netns_manager._vnc_lib.virtual_machine_delete\
            .assert_called_with(id='fake-vm-uuid')
        self.netns_manager._vnc_lib.ref_update.\
                assert_called_with('virtual-router', 'fake-vr-uuid',
                        'virtual-machine', 'fake-vm-uuid', None, 'DELETE')