text:
package org.andengine.input.sensor.orientation;

import java.util.Arrays;

import org.andengine.input.sensor.BaseSensorData;
import org.andengine.util.math.MathConstants;

import android.hardware.SensorManager;
import android.view.Surface;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 11:30:33 - 25.05.2010
 */
public class OrientationData extends BaseSensorData {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private final float[] mAccelerationValues = new float[3];
	private final float[] mMagneticFieldValues = new float[3];
	private final float[] mRotationMatrix = new float[16];

	private int mMagneticFieldAccuracy;

	// ===========================================================
	// Constructors
	// ===========================================================

	public OrientationData(final int pDisplayRotation) {
		super(3, pDisplayRotation);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public float getRoll() {
		return super.mValues[SensorManager.DATA_Z];
	}

	public float getPitch() {
		return super.mValues[SensorManager.DATA_Y];
	}

	public float getYaw() {
		return super.mValues[SensorManager.DATA_X];
	}

	@Override
	@Deprecated
	public void setValues(final float[] pValues) {
		super.setValues(pValues);
	}

	@Override
	@Deprecated
	public void setAccuracy(final int pAccuracy) {
		super.setAccuracy(pAccuracy);
	}

	public void setAccelerationValues(final float[] pValues) {
		System.arraycopy(pValues, 0, this.mAccelerationValues, 0, pValues.length);
		this.updateOrientation();
	}

	public void setMagneticFieldValues(final float[] pValues) {
		System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length);
		this.updateOrientation();
	}

	private void updateOrientation() {
		SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerationValues, this.mMagneticFieldValues);

		// TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons.
		switch(this.mDisplayRotation) {
			case Surface.ROTATION_0:
				/* Nothing. */
				break;
			case Surface.ROTATION_90:
				SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix);
				break;
//			case Surface.ROTATION_180:
//				SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
//				break;
//			case Surface.ROTATION_270:
//				SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
//				break;
		}

		final float[] values = this.mValues;
		SensorManager.getOrientation(this.mRotationMatrix, values);

		for(int i = values.length - 1; i >= 0; i--) {
			values[i] = values[i] * MathConstants.RAD_TO_DEG;
		}
	}

	public int getAccelerationAccuracy() {
		return this.getAccuracy();
	}

	public void setAccelerationAccuracy(final int pAccelerationAccuracy) {
		super.setAccuracy(pAccelerationAccuracy);
	}

	public int getMagneticFieldAccuracy() {
		return this.mMagneticFieldAccuracy;
	}

	public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) {
		this.mMagneticFieldAccuracy = pMagneticFieldAccuracy;
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public String toString() {
		return "Orientation: " + Arrays.toString(this.mValues);
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
namespace remoting {

namespace {

struct EnumDesktopShapeData {
  EnumDesktopShapeData()
    : window_region(CreateRectRgn(0, 0, 0, 0)),
      desktop_region(CreateRectRgn(0, 0, 0, 0)) {
  }
  base::win::ScopedRegion window_region;
  base::win::ScopedRegion desktop_region;
};

class DesktopShapeTrackerWin : public DesktopShapeTracker {
 public:
  DesktopShapeTrackerWin();
  virtual ~DesktopShapeTrackerWin();

  virtual void RefreshDesktopShape();
  virtual const webrtc::DesktopRegion& desktop_shape();

 private:
  // Callback passed to EnumWindows() to enumerate windows.
  static BOOL CALLBACK EnumWindowsCallback(HWND window, LPARAM lparam);

  // The most recently calculated desktop region.
  webrtc::DesktopRegion desktop_shape_;

  // Stored to compare with newly calculated desktop shapes, to avoid converting
  // to an DesktopRegion unless the shape has actually changed.
  base::win::ScopedRegion old_desktop_region_;

  DISALLOW_COPY_AND_ASSIGN(DesktopShapeTrackerWin);
};

DesktopShapeTrackerWin::DesktopShapeTrackerWin()
  : old_desktop_region_(CreateRectRgn(0, 0, 0, 0)) {
}

DesktopShapeTrackerWin::~DesktopShapeTrackerWin() {
}

void DesktopShapeTrackerWin::RefreshDesktopShape() {
  // Accumulate a new desktop shape from current window positions.
  scoped_ptr<EnumDesktopShapeData> shape_data(new EnumDesktopShapeData);
  if (!EnumWindows(EnumWindowsCallback, (LPARAM)shape_data.get())) {
    PLOG(ERROR) << "Failed to enumerate windows";
    desktop_shape_.Clear();
    return;
  }

  // If the shape has changed, refresh |desktop_shape_|.
  if (!EqualRgn(shape_data->desktop_region, old_desktop_region_)) {
    old_desktop_region_.Set(shape_data->desktop_region.release());

    // Determine the size of output buffer required to receive the region.
    DWORD bytes_size = GetRegionData(old_desktop_region_, 0, NULL);
    CHECK(bytes_size != 0);

    // Fetch the Windows RECTs that comprise the region.
    std::vector<char> buffer(bytes_size);
    LPRGNDATA region_data = reinterpret_cast<LPRGNDATA>(buffer.data());
    DWORD result = GetRegionData(old_desktop_region_, bytes_size, region_data);
    CHECK(result == bytes_size);
    const LPRECT rects = reinterpret_cast<LPRECT>(&region_data->Buffer[0]);

    // Reset |desktop_shape_| and add new rectangles into it.
    desktop_shape_.Clear();
    for (size_t i = 0; i < region_data->rdh.nCount; ++i) {
      desktop_shape_.AddRect(webrtc::DesktopRect::MakeLTRB(
          rects[i].left, rects[i].top, rects[i].right, rects[i].bottom));
    }
  }
}

const webrtc::DesktopRegion& DesktopShapeTrackerWin::desktop_shape() {
  return desktop_shape_;
}

// static
BOOL DesktopShapeTrackerWin::EnumWindowsCallback(HWND window, LPARAM lparam) {
  EnumDesktopShapeData* data = reinterpret_cast<EnumDesktopShapeData*>(lparam);
  HRGN desktop_region = data->desktop_region.Get();
  HRGN window_region = data->window_region.Get();

  // Is the window visible?
  if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))
    return TRUE;

  // Find the desktop position of the window (including non-client-area).
  RECT window_rect;
  if (!GetWindowRect(window, &window_rect))
    return TRUE;

  // Find the shape of the window, in window coords.
  // GetWindowRgn will overwrite the current contents of |window_region|.
  if (GetWindowRgn(window, window_region) != ERROR) {
    // Translate the window region into desktop coordinates.
    OffsetRgn(window_region, window_rect.left, window_rect.top);
  } else {
    // Window has no shape, or an error occurred, so assume it's rectangular.
    SetRectRgn(window_region, window_rect.left, window_rect.top,
               window_rect.right, window_rect.bottom);
  }

  // TODO(wez): If the window is maximized then we should clip it to the
  // display on which it is maximized.
  //  if (IsZoomed(window))
  //    CombineRgn(window_region, window_region, screen_region, RGN_AND);

  // Merge the window region into the accumulated desktop region.  Window
  // regions are combined together before converting the result to
  // DesktopRegion. It assumed that this approach is more efficient than
  // converting each window region individually.
  CombineRgn(desktop_region, desktop_region, window_region, RGN_OR);

  return TRUE;
}

} // namespace

// static
scoped_ptr<DesktopShapeTracker> DesktopShapeTracker::Create(
    webrtc::DesktopCaptureOptions options) {
  return scoped_ptr<DesktopShapeTracker>(new DesktopShapeTrackerWin());
}

}  // namespace remoting

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. R. bot. Gdns Peradeniya 7: 303 (1922)

#### Original name
Sphaerella vernoniae Petch

### Remarks
null


text:
<?php

namespace Doctrine\ORM\Internal;

/**
 * The CommitOrderCalculator is used by the UnitOfWork to sort out the
 * correct order in which changes to entities need to be persisted.
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 */
class CommitOrderCalculator
{
    const NOT_VISITED = 1;
    const IN_PROGRESS = 2;
    const VISITED = 3;

    private $_nodeStates = array();
    private $_classes = array(); // The nodes to sort
    private $_relatedClasses = array();
    private $_sorted = array();

    /**
     * Clears the current graph.
     *
     * @return void
     */
    public function clear()
    {
        $this->_classes =
        $this->_relatedClasses = array();
    }

    /**
     * Gets a valid commit order for all current nodes.
     *
     * Uses a depth-first search (DFS) to traverse the graph.
     * The desired topological sorting is the reverse postorder of these searches.
     *
     * @return array The list of ordered classes.
     */
    public function getCommitOrder()
    {
        // Check whether we need to do anything. 0 or 1 node is easy.
        $nodeCount = count($this->_classes);
        if ($nodeCount == 0) {
            return array();
        } else if ($nodeCount == 1) {
            return array_values($this->_classes);
        }

        // Init
        foreach ($this->_classes as $node) {
            $this->_nodeStates[$node->name] = self::NOT_VISITED;
        }

        // Go
        foreach ($this->_classes as $node) {
            if ($this->_nodeStates[$node->name] == self::NOT_VISITED) {
                $this->_visitNode($node);
            }
        }

        $sorted = array_reverse($this->_sorted);

        $this->_sorted = $this->_nodeStates = array();

        return $sorted;
    }

    private function _visitNode($node)
    {
        $this->_nodeStates[$node->name] = self::IN_PROGRESS;

        if (isset($this->_relatedClasses[$node->name])) {
            foreach ($this->_relatedClasses[$node->name] as $relatedNode) {
                if ($this->_nodeStates[$relatedNode->name] == self::NOT_VISITED) {
                    $this->_visitNode($relatedNode);
                }
            }
        }

        $this->_nodeStates[$node->name] = self::VISITED;
        $this->_sorted[] = $node;
    }

    public function addDependency($fromClass, $toClass)
    {
        $this->_relatedClasses[$fromClass->name][] = $toClass;
    }

    public function hasClass($className)
    {
        return isset($this->_classes[$className]);
    }

    public function addClass($class)
    {
        $this->_classes[$class->name] = $class;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.daw.service.implementation;

import com.google.gson.Gson;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.daw.bean.implementation.PusuarioBean;
import net.daw.bean.implementation.ReplyBean;
import net.daw.bean.implementation.AnaliticaBean;
import net.daw.connection.publicinterface.ConnectionInterface;
import net.daw.dao.implementation.AnaliticaDao;
import net.daw.helper.statics.AppConfigurationHelper;
import static net.daw.helper.statics.AppConfigurationHelper.getSourceConnection;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.JsonMessage;
import net.daw.helper.statics.Log4j;
import net.daw.helper.statics.ParameterCook;
import net.daw.service.publicinterface.TableServiceInterface;
import net.daw.service.publicinterface.ViewServiceInterface;

public class AnaliticaService implements TableServiceInterface, ViewServiceInterface {

    protected HttpServletRequest oRequest = null;

    public AnaliticaService(HttpServletRequest request) {
        oRequest = request;
    }

    private Boolean checkpermission(String strMethodName) throws Exception {
        PusuarioBean oPuserBean = (PusuarioBean) oRequest.getSession().getAttribute("userBean");
        if (oPuserBean != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ReplyBean getcount() throws Exception {
        if (this.checkpermission("getcount")) {
            String data = null;
            ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest));
            Connection oConnection = null;
            ConnectionInterface oDataConnectionSource = null;
            try {

                oDataConnectionSource = getSourceConnection();
                oConnection = oDataConnectionSource.newConnection();
                AnaliticaDao oAnaliticaDao = new AnaliticaDao(oConnection, (PusuarioBean) oRequest.getSession().getAttribute("userBean"), null);
                data = JsonMessage.getJsonExpression(200, Long.toString(oAnaliticaDao.getCount(alFilter)));
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oConnection != null) {
                    oConnection.close();
                }
                if (oDataConnectionSource != null) {
                    oDataConnectionSource.disposeConnection();
                }
            }
            return new ReplyBean(200, data);
        } else {
            return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
        }
    }

    @Override
    public ReplyBean get() throws Exception {
        if (this.checkpermission("get")) {
            int id = ParameterCook.prepareId(oRequest);
            String data = null;
            Connection oConnection = null;
            ConnectionInterface oDataConnectionSource = null;
            try {
                oDataConnectionSource = getSourceConnection();
                oConnection = oDataConnectionSource.newConnection();
                AnaliticaDao oAnaliticaDao = new AnaliticaDao(oConnection, (PusuarioBean) oRequest.getSession().getAttribute("userBean"), null);
                AnaliticaBean oAnaliticaBean = new AnaliticaBean(id);
                oAnaliticaBean = oAnaliticaDao.get(oAnaliticaBean, AppConfigurationHelper.getJsonMsgDepth());
                Gson gson = AppConfigurationHelper.getGson();
                data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(oAnaliticaBean));
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oConnection != null) {
                    oConnection.close();
                }
                if (oDataConnectionSource != null) {
                    oDataConnectionSource.disposeConnection();
                }
            }
            return new ReplyBean(200, data);
        } else {
            return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
        }
    }

    @Override
    public ReplyBean getall() throws Exception {
        if (this.checkpermission("getall")) {
            HashMap<String, String> hmOrder = ParameterCook.getOrderParams(ParameterCook.prepareOrder(oRequest));
            ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest));
            String data = null;
            Connection oConnection = null;
            ConnectionInterface oDataConnectionSource = null;
            try {
                oDataConnectionSource = getSourceConnection();
                oConnection = oDataConnectionSource.newConnection();
                AnaliticaDao oAnaliticaDao = new AnaliticaDao(oConnection, (PusuarioBean) oRequest.getSession().getAttribute("userBean"), null);
                ArrayList<AnaliticaBean> arrBeans = oAnaliticaDao.getAll(alFilter, hmOrder, AppConfigurationHelper.getJsonMsgDepth());
                data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(arrBeans));
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oConnection != null) {
                    oConnection.close();
                }
                if (oDataConnectionSource != null) {
                    oDataConnectionSource.disposeConnection();
                }
            }
            return new ReplyBean(200, data);
        } else {
            return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
        }
    }

    @Override
    public ReplyBean getpage() throws Exception {
        if (this.checkpermission("getpage")) {
            int intRegsPerPag = ParameterCook.prepareRpp(oRequest);
            int intPage = ParameterCook.preparePage(oRequest);
            HashMap<String, String> hmOrder = ParameterCook.getOrderParams(ParameterCook.prepareOrder(oRequest));
            ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest));
            String data = null;
            Connection oConnection = null;
            ConnectionInterface oDataConnectionSource = null;
            try {
                oDataConnectionSource = getSourceConnection();
                oConnection = oDataConnectionSource.newConnection();
                AnaliticaDao oAnaliticaDao = new AnaliticaDao(oConnection, (PusuarioBean) oRequest.getSession().getAttribute("userBean"), null);
                List<AnaliticaBean> arrBeans = oAnaliticaDao.getPage(intRegsPerPag, intPage, alFilter, hmOrder, AppConfigurationHelper.getJsonMsgDepth());
                data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(arrBeans));
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oConnection != null) {
                    oConnection.close();
                }
                if (oDataConnectionSource != null) {
                    oDataConnectionSource.disposeConnection();
                }
            }
            return new ReplyBean(200, data);
        } else {
            return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
        }
    }

    @Override
    public ReplyBean remove() throws Exception {
        if (this.checkpermission("remove")) {
            Integer id = ParameterCook.prepareId(oRequest);
            String data = null;
            Connection oConnection = null;
            ConnectionInterface oDataConnectionSource = null;
            try {
                oDataConnectionSource = getSourceConnection();
                oConnection = oDataConnectionSource.newConnection();
                oConnection.setAutoCommit(false);
                AnaliticaDao oAnaliticaDao = new AnaliticaDao(oConnection, (PusuarioBean) oRequest.getSession().getAttribute("userBean"), null);
                data = JsonMessage.getJsonExpression(200, (String) oAnaliticaDao.remove(id).toString());
                oConnection.commit();
            } catch (Exception ex) {
                if (oConnection != null) {
                    oConnection.rollback();
                }
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oConnection != null) {
                    oConnection.close();
                }
                if (oDataConnectionSource != null) {
                    oDataConnectionSource.disposeConnection();
                }
            }
            return new ReplyBean(200, data);
        } else {
            return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
        }
    }

    @Override
    public ReplyBean set() throws Exception {
        if (this.checkpermission("set")) {
            String jason = ParameterCook.prepareJson(oRequest);
            ReplyBean oReplyBean = new ReplyBean();
            Connection oConnection = null;
            ConnectionInterface oDataConnectionSource = null;
            try {
                oDataConnectionSource = getSourceConnection();
                oConnection = oDataConnectionSource.newConnection();
                oConnection.setAutoCommit(false);
                AnaliticaDao oAnaliticaDao = new AnaliticaDao(oConnection, (PusuarioBean) oRequest.getSession().getAttribute("userBean"), null);
                AnaliticaBean oAnaliticaBean = new AnaliticaBean();
                oAnaliticaBean = AppConfigurationHelper.getGson().fromJson(jason, oAnaliticaBean.getClass());
                if (oAnaliticaBean != null) {
                    Integer iResult = oAnaliticaDao.set(oAnaliticaBean);
                    if (iResult >= 1) {
                        oReplyBean.setCode(200);
                        oReplyBean.setJson(JsonMessage.getJsonExpression(200, iResult.toString()));
                    } else {
                        oReplyBean.setCode(500);
                        oReplyBean.setJson(JsonMessage.getJsonMsg(500, "Error during registry set"));
                    }
                } else {
                    oReplyBean.setCode(500);
                    oReplyBean.setJson(JsonMessage.getJsonMsg(500, "Error during registry set"));
                }
                oConnection.commit();
            } catch (Exception ex) {
                if (oConnection != null) {
                    oConnection.rollback();
                }
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oConnection != null) {
                    oConnection.close();
                }
                if (oDataConnectionSource != null) {
                    oDataConnectionSource.disposeConnection();
                }
            }
            return oReplyBean;
        } else {
            return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
        }
    }

}


text:
/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2009 The Boeing Company
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Guangyu Pei <guangyu.pei@boeing.com>
 */

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/mobility-module.h"
#include "ns3/stats-module.h"
#include "ns3/wifi-module.h"
#include "ns3/internet-module.h"

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Main");

class Experiment
{
public:
  Experiment ();
  Experiment (std::string name);
  uint32_t Run (const WifiHelper &wifi, const YansWifiPhyHelper &wifiPhy,
                const WifiMacHelper &wifiMac, const YansWifiChannelHelper &wifiChannel);
private:
  void ReceivePacket (Ptr<Socket> socket);
  void SetPosition (Ptr<Node> node, Vector position);
  Vector GetPosition (Ptr<Node> node);
  Ptr<Socket> SetupPacketReceive (Ptr<Node> node);
  void GenerateTraffic (Ptr<Socket> socket, uint32_t pktSize,
                        uint32_t pktCount, Time pktInterval );

  uint32_t m_pktsTotal;
  Gnuplot2dDataset m_output;
};

Experiment::Experiment ()
{
}

Experiment::Experiment (std::string name)
  : m_output (name)
{
  m_output.SetStyle (Gnuplot2dDataset::LINES);
}

void
Experiment::SetPosition (Ptr<Node> node, Vector position)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  mobility->SetPosition (position);
}

Vector
Experiment::GetPosition (Ptr<Node> node)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  return mobility->GetPosition ();
}

void
Experiment::ReceivePacket (Ptr<Socket> socket)
{
  Ptr<Packet> packet;
  while ((packet = socket->Recv ()))
    {
      m_pktsTotal++;
    }
}

Ptr<Socket>
Experiment::SetupPacketReceive (Ptr<Node> node)
{
  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
  Ptr<Socket> sink = Socket::CreateSocket (node, tid);
  InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
  sink->Bind (local);
  sink->SetRecvCallback (MakeCallback (&Experiment::ReceivePacket, this));
  return sink;
}

void
Experiment::GenerateTraffic (Ptr<Socket> socket, uint32_t pktSize,
                             uint32_t pktCount, Time pktInterval )
{
  if (pktCount > 0)
    {
      socket->Send (Create<Packet> (pktSize));
      Simulator::Schedule (pktInterval, &Experiment::GenerateTraffic, this,
                           socket, pktSize,pktCount-1, pktInterval);
    }
  else
    {
      socket->Close ();
    }
}

uint32_t
Experiment::Run (const WifiHelper &wifi, const YansWifiPhyHelper &wifiPhy,
                 const WifiMacHelper &wifiMac, const YansWifiChannelHelper &wifiChannel)
{
  m_pktsTotal = 0;

  NodeContainer c;
  c.Create (2);

  InternetStackHelper internet;
  internet.Install (c);

  YansWifiPhyHelper phy = wifiPhy;
  phy.SetChannel (wifiChannel.Create ());

  WifiMacHelper mac = wifiMac;
  NetDeviceContainer devices = wifi.Install (phy, mac, c);

  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
  positionAlloc->Add (Vector (5.0, 0.0, 0.0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (c);

  Ipv4AddressHelper ipv4;
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (devices);

  Ptr<Socket> recvSink = SetupPacketReceive (c.Get (0));

  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
  Ptr<Socket> source = Socket::CreateSocket (c.Get (1), tid);
  InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
  source->SetAllowBroadcast (true);
  source->Connect (remote);
  uint32_t packetSize = 1014;
  uint32_t maxPacketCount = 200;
  Time interPacketInterval = Seconds (1.);
  Simulator::Schedule (Seconds (1.0), &Experiment::GenerateTraffic,
                       this, source, packetSize, maxPacketCount,interPacketInterval);
  Simulator::Run ();

  Simulator::Destroy ();

  return m_pktsTotal;
}

int main (int argc, char *argv[])
{
  std::ofstream outfile ("clear-channel.plt");
  std::vector <std::string> modes;

  modes.push_back ("DsssRate1Mbps");
  modes.push_back ("DsssRate2Mbps");
  modes.push_back ("DsssRate5_5Mbps");
  modes.push_back ("DsssRate11Mbps");
  // disable fragmentation
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));

  CommandLine cmd;
  cmd.Parse (argc, argv);

  Gnuplot gnuplot = Gnuplot ("clear-channel.eps");

  for (uint32_t i = 0; i < modes.size (); i++)
    {
      std::cout << modes[i] << std::endl;
      Gnuplot2dDataset dataset (modes[i]);

      for (double rss = -102.0; rss <= -80.0; rss += 0.5)
        {
          Experiment experiment;
          dataset.SetStyle (Gnuplot2dDataset::LINES);

          WifiHelper wifi;
          wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
          WifiMacHelper wifiMac;
          Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
                              StringValue (modes[i]));
          wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                        "DataMode",StringValue (modes[i]),
                                        "ControlMode",StringValue (modes[i]));
          wifiMac.SetType ("ns3::AdhocWifiMac");

          YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
          YansWifiChannelHelper wifiChannel;
          wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
          wifiChannel.AddPropagationLoss ("ns3::FixedRssLossModel","Rss",DoubleValue (rss));

          NS_LOG_DEBUG (modes[i]);
          experiment = Experiment (modes[i]);
          wifiPhy.Set ("EnergyDetectionThreshold", DoubleValue (-110.0) );
          wifiPhy.Set ("CcaMode1Threshold", DoubleValue (-110.0) );
          wifiPhy.Set ("TxPowerStart", DoubleValue (15.0) );
          wifiPhy.Set ("TxPowerEnd", DoubleValue (15.0) );
          wifiPhy.Set ("RxGain", DoubleValue (0) );
          wifiPhy.Set ("RxNoiseFigure", DoubleValue (7) );
          uint32_t pktsRecvd = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
          dataset.Add (rss, pktsRecvd);
        }

      gnuplot.AddDataset (dataset);
    }
  gnuplot.SetTerminal ("postscript eps color enh \"Times-BoldItalic\"");
  gnuplot.SetLegend ("RSS(dBm)", "Number of packets received");
  gnuplot.SetExtra  ("set xrange [-102:-83]");
  gnuplot.GenerateOutput (outfile);
  outfile.close ();

  return 0;
}


text:
/* line 3, jewellery.home.component.scss */
.home {
  width: 70%;
  margin: 35px auto 0;
}
/* line 6, jewellery.home.component.scss */
.home .jewellery-sliding-header {
  position: relative;
  z-index: 90;
  padding: 10px 10px 10px 15px;
  font-size: 1.2em;
  background-color: #fff;
  text-align: center;
  width: 200px;
  border: 1px solid lightgrey;
  border-top: 3px solid #75FF75;
  border-bottom-color: #fff;
  margin-top: 50px;
  margin-bottom: -1px;
}
/* line 20, jewellery.home.component.scss */
.home .slide-how-it-works {
  display: flex;
  justify-content: space-between;
  align-items: stretch;
}
/* line 24, jewellery.home.component.scss */
.home .slide-how-it-works .slideShow-container {
  width: 72%;
  border: 1px solid lightgrey;
}
/* line 27, jewellery.home.component.scss */
.home .slide-how-it-works .slideShow-container ngb-carousel {
  width: 100%;
}
/* line 32, jewellery.home.component.scss */
.home .slide-how-it-works .how-it-works-details-container {
  display: flex;
  flex-direction: column;
  width: 25%;
  justify-content: space-between;
  align-items: flex-end;
}
/* line 39, jewellery.home.component.scss */
.home .slide-how-it-works .how-it-works-details-container > .how-it-works-header {
  display: none;
  margin-top: 0;
}
/* line 43, jewellery.home.component.scss */
.home .slide-how-it-works .how-it-works-details-container .how-it-works-item {
  background-color: #fff;
  height: 150px;
  border: 1px solid lightgrey;
  display: flex;
  width: 100%;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
/* line 53, jewellery.home.component.scss */
.home .slide-how-it-works .how-it-works-details-container .how-it-works-item img {
  height: 50px;
}
/* line 57, jewellery.home.component.scss */
.home .slide-how-it-works .how-it-works-details-container .how-it-works-item h3 {
  margin-top: 10px;
  text-align: center;
  width: 85%;
}
/* line 67, jewellery.home.component.scss */
.home .offers-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background-color: #fff;
  border: 1px solid lightgrey;
}
/* line 76, jewellery.home.component.scss */
.home .offers-container button {
  background-color: transparent;
  cursor: pointer;
}
/* line 80, jewellery.home.component.scss */
.home .offers-container button:focus, .home .offers-container button:active {
  outline: 0;
}
/* line 83, jewellery.home.component.scss */
.home .offers-container button img {
  height: 25px;
}
/* line 87, jewellery.home.component.scss */
.home .offers-container .btn:focus {
  outline: 0;
}
/* line 90, jewellery.home.component.scss */
.home .offers-container .overFlow-container {
  overflow: hidden;
  height: 265px;
  width: 100%;
}
/* line 95, jewellery.home.component.scss */
.home .offers-container .overFlow-container jewellery-thumbnail {
  width: 600%;
}

/*******************/
/*Responsive styles*/
/*******************/
@media screen and (min-width: 1920px) {
  /* line 108, jewellery.home.component.scss */
  .home .slide-how-it-works {
    flex-direction: column;
    align-items: center;
  }
  /* line 111, jewellery.home.component.scss */
  .home .slide-how-it-works .slideShow-container {
    width: 1024px;
  }
  /* line 114, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container {
    width: 100%;
    flex-direction: row;
    margin-top: 35px;
  }
  /* line 119, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item {
    max-width: 30%;
  }
}
@media screen and (max-width: 1440px) {
  /* line 129, jewellery.home.component.scss */
  .home .slide-how-it-works {
    flex-direction: column;
  }
  /* line 131, jewellery.home.component.scss */
  .home .slide-how-it-works .slideShow-container {
    width: 100%;
  }
  /* line 133, jewellery.home.component.scss */
  .home .slide-how-it-works .slideShow-container ngb-carousel {
    width: 100%;
  }
  /* line 135, jewellery.home.component.scss */
  .home .slide-how-it-works .slideShow-container ngb-carousel img {
    width: 100%;
    height: 100%;
  }
  /* line 141, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
    flex-wrap: wrap;
    margin-top: 35px;
  }
  /* line 147, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item {
    max-width: 30%;
  }
}
@media screen and (max-width: 1024px) {
  /* line 161, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item h3 {
    font-size: 1em;
  }
}
@media screen and (max-width: 768px) {
  /* line 171, jewellery.home.component.scss */
  .home {
    width: 95%;
  }
  /* line 176, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item h3 {
    font-size: 1em;
  }
}
@media screen and (max-width: 425px) {
  /* line 188, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container {
    flex-direction: column;
    justify-content: space-between;
    height: 200px;
  }
  /* line 193, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item {
    max-width: 100%;
    height: 30%;
    flex-direction: row;
  }
  /* line 197, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item img {
    height: 70%;
    margin-right: 15px;
    margin-left: 15px;
  }
  /* line 202, jewellery.home.component.scss */
  .home .slide-how-it-works .how-it-works-details-container .how-it-works-item h3 {
    font-size: 0.9em;
    text-align: left;
  }
}


text:
package net.liftweb {
package util {

import _root_.org.slf4j.{Logger, LoggerFactory}

/**
 * Object use to configure lift to use slf4j for as internal logging.
 * Note that slf4j back-end should be configured previously to use Slf4jLogBoot.
 * To use it, call Slf4jLogBoot.enable():
 *

 * package bootstrap.liftweb
 *
 * import _root_.net.liftweb.util._
 * ...
 * class Boot {
 *   def boot {
 *     Slf4jLogBoot.enable()
 *     ...
 *

 * You have to add slf4j (and/or the backend) as dependency of your webapp, and you could exclude log4j.
 * I (DavidB) highly recommand using logback as backend for slf4j.
 * ex, add in your pom.xml:
 *

 *    <dependency>
 *      <groupId>net.liftweb</groupId>
 *      <artifactId>lift-webkit</artifactId>
 *      <version>0.7</version>
 *      <exclusions>
 *        <exclusion>
 *          <groupId>log4j</groupId>
 *          <artifactId>log4j</artifactId>
 *        </exclusion>
 *      </exclusions>
 *    </dependency>
 *    <dependency>
 *      <groupId>ch.qos.logback</groupId>
 *      <artifactId>logback-classic</artifactId>
 *      <version>0.9.8</version>
 *    </dependency>
 *

 *
 */
@deprecated object Slf4jLogBoot {
  private def _loggerByClass(clz: Class[AnyRef]): LiftLogger = new Slf4jLogger(LoggerFactory.getLogger(clz))
  private def _loggerByName(name: String): LiftLogger = new Slf4jLogger(LoggerFactory.getLogger(name))

  /**
   * enable slf4j as logging system for lift (internal, not for lift based application)
   */
  def enable() {
    LogBoot.loggerByName = _loggerByName
    LogBoot.loggerByClass = _loggerByClass
  }
}

/**
 * Adapter use internaly by lift as Logger, if Slf4jLogBoot is enabled.
 * @see Slf4jLogBoot
 */
@deprecated class Slf4jLogger(val logger: Logger) extends LiftLogger {
  override def isTraceEnabled = logger.isTraceEnabled
  override def trace(msg: => AnyRef) = if (isTraceEnabled) logger.trace(String.valueOf(msg))
  override def trace(msg: => AnyRef, t: => Throwable) = if (isTraceEnabled) logger.trace(String.valueOf(msg), t)

  override def assertLog(assertion: Boolean, msg: => String) = if (assertion) info(msg)

  override def isDebugEnabled = logger.isDebugEnabled
  override def debug(msg: => AnyRef) = if (isDebugEnabled) logger.debug(String.valueOf(msg))
  override def debug(msg: => AnyRef, t: => Throwable) = if (isDebugEnabled) logger.debug(String.valueOf(msg), t)

  override def isErrorEnabled = logger.isErrorEnabled
  override def error(msg: => AnyRef) = if (isErrorEnabled) logger.error(String.valueOf(msg))
  override def error(msg: => AnyRef, t: => Throwable) = if (isErrorEnabled) logger.error(String.valueOf(msg), t)

  override def fatal(msg: AnyRef) = error(msg)
  override def fatal(msg: AnyRef, t: Throwable) = error(msg, t)

  override def level = LiftLogLevels.All

  override def isEnabledFor(level: LiftLogLevels.Value): Boolean = level match {
    case LiftLogLevels.All => isTraceEnabled
    case LiftLogLevels.Debug => isDebugEnabled
    case LiftLogLevels.Error => isErrorEnabled
    case LiftLogLevels.Warn => isWarnEnabled
    case LiftLogLevels.Fatal => isErrorEnabled
    case LiftLogLevels.Info => isInfoEnabled
    case LiftLogLevels.Trace => isTraceEnabled
    case LiftLogLevels.Off => !isErrorEnabled
  }

//  override def level_=(level: LiftLogLevels.Value) = logger.setLevel(liftToLog4J(level) )
  override def name = logger.getName

  override def isInfoEnabled = logger.isInfoEnabled
  override def info(msg: => AnyRef) = if (isInfoEnabled) logger.info(String.valueOf(msg))
  override def info(msg: => AnyRef, t: => Throwable) = if (isInfoEnabled) logger.info(String.valueOf(msg), t)

  override def isWarnEnabled = logger.isWarnEnabled
  override def warn(msg: => AnyRef) = if (isWarnEnabled) logger.warn(String.valueOf(msg))
  override def warn(msg: => AnyRef, t: => Throwable) = if (isWarnEnabled) logger.warn(String.valueOf(msg), t)
}

}
}


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.resources.commerce.shipping.admin;

import com.mozu.api.ApiContext;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

/**
 * Use the Profiles resource to manage your shipping profiles.
 *
 */
public class ShippingProfileResource {
	///
	/// <see cref="Mozu.Api.ApiContext"/>
	///
	private ApiContext _apiContext;

	public ShippingProfileResource(ApiContext apiContext)
	{
		_apiContext = apiContext;
	}

	/**
	 *
	 *

	 *	ShippingProfile shippingprofile = new ShippingProfile();
	 *	ShippingProfileCollection shippingProfileCollection = shippingprofile.getProfiles();
	 *

	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 * @see com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 */
	public com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection getProfiles() throws Exception
	{
		return getProfiles( null);
	}

	/**
	 *
	 *

	 *	ShippingProfile shippingprofile = new ShippingProfile();
	 *	CountDownLatch latch = shippingprofile.getProfiles( callback );
	 *	latch.await()	 *

	 * @param  callback callback handler for asynchronous operations
	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 * @see com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 */
	public CountDownLatch getProfilesAsync( AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection> callback) throws Exception
	{
		return getProfilesAsync( null, callback);
	}

	/**
	 *
	 *

	 *	ShippingProfile shippingprofile = new ShippingProfile();
	 *	ShippingProfileCollection shippingProfileCollection = shippingprofile.getProfiles( responseFields);
	 *

	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 * @see com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 */
	public com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection getProfiles(String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection> client = com.mozu.api.clients.commerce.shipping.admin.ShippingProfileClient.getProfilesClient( responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 *
	 *

	 *	ShippingProfile shippingprofile = new ShippingProfile();
	 *	CountDownLatch latch = shippingprofile.getProfiles( responseFields, callback );
	 *	latch.await()	 *

	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param  callback callback handler for asynchronous operations
	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 * @see com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection
	 */
	public CountDownLatch getProfilesAsync(String responseFields, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection> callback) throws Exception
	{
		MozuClient<com.mozu.api.contracts.shippingadmin.profile.ShippingProfileCollection> client = com.mozu.api.clients.commerce.shipping.admin.ShippingProfileClient.getProfilesClient( responseFields);
		client.setContext(_apiContext);
		return client.executeRequest(callback);

	}

}


text:
package main

import (
	//"bufio"
	"bufio"
	"crypto/rand"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"time"

	"github.com/codegangsta/cli"

	"github.com/toorop/pepper"
)

func handleErr(err error) {
	if err != nil {
		dieError(err.Error())
	}
}

func dieError(msg string) {
	fmt.Println(msg)
	os.Exit(1)
}

// getKeys returns keys used for enc/dec from:
// - cmd line option
// - environment vars
// - ~/.pepper/private.key /.pepper/public.key
func getKeys(c *cli.Context) (privkey, pubkey *pepper.Key, err error) {
	privkeyStr := c.String("privkey")
	if privkeyStr == "" {
		privkeyStr = os.Getenv("PEPPER_PRIVATE_KEY")
	}
	if privkeyStr != "" {
		privkey, err = pepper.KeyFromString(privkeyStr)
		handleErr(err)
	} else {
		// From homedir
		privkey, err = pepper.KeyFromHomeDir("private")
		handleErr(err)
	}
	if privkey == nil {
		return nil, nil, errors.New("No private key found")
	}

	// pubkey
	pubkeyStr := c.String("pubkey")
	if pubkeyStr == "" {
		pubkeyStr = os.Getenv("PEPPER_PUBLIC_KEY")
	}
	if pubkeyStr != "" {
		pubkey, err = pepper.KeyFromString(pubkeyStr)
		handleErr(err)
	} else {
		// From homedir
		pubkey, err = pepper.KeyFromHomeDir("public")
		handleErr(err)
	}
	return
}

// getInput return input in the order below
// - from command line
// - from stdin
func getInput(c *cli.Context) (*[]byte, error) {
	var err error
	input := []byte(c.Args().First())
	if len(input) == 0 {
		// try stdin
		// timeout on read
		// if nothing to raise.
		c := make(chan byte, 1)
		go func() {
			b := make([]byte, 1)
			_, err := os.Stdin.Read(b)
			handleErr(err)
			c <- b[0]
		}()
		select {
		case b := <-c:
			input, err = ioutil.ReadAll(os.Stdin)
			if err != nil {
				return nil, err
			}
			input = append([]byte{b}, input...)
		case <-time.After(time.Millisecond * 10):
			println("timeout")
			// some kind of magic happens here
		}
	}
	return &input, nil
}

// generateKey generates a new set of key
var generateKey = cli.Command{
	Name:  "genkey",
	Usage: "Create new set of keys",
	Action: func(c *cli.Context) {
		pub, priv, err := pepper.GenerateKey(rand.Reader)
		handleErr(err)

		// save in ~/.pepper/key.priv|pub ?
		homeDir, err := pepper.GetHomeDir()
		handleErr(err)

		handleErr(err)
		var r []byte

		pubKey := &pepper.Key{
			Raw:  *pub,
			Type: "public",
		}

		privKey := &pepper.Key{
			Raw:  *priv,
			Type: "private",
		}

		fmt.Printf("Private key: %s\n", privKey)
		fmt.Printf("Public key: %s\n", pubKey)

		for {
			fmt.Printf("Would you like to save keys as your keys in %s ?\nWarning if keys exists they will be replaced (y/n) :", path.Join(homeDir, ".pepper"))
			r, _, _ = bufio.NewReader(os.Stdin).ReadLine()
			if r[0] == 110 || r[0] == 121 {
				break
			}
		}
		if r[0] == 121 {
			handleErr(pubKey.SaveInHomeDir())
			handleErr(privKey.SaveInHomeDir())
		}
	},
}

// encmsg encrypt a message
var encmsg = cli.Command{
	Name:  "encmsg",
	Usage: "Encrypt à text message",
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:   "privkey, r",
			Value:  "",
			Usage:  "Your private key",
			EnvVar: "PEPPER_PRIVATE_KEY",
		}, cli.StringFlag{
			Name:  "pubkey, u",
			Value: "",
			Usage: "Peer public key",
		},
	},
	Action: func(c *cli.Context) {
		var err error
		// message to be encrypted
		msg, err := getInput(c)
		handleErr(err)
		if len(*msg) == 0 {
			println("Nothing to encrypt\n pepper encmsg " + `"message to encrypt"` + "\nor\n echo " + `"message to encrypt"` + " | pepper encmsg" + "\nor\n cat file.txt | pepper encmsg")
			os.Exit(1)
		}
		// get keys
		privKey, pubKey, err := getKeys(c)
		handleErr(err)

		encrypted, err := pepper.EncryptMsg(*msg, pubKey, privKey)
		handleErr(err)

		println(encrypted)

	},
}

// decmsg decrypt a message
var decmsg = cli.Command{
	Name:  "decmsg",
	Usage: "Decrypt à text message",
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:   "privkey, r",
			Value:  "",
			Usage:  "Your private key",
			EnvVar: "PEPPER_PRIVATE_KEY",
		}, cli.StringFlag{
			Name:  "pubkey, u",
			Value: "",
			Usage: "Peer public key",
		},
	},
	Action: func(c *cli.Context) {
		msg, err := getInput(c)
		handleErr(err)
		if len(*msg) == 0 {
			println("Nothing to decrypt\n pepper decmsg " + `"message to encrypt"` + "\nor\n echo " + `"message to decrypt"` + " | pepper decmsg" + "\nor\n cat file.txt | pepper decmsg")
			os.Exit(1)
		}

		// get keys
		privKey, pubKey, err := getKeys(c)
		handleErr(err)

		decrypted, err := pepper.DecryptMsg(string(*msg), pubKey, privKey)
		println(string(decrypted))
	},
}

// encfile encrypt a file
var encfile = cli.Command{
	Name:  "encfile",
	Usage: "Encrypt a file",
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:   "privkey, r",
			Value:  "",
			Usage:  "Your private key",
			EnvVar: "PEPPER_PRIVATE_KEY",
		}, cli.StringFlag{
			Name:  "pubkey, u",
			Value: "",
			Usage: "Peer public key",
		}, cli.StringFlag{
			Name:  "in, i",
			Value: "",
			Usage: "File to encrypt",
		}, cli.StringFlag{
			Name:  "out, o",
			Value: "",
			Usage: "Full path for encrypted file",
		},
	},
	Action: func(c *cli.Context) {
		var err error
		// input
		in := c.String("in")
		if in == "" {
			dieError("You must provide a file to encrytp\npepper encfile -i FILE_TO_ENCRYPT [-o OUTPUT_FILE]")
		}
		if _, err = os.Stat(in); os.IsNotExist(err) {
			dieError("no such file or directory: " + in)
		}

		// output
		out := c.String("out")
		if out == "" {
			out = in + ".enc"
		}
		privKey, pubKey, err := getKeys(c)
		handleErr(err)

		handleErr(pepper.EncryptFile(in, out, pubKey, privKey))
	},
}

// encfile encrypt a file
var decfile = cli.Command{
	Name:  "decfile",
	Usage: "Decrypt a file",
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:   "privkey, r",
			Value:  "",
			Usage:  "Your private key",
			EnvVar: "PEPPER_PRIVATE_KEY",
		}, cli.StringFlag{
			Name:  "pubkey, u",
			Value: "",
			Usage: "Peer public key",
		}, cli.StringFlag{
			Name:  "in, i",
			Value: "",
			Usage: "File to decrypt",
		}, cli.StringFlag{
			Name:  "out, o",
			Value: "",
			Usage: "Full path for decrypted file",
		},
	},
	Action: func(c *cli.Context) {
		// in
		in := c.String("in")
		if in == "" {
			dieError("You must provide a file to decrypt\npepper decfile -i FILE_TO_ENCRYPT -n NONCE [-o OUTPUT_FILE]")
		}

		// out
		out := c.String("out")
		if out == "" {
			out = in + ".decrypted"
		}

		// get keys
		privKey, pubKey, err := getKeys(c)
		handleErr(err)
		handleErr(pepper.DecryptFile(in, out, pubKey, privKey))
	},
}

// Print user keys as string
var dumpkeys = cli.Command{
	Name:  "dumpkeys",
	Usage: "Print user keys as string",
	Action: func(c *cli.Context) {
		pubKey, err := pepper.KeyFromHomeDir("public")
		handleErr(err)
		privKey, err := pepper.KeyFromHomeDir("private")
		handleErr(err)
		fmt.Printf("Public key:%s\nPrivate key:%s\n", pubKey, privKey)
	},
}

// Save keys in user HOMEDIR/.pepper
var savekeys = cli.Command{
	Name:  "savekeys",
	Usage: "Decrypt a file",
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:   "privkey, r",
			Value:  "",
			Usage:  "Your private key",
			EnvVar: "PEPPER_PRIVATE_KEY",
		}, cli.StringFlag{
			Name:  "pubkey, u",
			Value: "",
			Usage: "Peer public key",
		},
	},
	Action: func(c *cli.Context) {
		// public key
		pubstr := c.String("u")
		if pubstr == "" {
			dieError("public key is missing \npepper savekeys -u PUBLIC_KEY -r PRIVATE_KEY")
		}

		// private key
		privstr := c.String("r")
		if privstr == "" {
			dieError("private key is missing \npepper savekeys -u PUBLIC_KEY -r PRIVATE_KEY")
		}

		pubKey, err := pepper.KeyFromString(pubstr)
		handleErr(err)
		pubKey.Type = "public"
		privKey, err := pepper.KeyFromString(privstr)
		handleErr(err)
		privKey.Type = "private"
		handleErr(pubKey.SaveInHomeDir())
		handleErr(privKey.SaveInHomeDir())
	},
}

func main() {
	app := cli.NewApp()
	app.Name = "pepper"
	app.Usage = "repellent for black boxes"
	app.Author = "Stéphane Depierrepont aka toorop"
	app.Email = "toorop@toorop.fr"
	app.Version = "0.0.1"
	app.Commands = []cli.Command{
		generateKey,
		encmsg,
		decmsg,
		encfile,
		decfile,
		dumpkeys,
		savekeys,
	}
	app.Run(os.Args)
}


text:
function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function addLabels() {
        $.scroller.add(Ti.UI.createLabel(Alloy.createStyle("index", {
            apiName: "Ti.UI.Label",
            text: "Alloy.createStyle() + Ti.UI.createLabel()"
        })));
        $.scroller.add(Ti.UI.createLabel($.createStyle({
            apiName: "Ti.UI.Label",
            text: "$.createStyle() + Ti.UI.createLabel()"
        })));
        $.scroller.add(Alloy.UI.create("index", "Ti.UI.Label", {
            text: "Alloy.UI.create()"
        }));
        $.scroller.add($.UI.create("Ti.UI.Label", {
            text: "$.UI.create()"
        }));
        $.scroller.add(Alloy.createWidget("alloy.testWidget", "labelmaker").createLabels());
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    this.args = arguments[0] || {};
    if (arguments[0]) {
        {
            __processArg(arguments[0], "__parentSymbol");
        }
        {
            __processArg(arguments[0], "$model");
        }
        {
            __processArg(arguments[0], "__itemTemplate");
        }
    }
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.index = Ti.UI.createWindow({
        backgroundColor: "#fff",
        fullscreen: false,
        exitOnClose: true,
        id: "index"
    });
    $.__views.index && $.addTopLevelView($.__views.index);
    addLabels ? $.__views.index.addEventListener("click", addLabels) : __defers["$.__views.index!click!addLabels"] = true;
    $.__views.scroller = Ti.UI.createScrollView({
        layout: "vertical",
        height: Ti.UI.FILL,
        width: Ti.UI.FILL,
        id: "scroller"
    });
    $.__views.index.add($.__views.scroller);
    exports.destroy = function() {};
    _.extend($, $.__views);
    $.index.open();
    __defers["$.__views.index!click!addLabels"] && $.__views.index.addEventListener("click", addLabels);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
<?php
header("Content-Type: application/json; charset=utf-8");
$keyword = setVar('keyword');

function setVar($name, $default = "0"){
	return isset($_GET[$name])?$_GET[$name]:$default;
}
if($keyword){
	require_once('dummyTokyo.json');
	// echo $keyword;
}else{
	require_once('dummyAll.json');
	// echo 'hoge';
}
?>


text:
package com.raulh82vlc.MoviesFinder.domain.executors;

import com.raulh82vlc.MoviesFinder.domain.exceptions.InternetConnectionException;

/**
 * Use case or Interactor, each thread or action
 * is taken in a use case, what means an interactor
 *

 * This is a contract of the interactor, but
 * concrete logic will be done through its
 * use case (specific interactor implementation)
 *

 *
 * @author Raul Hernandez Lopez
 */
public interface Interactor {
    void run() throws InternetConnectionException;
}


text:
Nuke Snake is a cross between "snake" games and "tank" games.  Players control nuclear-powered snakes and try to destroy each other while avoiding obstacles.

Nuke Snake was originally written for classic (pre-OS X) Macintosh by David Riggle.  This is a clone with some added features and support for multiple platforms.

Note that this is still in "alpha".  It is mostly feature-complete and entirely playable, but there are some missing features.

# INSTALLATION

Nuke Snake is cross-platform; the files in 'engine' are constant throughout all the ports, but other source files differ.  The 'allegro' folder is for PC (Linux, Windows, Mac OS X) while the 'tigcc' folder is for the TI-89 graphing calculator.

Currently, Nuke Snake only runs in the game folder where 'nukesnake.dat' and 'wav' are (unless you are using the tigcc version).

The "qt", "ecere", and "engine2" folders contain unfinished code.

## Linux

To build Nuke Snake for Linux, you need to install the Allegro Game Programming library development package, version 4.  If you are running a major Linux distribution like Fedora, Ubuntu, or Debian, the package manager can be used to install this.  On Ubuntu:

    sudo apt-get install liballegro4-dev

and on Fedora:

    sudo yum install allegro4-devel

If neither of these options exist, you may need to download, compile, and install the tarball manually.

After installing the Allegro development package, open the folder 'allegro' in this source archive and type `make`.  To run, type ./nukesnake in the same directory where 'nukesnake.dat' and 'wav' are.  Enjoy!

## Windows

In the past, I compiled Nuke Snake for Windows using [Dev-C++](http://www.bloodshed.net/devcpp.html).  To do so, download the [Allegro DevPack for Dev-Cpp](http://devpaks.org/details.php?devpak=1) and use the PackMan.exe program in C:\Dev-Cpp to install it.  You may have to fix warnings or errors like "uint does not exist".

# LICENSE

Nuke Snake is free software; both code and media are MIT-licensed.

# AUTHORS

 * David Riggle - Original concept and game, media.  Some code from his original game was converted from Pascal to C almost line-by-line for this game, too.

 * Joey Adams (joeyadams3.14159@gmail.com) - Engine code for Linux (Allegro) and the TI-89 (TIGCC).


text:
import React from 'react';
import { Theme, createStyles, makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import Accordion from '@material-ui/core/Accordion';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionActions from '@material-ui/core/AccordionActions';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import Chip from '@material-ui/core/Chip';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      width: '100%',
    },
    heading: {
      fontSize: theme.typography.pxToRem(15),
    },
    secondaryHeading: {
      fontSize: theme.typography.pxToRem(15),
      color: theme.palette.text.secondary,
    },
    icon: {
      verticalAlign: 'bottom',
      height: 20,
      width: 20,
    },
    details: {
      alignItems: 'center',
    },
    column: {
      flexBasis: '33.33%',
    },
    helper: {
      borderLeft: `2px solid ${theme.palette.divider}`,
      padding: theme.spacing(1, 2),
    },
    link: {
      color: theme.palette.primary.main,
      textDecoration: 'none',
      '&:hover': {
        textDecoration: 'underline',
      },
    },
  }),
);

export default function DetailedAccordion() {
  const classes = useStyles();

  return (

      <Accordion defaultExpanded>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel1c-content"
          id="panel1c-header"
        >

            <Typography className={classes.heading}>Location</Typography>

            <Typography className={classes.secondaryHeading}>Select trip destination</Typography>

        </AccordionSummary>
        <AccordionDetails className={classes.details}>

            <Chip label="Barbados" onDelete={() => {}} />

            <Typography variant="caption">
              Select your destination of choice

                Learn more

            </Typography>

        </AccordionDetails>
        <Divider />
        <AccordionActions>
          <Button size="small">Cancel</Button>
          <Button size="small" color="primary">
            Save
          </Button>
        </AccordionActions>
      </Accordion>

  );
}


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#include "config.h"
#include "MediaStreamEventInit.h"

namespace blink {

MediaStreamEventInit::MediaStreamEventInit()
{
}

DEFINE_TRACE(MediaStreamEventInit)
{
    visitor->trace(m_stream);
    EventInit::trace(visitor);
}

} // namespace blink


text:
package io.quarkus.resteasy.reactive.server.test.resource.basic.resource;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/")
public class MultiInterfaceResLocatorResource {
    @Produces("text/plain")
    @Path("test")
    public Object resourceLocator() {
        return new MultiInterfaceResLocatorSubresource();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/sunrises-sunsets#birds-in-sunset-775333" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">birds-in-sunset-775333</uri-title>
      <source>birds-in-sunset-775333</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Birds</subject>
          <subject>Flying</subject>
          <subject>Water</subject>
          <subject>Oceans</subject>
          <subject>Sunset</subject>
          <subject>Sky</subject>
          <subject>Clouds</subject>
          <subject>Nature</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/sunrises-sunsets/birds-in-sunset-775333-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/sunrises-sunsets/birds-in-sunset-775333-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>99 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/sunrises-sunsets/birds-in-sunset-775333-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>111 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/sunrises-sunsets/birds-in-sunset-775333-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>240 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/sunrises-sunsets/birds-in-sunset-775333-print.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="birds-in-sunset-775333" locale="eng" uri="/media-library/images/sunrises-sunsets#birds-in-sunset-775333" status="publish" site="ldsorg" source="chq" words="111" tgp="0.3881"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:05.692556-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
@interface MOBProjectionEPSG29379 : MOBProjection

@end


text:
<!DOCTYPE html>

	<title>Leaflet debug page</title>

	<link rel="stylesheet" href="../../dist/leaflet.css" />

	<link rel="stylesheet" href="../css/screen.css" />


text:
const Vue = require("vue");

Vue.config.productionTip = false

function bootstrap(el, template, components) {
    /* eslint-disable no-new */
    console.log("Bootstrapping Ymir Application!")
    return new Vue({el, template, components})
}

module.exports = bootstrap


text:
package cert

import (
	"context"
	"crypto/x509"
	"encoding/json"
	"os"
	"strings"
	"testing"
	"time"
	"v2ray.com/core/common"
	"v2ray.com/core/common/task"
)

func TestGenerate(t *testing.T) {
	err := generate(nil, true, true, "ca")
	if err != nil {
		t.Fatal(err)
	}
}

func generate(domainNames []string, isCA bool, jsonOutput bool, fileOutput string) error {
	commonName := "V2Ray Root CA"
	organization := "V2Ray Inc"

	expire := time.Hour * 3

	var opts []Option
	if isCA {
		opts = append(opts, Authority(isCA))
		opts = append(opts, KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature))
	}

	opts = append(opts, NotAfter(time.Now().Add(expire)))
	opts = append(opts, CommonName(commonName))
	if len(domainNames) > 0 {
		opts = append(opts, DNSNames(domainNames...))
	}
	opts = append(opts, Organization(organization))

	cert, err := Generate(nil, opts...)
	if err != nil {
		return newError("failed to generate TLS certificate").Base(err)
	}

	if jsonOutput {
		printJSON(cert)
	}

	if len(fileOutput) > 0 {
		if err := printFile(cert, fileOutput); err != nil {
			return err
		}
	}

	return nil
}

type jsonCert struct {
	Certificate []string `json:"certificate"`
	Key         []string `json:"key"`
}

func printJSON(certificate *Certificate) {
	certPEM, keyPEM := certificate.ToPEM()
	jCert := &jsonCert{
		Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"),
		Key:         strings.Split(strings.TrimSpace(string(keyPEM)), "\n"),
	}
	content, err := json.MarshalIndent(jCert, "", "  ")
	common.Must(err)
	os.Stdout.Write(content)
	os.Stdout.WriteString("\n")
}
func printFile(certificate *Certificate, name string) error {
	certPEM, keyPEM := certificate.ToPEM()
	return task.Run(context.Background(), func() error {
		return writeFile(certPEM, name+"_cert.pem")
	}, func() error {
		return writeFile(keyPEM, name+"_key.pem")
	})
}
func writeFile(content []byte, name string) error {
	f, err := os.Create(name)
	if err != nil {
		return err
	}
	defer f.Close()

	return common.Error2(f.Write(content))
}


text:
<?php
/**
 * Property Generator Interface
 * @package repose
 */

/**
 * Property Generator Interface
 * @package repose
 */
interface repose_IPropertyGenerator {

    /**
     * Generates an ID
     * @param $session Session
     * @param $clazz Mapped Class
     * @param $property Mapped Class Property
     * @param $object Instance of class
     * @param $newId New ID if available from engine (auto increment)
     */
    public function generate(repose_Session $session, repose_MappedClass $clazz, repose_MappedClassProperty $property, $object, $newId = null);

    /**
     * Should generate ID when object is added to session
     * @return bool
     */
    public function shouldGenerateOnAdd();

    /**
     * Should generate ID just before object will be persisted
     * @return bool
     */
    public function shouldGenerateBeforePersist();

    /**
     * Should generate ID right after object has been persisted (i.e., "last insert ID")
     * @return bool
     */
    public function shouldGenerateAfterPersist();

}
?>


text:
package com.a9ski.algo.graph;

import com.a9ski.algo.arithmetic.Arithmetic;

public class UndirectedGraphBuilder<T> extends DirectedGraphBuilder<T> {

	public UndirectedGraphBuilder(Arithmetic<T> arithmetic) {
		super(arithmetic);
	}

	@Override
	public GraphBuilder<T> addEdge(int from, int to, T weight) {
		super.addEdge(from, to, weight);
		super.addEdge(to, from, weight);
		return this;
	}

}


text:
static char kAFImageRequestOperationObjectKey;

@interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, retain, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation;
@end

@implementation UIImageView (_AFNetworking)
@dynamic af_imageRequestOperation;
@end

#pragma mark -

@implementation UIImageView (AFNetworking)

- (AFHTTPRequestOperation *)af_imageRequestOperation {
    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey);
}

- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation {
    objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (NSOperationQueue *)af_sharedImageRequestOperationQueue {
    static NSOperationQueue *_imageRequestOperationQueue = nil;

    if (!_imageRequestOperationQueue) {
        _imageRequestOperationQueue = [[NSOperationQueue alloc] init];
        [_imageRequestOperationQueue setMaxConcurrentOperationCount:8];
    }

    return _imageRequestOperationQueue;
}

#pragma mark -

- (void)setImageWithURL:(NSURL *)url {
    [self setImageWithURL:url placeholderImage:nil];
}

- (void)setImageWithURL:(NSURL *)url
       placeholderImage:(UIImage *)placeholderImage
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0];
    [request setHTTPShouldHandleCookies:NO];
    [request setHTTPShouldUsePipelining:YES];

    [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}

- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
              placeholderImage:(UIImage *)placeholderImage
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
    if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]])) {
        return;
    } else {
        [self cancelImageRequestOperation];
    }

    UIImage *cachedImage = [[AFImageCache sharedImageCache] cachedImageForURL:[urlRequest URL] cacheName:nil];
    if (cachedImage) {
        self.image = cachedImage;
        self.af_imageRequestOperation = nil;

        if (success) {
            success(nil, nil, cachedImage);
        }
    } else {
        self.image = placeholderImage;

        self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            if (self.af_imageRequestOperation && ![self.af_imageRequestOperation isCancelled]) {
                if (success) {
                    success(request, response, image);
                }

                if ([[request URL] isEqual:[[self.af_imageRequestOperation request] URL]]) {
                    self.image = image;
                } else {
                    self.image = placeholderImage;
                }
            }
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            self.af_imageRequestOperation = nil;

            if (failure) {
                failure(request, response, error);
            }
        }];

        [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
    }
}

- (void)cancelImageRequestOperation {
    [self.af_imageRequestOperation cancel];
}

@end

#endif


text:
var watchify      = require('watchify');
var browserify    = require('browserify');
var gulp          = require('gulp');
var source        = require('vinyl-source-stream');
var buffer        = require('vinyl-buffer');
var gutil         = require('gulp-util');
var babelify      = require('babelify');
var uglify        = require('gulp-uglify');
var sourcemaps    = require('gulp-sourcemaps');
var assign        = require('lodash.assign');
var browserSync   = require('browser-sync');
var sass          = require('gulp-sass');
var autoprefixer  = require('gulp-autoprefixer');

// ////////////////////////////////////////////////
// Javascript Browserify, Watchify, Babel, React
// https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md
// ////////////////////////////////////////////////

// add custom browserify options here
var customOpts = {
  entries: ['./src/js/app.js'],
  debug: true
};

var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts)); //call browserify which put all scripts in one file (bundle.js)

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
  return b.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, gutil.colors.red(
       '\n\n*********************************** \n' +
      'BROWSERIFY ERROR:' +
      '\n*********************************** \n\n'
      )))
    .pipe(source('main.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // .pipe(uglify()) //add for build
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
    // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('../maps')) // writes .map file
    .pipe(gulp.dest('./public/js'))
    .pipe(browserSync.reload({stream:true}));
}

// ////////////////////////////////////////////////
// Browser-Sync Tasks
// ////////////////////////////////////////////////

gulp.task('browserSync', function() {
    browserSync({
        server: {
            baseDir: "./public/"
        }
    });
});

// ////////////////////////////////////////////////
// HTML Tasks
// ////////////////////////////////////////////////

gulp.task('html', function() {
  return gulp.src('public/**/*.html')
    .pipe(browserSync.reload({stream:true}));
});

// ////////////////////////////////////////////////
// Styles Tasks
// ///////////////////////////////////////////////

gulp.task('styles', function() {
  gulp.src('src/scss/style.scss') //all styles are included in style.scss
    .pipe(sourcemaps.init())
      .pipe(sass({outputStyle: 'compressed'}))
      // .on('error', errorlog)
      .pipe(autoprefixer({
              browsers: ['last 3 versions'],
              cascade: false
          }))
    .pipe(sourcemaps.write('../maps'))
    .pipe(gulp.dest('public/css'))
    .pipe(browserSync.reload({stream:true}));
});

// ////////////////////////////////////////////////
// Watch Tasks
// ////////////////////////////////////////////////

gulp.task('watch', function() {
  gulp.watch('public/**/*.html', ['html']);
  gulp.watch('src/scss/**/*.scss', ['styles']);
});

gulp.task('default', ['js', 'styles', 'browserSync', 'watch']);


text:
# number-max-precision

Limit the number of decimal places allowed in numbers.

<!-- prettier-ignore -->
```css
a { top: 3.245634px; }
/**           ↑
 * This decimal place */
```

## Options

`int`: Maximum number of decimal places allowed.

For example, with `2`:

The following patterns are considered problems:

<!-- prettier-ignore -->
```css
a { top: 3.245px; }
```

<!-- prettier-ignore -->
```css
a { top: 3.245634px; }
```

<!-- prettier-ignore -->
```css
@media (min-width: 3.234em) {}
```

The following patterns are _not_ considered problems:

<!-- prettier-ignore -->
```css
a { top: 3.24px; }
```

<!-- prettier-ignore -->
```css
@media (min-width: 3.23em) {}
```

## Optional secondary options

### `ignoreProperties: ["/regex/", /regex/, "string"]`

Ignore the precision of numbers for the specified properties.

For example, with `0`.

Given:

```json
["transition"]
```

The following patterns are considered problems:

<!-- prettier-ignore -->
```css
a { top: 10.5px; }
```

The following patterns are _not_ considered problems:

<!-- prettier-ignore -->
```css
a { transition: all 4.5s ease; }
```

### `ignoreUnits: ["/regex/", /regex/, "string"]`

Ignore the precision of numbers for values with the specified units.

For example, with `2`.

Given:

```json
["/^my-/", "%"]
```

The following patterns are considered problems:

<!-- prettier-ignore -->
```css
a { top: 3.245px; }
```

<!-- prettier-ignore -->
```css
a { top: 3.245634px; }
```

<!-- prettier-ignore -->
```css
@media (min-width: 3.234em) {}
```

The following patterns are _not_ considered problems:

<!-- prettier-ignore -->
```css
a { top: 3.245%; }
```

<!-- prettier-ignore -->
```css
@media (min-width: 3.23em) {}
```

<!-- prettier-ignore -->
```css
a {
  width: 10.5432%;
}
```

<!-- prettier-ignore -->
```css
a { top: 3.245my-unit; }
```

<!-- prettier-ignore -->
```css
a {
  width: 10.989my-other-unit;
}
```


text:
"""Tests for mathematics_dataset.modules.calculus."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# Dependency imports
from mathematics_dataset.modules import calculus
import tensorflow as tf

class CalculusTest(tf.test.TestCase):

  def testSampleIntegrand(self):
    # y + 2*x + 3*x**2
    coefficients = [[0, 1], [2, 0], [3, 0]]
    derivative_order = 1
    derivative_axis = 0
    # const + x*y + x**2 + x**3
    expected = [[0, 1], [1, 0], [1, 0]]
    entropy = 4
    result = calculus._sample_integrand(
        coefficients, derivative_order, derivative_axis, entropy)
    result = result[1:, :]  # ignore random constant terms
    self.assertAllEqual(result, expected)

if __name__ == '__main__':
  tf.test.main()


text:
A server to manage monkeys services...

## How to build and run all tests
from the root folder type

```
mvn clean install
```

## How to run
In the IDE of choice (Intelij) run the main class **RuntimeService** from module **jf-runtime-service**.
Once this is running, the service should be reachable from http://localhost:8080/reach


text:
 package com.versionmaintain.panel;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.TreeNode;

import com.versionmaintain.JTitleLabel;
import com.versionmaintain.VerDetailTreeCellRenderer;
import com.versionmaintain.model.JVersionDetailPopupMenu;
import com.versionmaintain.res.Resource;

/**
 * @author xiaobolx
 * 2016年1月26日
 */
public class VersionDetailPanel
{
	private Component component;
	private JButton versionDetailEditAdd;
	private JButton versionDetailEditRemove;
	private JButton versionDetailEditEdit;
	private JTree softwareVersionInfoTree;
	private JVersionDetailPopupMenu versionDetailTreeMenu;

	public VersionDetailPanel()
    {
		JPanel topPanel = new JPanel(new BorderLayout());

		JLabel softInfoDetailLabel = new JTitleLabel("VersionDetail");
		softInfoDetailLabel.setBorder(new EmptyBorder(5, 5, 5, 5));

		JToolBar versionMaintainToolbar = new JToolBar("Detail info");
		versionDetailEditAdd = new JButton(Resource.ICON_ADD);
		versionDetailEditEdit = new JButton(Resource.ICON_EDIT);
		versionDetailEditRemove = new JButton(Resource.ICON_DEL);
		versionMaintainToolbar.add(versionDetailEditAdd);
		versionMaintainToolbar.add(versionDetailEditEdit);
		versionMaintainToolbar.add(versionDetailEditRemove);

		topPanel.add(softInfoDetailLabel, BorderLayout.NORTH);
		topPanel.add(versionMaintainToolbar, BorderLayout.SOUTH);

		TreeNode root = null;
		softwareVersionInfoTree = new JTree(root);
		softwareVersionInfoTree.setCellRenderer(new VerDetailTreeCellRenderer());
		versionDetailTreeMenu = new JVersionDetailPopupMenu(softwareVersionInfoTree);
		versionDetailTreeMenu.injectPopupMenu(versionDetailEditAdd, versionDetailEditEdit, versionDetailEditRemove);
		softwareVersionInfoTree.setEditable(true);
		softwareVersionInfoTree.setRowHeight(30);

		JPanel detailPanel = new JPanel();
		GridBagLayout bagLayout = new GridBagLayout();
		GridBagConstraints bagConstraints = new GridBagConstraints();
		bagConstraints.insets=new Insets(1,5,1,5);
		detailPanel.setLayout(bagLayout);
		bagConstraints.gridx=0;
		bagConstraints.gridy=0;
		bagConstraints.weightx = 1;
		bagConstraints.fill = GridBagConstraints.BOTH;
		detailPanel.add(topPanel, bagConstraints);
		bagConstraints.gridx=0;
		bagConstraints.gridy=1;
		bagConstraints.weightx = 1;
		bagConstraints.fill = GridBagConstraints.BOTH;
		bagConstraints.weighty = 1;
		bagConstraints.weighty=1;
		detailPanel.add(new JScrollPane(softwareVersionInfoTree), bagConstraints);
		this.component = detailPanel;
    }

	public Component getVersionDetailInfoPanel()
	{
		return component;
	}

	public JTree getTree()
	{
		return softwareVersionInfoTree;
	}

	public void resetTreeMenu()
    {
		versionDetailTreeMenu.resetComponent();
    }
}


text:
from social.backends.oauth import BaseOAuth2

class TribOAuth2(BaseOAuth2):
    """Texas Tribune OAuth authentication backend"""
    name = 'texastribune'
    AUTHORIZATION_URL = 'https://www.texastribune.org/oauth2/authorize/'
    ACCESS_TOKEN_URL = 'https://www.texastribune.org/oauth2/token/'
    ACCESS_TOKEN_METHOD = 'POST'
    ID_KEY = 'email'
    SCOPE_SEPARATOR = ','
    EXTRA_DATA = [
        ('expires_in', 'expires_in')
    ]

    def get_user_details(self, response):
        """Return user details from Texas Tribune account"""
        return {
            'username': response.get('username'),
            'email': response.get('email') or '',
            'first_name': response.get('first_name') or '',
            'last_name': response.get('last_name') or '',
        }

    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""

        result = self.get_json(
            'https://www.texastribune.org/api/self/',
            headers={'Authorization': 'Bearer {0}'.format(access_token)}
        )
        return result


text:
class SOAPBuilder < BasicBuilder

  def build(options = {})
    object = options.delete(:object)
    mapping = options.delete(:mapping)
    super(options.merge!({:raw_data => SOAP::Marshal.marshal(object, mapping), :method => :post}))
  end
end


text:
package com.jcabi.log;

import java.util.Formattable;
import java.util.Formatter;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.hamcrest.MockitoHamcrest;
import org.w3c.dom.Document;

/**
 * Test case for {@link DomDecor}.
 * @author Yegor Bugayenko (yegor256@gmail.com)
 * @version $Id$
 */
public final class DomDecorTest {

    /**
     * DocumentDecor can transform Document to text.
     * @throws Exception If some problem
     */
    @Test
    public void convertsDocumentToText() throws Exception {
        final Document doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().newDocument();
        doc.appendChild(doc.createElement("root"));
        final Formattable decor = new DomDecor(doc);
        final Appendable dest = Mockito.mock(Appendable.class);
        final Formatter fmt = new Formatter(dest);
        decor.formatTo(fmt, 0, 0, 0);
        Mockito.verify(dest).append(
            MockitoHamcrest.argThat(Matchers.containsString("<root/>"))
        );
    }

    /**
     * DocumentDecor can handle NULL properly.
     * @throws Exception If some problem
     */
    @Test
    public void convertsNullToText() throws Exception {
        final Formattable decor = new DomDecor(null);
        final Appendable dest = Mockito.mock(Appendable.class);
        final Formatter fmt = new Formatter(dest);
        decor.formatTo(fmt, 0, 0, 0);
        Mockito.verify(dest).append("NULL");
    }

}


text:
module DatabaseRewinder
  module Compatibility
    def clean_with(*args)
      cleaners.each {|c| c.clean_with(*args)}
    end

    def start; end

    def strategy=(args)
      options = args.is_a?(Array) ? args.extract_options! : {}
      @only, @except = options[:only], options[:except]
      cleaners.each {|c| c.strategy = nil, options}
    end
  end
  class << self
    include Compatibility
  end

  class Cleaner
    module Compatibility
      def clean_with(_strategy, only: nil, except: nil, **)
        originals = @only, @except
        self.only, self.except = Array(only), Array(except)
        clean_all
      ensure
        self.only, self.except = originals
      end

      def strategy=(args)
        options = args.is_a?(Array) ? args.extract_options! : {}
        self.only = Array(options[:only]) if options.key?(:only)
        self.except = Array(options[:except]) if options.key?(:except)
      end
    end

    include Compatibility
  end
end


text:
PXbase Package Bundle
=====================

LaTeX: Tools for use with (u)pLaTeX

The main purpose of this package is to provide auxiliary functions which
are utilized by packages created by the same author. This package also
provides a few user commands to assist in creating Japanese document on
(u)pLaTeX.

### System Requirements

  * TeX format: LaTeX.
  * TeX engine: pTeX and upTeX.
  * DVI-ware (in DVI output): Anything.

### Package content

  * `pxbase.sty`: the pxbase package
  * `pxbase.def`: a submodule (no longer used)
  * `pxbabel.sty`: the pxbabel package
  * `pxbasenc.def`: a submodule
  * `pxjsfenc.def`: a submodule
  * `pxbsjc.def`: a helper file for pxbase
  * `pxbsjc1.def`: a helper file for pxbase
  * `upkcat.sty`: the upkcat package

Some files are kept present for compatibility with other packages.

### Installation

In a system compliant to TDS 1.1, move the files as follows:

  - `*.sty` → $TEXMF/tex/platex/pxbase

And rehash your TEXMF trees if necessary.

### License

This package is distributed under the MIT License.

pxbase package ― the (quondam) base library for pTeX
-----------------------------------------------------

The package used to provide pTeX-specific features required by other
packages. However, it has been merged with the [bxbase] package since
v0.9, and currently it simply loads bxbase internally.

[bxbase]: https://www.ctan.org/pkg/bxbase

pxbabel package ― To help use Babel with Japanese document
-----------------------------------------------------------

Currently the documentation is available only in Japanese (see
pxbabel.pdf).

upkcat package ― To safely operate with kcatcode
-------------------------------------------------

Currently the documentation is available only in Japanese (see
README-ja.md).

Revision History
----------------

  * Version 1.3  〈2021/05/31〉
  * Version 1.2  〈2021/05/22〉
  * Version 1.1b 〈2017/07/03〉
  * Version 1.1a 〈2017/06/19〉
  * Version 1.1  〈2017/05/29〉
  * Version 0.5i 〈2017/05/04〉 ― for CTAN
  * Version 0.9b 〈2012/08/19〉
  * Version 0.5  〈2010/06/15〉
  * Version 0.4a 〈2010/02/07〉
  * Version 0.4  〈2009/07/05〉
  * Version 0.3  〈2008/04/06〉
  * Version 0.2b 〈2008/03/28〉
  * Version 0.2a 〈2008/03/18〉
  * Version 0.2  〈2008/03/14〉

--------------------
Takayuki YATO (aka. "ZR")
https://github.com/zr-tex8r


text:
AStar::AStar(int nMaxNodes)
{
	m_ClosedList = new bool[nMaxNodes];
	m_MaxNode = nMaxNodes;
}

//--------------------------------------------------------------------------------------
// Default Destructor
//--------------------------------------------------------------------------------------
AStar::~AStar()
{
	delete[] m_ClosedList;
}

// Call the function pointer.
int AStar::Callfunction(AStarNode* pStart, AStarNode* pEnd)
{
	if (fn_CalcHeuristic)
		return fn_CalcHeuristic(pStart, pEnd);

	return 0;
}

// Set the function pointer.
void AStar::SetFunction(CalcHeuristic func)
{
	fn_CalcHeuristic = func;
}

//--------------------------------------------------------------------------------------
// CalculatePath: Calculate the Astar path.
//
// Returns:
//		bool: Returns true or false if a path is found or not.
// Param:
//		pStart: AStarNode pointer for the start of the path.
//		pEnd: AStarNode pointer for the end of the path.
//		finishedPath: A DynamicArray pointer of AstarNode pointers.
//--------------------------------------------------------------------------------------
bool AStar::CalculatePath(AStarNode* pStart, AStarNode* pEnd, DynamicArray<AStarNode*>* finishedPath)
{
	//http://www.policyalmanac.org/games/aStarTutorial.htm

	// Clear open list
	m_OpenList.Clear();

	// Set all elements in closed list to false
	memset(m_ClosedList, 0, sizeof(bool) * m_MaxNode);

	// Set start nodes G score to zero
	pStart->m_nGScore = 0;

	// Calculate start nodes H score (for now set to zero).
	pStart->m_nHScore = Callfunction(pStart, pEnd);

	// Calculate start nodes F score.
	pStart->m_nFScore = pStart->m_nGScore + pStart->m_nHScore;

	// Set start nodes prev to null.
	pStart->m_nPrev = nullptr;

	// Add start node to open list.
	m_OpenList.Push(pStart);

	// While there are still nodes in the open list
	while (m_OpenList.GetSize() > 0)
	{
		// Get the node from the open list with the lowest F Score, we'll call that currentNode. (Pop off the top)
		AStarNode* pCurrentNode = m_OpenList.Pop();

		// Add currentNode to the closed list. (by setting the indexed bool to true)
		m_ClosedList[pCurrentNode->m_nIndex] = true;

		// if currentNode is the end node, we are finished
		if (pCurrentNode == pEnd)
		{
			// Build path (remember it is backwards so we need to fix that)
			AStarNode* pNode = pEnd;

			do
			{
				finishedPath->PushFront(pNode);
				pNode = pNode->m_nPrev;
			}

			while (pNode);

			// Return true to indicate that we found a valid path.
			return true;
		}

		// Loop through all of currentNode's neighbours
		for (int i = 0; i < pCurrentNode->m_AdjacentList.Size(); ++i)
		{
			AStarNode* pNeighbour = pCurrentNode->m_AdjacentList[i]->m_nEndNode;
			int nCost = pCurrentNode->m_AdjacentList[i]->m_nCost;

			//Walls. Skip walls.
			if (pNeighbour->m_Blocked)
				continue;

			// Skip neighbours that are already in the closed list.
			if (m_ClosedList[pNeighbour->m_nIndex])
			{
				continue;
			}

			int heapIndex = m_OpenList.Contains(pNeighbour);

			if (heapIndex != -1)
			{
				// Check if this current path is better than old path (loser F Score)
				if (pCurrentNode->m_nFScore + nCost < pNeighbour->m_nFScore)
				{
					// Update G Score.
					pNeighbour->m_nGScore = pCurrentNode->m_nGScore + nCost;

					// Update F Score.
					pNeighbour->m_nFScore = pNeighbour->m_nGScore + pNeighbour->m_nHScore;

					// Update Prev Node.
					pNeighbour->m_nPrev = pCurrentNode;

					// Sort Heap
					m_OpenList.Resort(heapIndex);
				}
			}
			else
			{
				// Calculate G Score.
				pNeighbour->m_nGScore = pCurrentNode->m_nGScore + nCost;

				// Calculate H Score.
				pNeighbour->m_nHScore = Callfunction(pStart, pEnd);

				// Calculate F Score.
				pNeighbour->m_nFScore = pNeighbour->m_nGScore + pNeighbour->m_nHScore;

				// Set Prev node pointer.
				pNeighbour->m_nPrev = pCurrentNode;

				// Add neigbour to open list.
				m_OpenList.Push(pNeighbour);
			}
		}
	}

	// No path found if we got to here, so return false.
	return false;
}


text:
package types

import dclauthtypes "github.com/zigbee-alliance/distributed-compliance-ledger/x/dclauth/types"

// TODO: 1. Move it to separate module  	2. Make it configurable		3. Save into store.
var (
	RootCertificateApprovalsPercent = 0.66
	RootCertificateApprovalRole     = dclauthtypes.Trustee
)


text:
@interface SDTabBarViewController : UITabBarController

@end


text:
package org.basex.query.func.fn;

import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.expr.CmpV.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.util.collation.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.util.list.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class FnIndexOf extends StandardFunc {
  @Override
  public Iter iter(final QueryContext qc) throws QueryException {
    return new Iter() {
      final Iter input = exprs[0].atomIter(qc, info);
      final Item search = toAtomItem(exprs[1], qc);
      final Collation coll = toCollation(2, qc);
      int c;

      @Override
      public Int next() throws QueryException {
        for(Item item; (item = qc.next(input)) != null;) {
          ++c;
          if(equal(item, search, coll)) return Int.get(c);
        }
        return null;
      }
    };
  }

  @Override
  public Value value(final QueryContext qc) throws QueryException {
    final Iter input = exprs[0].atomIter(qc, info);
    final Item search = toAtomItem(exprs[1], qc);
    final Collation coll = toCollation(2, qc);

    final LongList list = new LongList();
    int c = 0;
    for(Item item; (item = qc.next(input)) != null;) {
      ++c;
      if(equal(item, search, coll)) list.add(c);
    }
    return IntSeq.get(list);
  }

  /**
   * Checks the specified items for equality.
   * @param item input input
   * @param search search item
   * @param coll collation
   * @return result of check
   * @throws QueryException query exception
   */
  private boolean equal(final Item item, final Item search, final Collation coll)
      throws QueryException {
    return item.comparable(search) && OpV.EQ.eval(item, search, coll, sc, info);
  }

  @Override
  protected Expr opt(final CompileContext cc) {
    final Expr input = exprs[0];
    final SeqType st = input.seqType();
    if(st.zero()) return input;
    if(st.zeroOrOne() && !st.mayBeArray()) exprType.assign(Occ.ZERO_OR_ONE);
    return this;
  }
}