text:
namespace media {
namespace cast {

class AdaptiveCongestionControl final : public CongestionControl {
 public:
  AdaptiveCongestionControl(const base::TickClock* clock,
                            int max_bitrate_configured,
                            int min_bitrate_configured,
                            double max_frame_rate);

  AdaptiveCongestionControl(const AdaptiveCongestionControl&) = delete;
  AdaptiveCongestionControl& operator=(const AdaptiveCongestionControl&) =
      delete;

  ~AdaptiveCongestionControl() final;

  // CongestionControl implementation.
  void UpdateRtt(base::TimeDelta rtt) final;
  void UpdateTargetPlayoutDelay(base::TimeDelta delay) final;
  void SendFrameToTransport(FrameId frame_id,
                            size_t frame_size_in_bits,
                            base::TimeTicks when) final;
  void AckFrame(FrameId frame_id, base::TimeTicks when) final;
  void AckLaterFrames(std::vector<FrameId> received_frames,
                      base::TimeTicks when) final;
  int GetBitrate(base::TimeTicks playout_time,
                 base::TimeDelta playout_delay) final;

 private:
  struct FrameStats {
    FrameStats();
    // Time this frame was first enqueued for transport.
    base::TimeTicks enqueue_time;
    // Time this frame was acked.
    base::TimeTicks ack_time;
    // Size of encoded frame in bits.
    size_t frame_size_in_bits;
  };

  // Calculate how much "dead air" (idle time) there is between two frames.
  static base::TimeDelta DeadTime(const FrameStats& a, const FrameStats& b);
  // Get the FrameStats for a given |frame_id|, auto-creating a new FrameStats
  // for newer frames, but possibly returning nullptr for older frames that have
  // been pruned. Never returns nullptr for |frame_id|s equal to or greater than
  // |last_checkpoint_frame_|.
  // Note: Older FrameStats will be removed automatically.
  FrameStats* GetFrameStats(FrameId frame_id);
  // Discard old FrameStats.
  void PruneFrameStats();
  // Calculate a safe bitrate. This is based on how much we've been
  // sending in the past.
  double CalculateSafeBitrate();

  // Estimate when the transport will start sending the data for a given frame.
  // |estimated_bitrate| is the current estimated transmit bitrate in bits per
  // second.
  base::TimeTicks EstimatedSendingTime(FrameId frame_id,
                                       double estimated_bitrate);

  const base::TickClock* const clock_;  // Not owned by this class.
  const int max_bitrate_configured_;
  const int min_bitrate_configured_;
  const double max_frame_rate_;

  // This can not be a base::circular_deque because the AckFrame implementation
  // preserves a FrameStats* pointing inside the deque across mutations.
  std::deque<FrameStats> frame_stats_;

  FrameId last_frame_stats_;
  // This is the latest known frame that all previous frames (having smaller
  // |frame_id|) and this frame were acked by receiver.
  FrameId last_checkpoint_frame_;
  // This is the first time that |last_checkpoint_frame_| is marked.
  base::TimeTicks last_checkpoint_time_;
  FrameId last_enqueued_frame_;
  base::TimeDelta rtt_;
  size_t history_size_;
  size_t acked_bits_in_history_;
  base::TimeDelta dead_time_in_history_;
};

class FixedCongestionControl final : public CongestionControl {
 public:
  explicit FixedCongestionControl(int bitrate) : bitrate_(bitrate) {}

  FixedCongestionControl(const FixedCongestionControl&) = delete;
  FixedCongestionControl& operator=(const FixedCongestionControl&) = delete;

  ~FixedCongestionControl() final = default;

  // CongestionControl implementation.
  void UpdateRtt(base::TimeDelta rtt) final {}
  void UpdateTargetPlayoutDelay(base::TimeDelta delay) final {}
  void SendFrameToTransport(FrameId frame_id,
                            size_t frame_size_in_bits,
                            base::TimeTicks when) final {}
  void AckFrame(FrameId frame_id, base::TimeTicks when) final {}
  void AckLaterFrames(std::vector<FrameId> received_frames,
                      base::TimeTicks when) final {}
  int GetBitrate(base::TimeTicks playout_time,
                 base::TimeDelta playout_delay) final {
    return bitrate_;
  }

 private:
  const int bitrate_;
};

CongestionControl* NewAdaptiveCongestionControl(const base::TickClock* clock,
                                                int max_bitrate_configured,
                                                int min_bitrate_configured,
                                                double max_frame_rate) {
  return new AdaptiveCongestionControl(clock,
                                       max_bitrate_configured,
                                       min_bitrate_configured,
                                       max_frame_rate);
}

CongestionControl* NewFixedCongestionControl(int bitrate) {
  return new FixedCongestionControl(bitrate);
}

// This means that we *try* to keep our buffer 90% empty.
// If it is less full, we increase the bandwidth, if it is more
// we decrease the bandwidth. Making this smaller makes the
// congestion control more aggressive.
static const double kTargetEmptyBufferFraction = 0.9;

// This is the size of our history in frames. Larger values makes the
// congestion control adapt slower.
static const size_t kHistorySize = 100;

AdaptiveCongestionControl::FrameStats::FrameStats() : frame_size_in_bits(0) {
}

AdaptiveCongestionControl::AdaptiveCongestionControl(
    const base::TickClock* clock,
    int max_bitrate_configured,
    int min_bitrate_configured,
    double max_frame_rate)
    : clock_(clock),
      max_bitrate_configured_(max_bitrate_configured),
      min_bitrate_configured_(min_bitrate_configured),
      max_frame_rate_(max_frame_rate),
      last_frame_stats_(FrameId::first() - 1),
      last_checkpoint_frame_(FrameId::first() - 1),
      last_enqueued_frame_(FrameId::first() - 1),
      history_size_(kHistorySize),
      acked_bits_in_history_(0) {
  DCHECK_GE(max_bitrate_configured, min_bitrate_configured) << "Invalid config";
  DCHECK_GT(min_bitrate_configured, 0);
  frame_stats_.resize(2);
  base::TimeTicks now = clock->NowTicks();
  frame_stats_[0].ack_time = now;
  frame_stats_[0].enqueue_time = now;
  frame_stats_[1].ack_time = now;
  frame_stats_[1].enqueue_time = now;
  last_checkpoint_time_ = now;
  DCHECK(!frame_stats_[0].ack_time.is_null());
}

CongestionControl::~CongestionControl() = default;
AdaptiveCongestionControl::~AdaptiveCongestionControl() = default;

void AdaptiveCongestionControl::UpdateRtt(base::TimeDelta rtt) {
  rtt_ = (7 * rtt_ + rtt) / 8;
}

void AdaptiveCongestionControl::UpdateTargetPlayoutDelay(
    base::TimeDelta delay) {
  const int max_unacked_frames = std::min<int>(
      kMaxUnackedFrames, 1 + (delay * max_frame_rate_).InSeconds());
  DCHECK_GT(max_unacked_frames, 0);
  history_size_ = max_unacked_frames + kHistorySize;
  PruneFrameStats();
}

// Calculate how much "dead air" there is between two frames.
base::TimeDelta AdaptiveCongestionControl::DeadTime(const FrameStats& a,
                                                    const FrameStats& b) {
  if (b.enqueue_time > a.ack_time) {
    return b.enqueue_time - a.ack_time;
  } else {
    return base::TimeDelta();
  }
}

double AdaptiveCongestionControl::CalculateSafeBitrate() {
  DCHECK(!frame_stats_.empty());
  base::TimeDelta transmit_time =
      GetFrameStats(last_checkpoint_frame_)->ack_time -
      frame_stats_.front().enqueue_time - dead_time_in_history_;

  if (acked_bits_in_history_ == 0 || transmit_time <= base::TimeDelta()) {
    return min_bitrate_configured_;
  }
  transmit_time = std::max(transmit_time, base::Milliseconds(1));
  return acked_bits_in_history_ / transmit_time.InSecondsF();
}

AdaptiveCongestionControl::FrameStats* AdaptiveCongestionControl::GetFrameStats(
    FrameId frame_id) {
  int offset = frame_id - last_frame_stats_;
  if (offset > 0) {
    // Sanity-check: Make sure the new |frame_id| will not cause an unreasonably
    // large increase in the history dataset.
    DCHECK_LE(offset, kMaxUnackedFrames + 1);

    frame_stats_.resize(frame_stats_.size() + offset);
    last_frame_stats_ = frame_id;
    offset = 0;
  }
  PruneFrameStats();
  offset += frame_stats_.size() - 1;
  if (offset < 0) {
    DCHECK_LT(frame_id, last_checkpoint_frame_);
    return nullptr;  // Old frame has been pruned from the dataset.
  }
  return &frame_stats_[offset];
}

void AdaptiveCongestionControl::PruneFrameStats() {
  // Maintain a minimal amount of history, specified by |history_size_|, that
  // MUST also include all frames from the last ACK'ed frame.
  const size_t retention_count = std::max<size_t>(
      history_size_, last_frame_stats_ - last_checkpoint_frame_ + 1);

  // Sanity-check: At least one entry must be kept, but the dataset should not
  // grow indefinitely.
  DCHECK_GE(retention_count, 1u);
  constexpr size_t kMaxInFlightRangeSize =
      kMaxUnackedFrames +  // Maximum unACKed frames.
      1 +                  // The last ACKed frame.
      1;  // One not-yet-enqueued frame (see call to EstimatedSendingTime()).
  DCHECK_LE(retention_count, std::max(history_size_, kMaxInFlightRangeSize));

  while (frame_stats_.size() > retention_count) {
    DCHECK(!frame_stats_[0].ack_time.is_null());
    acked_bits_in_history_ -= frame_stats_[0].frame_size_in_bits;
    dead_time_in_history_ -= DeadTime(frame_stats_[0], frame_stats_[1]);
    DCHECK_GE(acked_bits_in_history_, 0UL);
    VLOG(2) << "DT: " << dead_time_in_history_.InSecondsF();
    DCHECK_GE(dead_time_in_history_, base::TimeDelta());
    frame_stats_.pop_front();
  }
}

void AdaptiveCongestionControl::AckFrame(FrameId frame_id,
                                         base::TimeTicks when) {
  FrameStats* frame_stats = GetFrameStats(last_checkpoint_frame_);
  while (last_checkpoint_frame_ < frame_id) {
    FrameStats* last_frame_stats = frame_stats;
    frame_stats = GetFrameStats(last_checkpoint_frame_ + 1);
    // Note: This increment must happen AFTER the GetFrameStats() call to
    // prevent the |last_frame_stats| pointer from being invalidated.
    last_checkpoint_frame_++;
    // When ACKing a frame that was never sent, just pretend it was sent and
    // ACKed at the same point-in-time.
    if (frame_stats->enqueue_time.is_null())
      frame_stats->enqueue_time = when;
    else if (when < frame_stats->enqueue_time)
      when = frame_stats->enqueue_time;
    // Don't overwrite the ack time for those frames that were already acked in
    // previous extended ACKs.
    if (frame_stats->ack_time.is_null())
      frame_stats->ack_time = when;
    DCHECK_GE(when, frame_stats->ack_time);
    acked_bits_in_history_ += frame_stats->frame_size_in_bits;
    dead_time_in_history_ += DeadTime(*last_frame_stats, *frame_stats);
    last_checkpoint_time_ = when;
  }
}

void AdaptiveCongestionControl::AckLaterFrames(
    std::vector<FrameId> received_frames,
    base::TimeTicks when) {
  DCHECK(std::is_sorted(received_frames.begin(), received_frames.end()));
  for (FrameId frame_id : received_frames) {
    if (frame_id <= last_checkpoint_frame_)
      continue;
    FrameStats* frame_stats = GetFrameStats(frame_id);
    // When ACKing a frame that was never sent, just pretend it was sent and
    // ACKed at the same point-in-time.
    if (frame_stats->enqueue_time.is_null())
      frame_stats->enqueue_time = when;
    else if (when < frame_stats->enqueue_time)
      when = frame_stats->enqueue_time;
    // Don't overwrite the ack time for those frames that were acked before.
    if (frame_stats->ack_time.is_null())
      frame_stats->ack_time = when;
    DCHECK_GE(when, frame_stats->ack_time);
  }
}

void AdaptiveCongestionControl::SendFrameToTransport(FrameId frame_id,
                                                     size_t frame_size_in_bits,
                                                     base::TimeTicks when) {
  last_enqueued_frame_ = frame_id;
  FrameStats* frame_stats = GetFrameStats(frame_id);
  DCHECK(frame_stats);
  frame_stats->enqueue_time = when;
  frame_stats->frame_size_in_bits = frame_size_in_bits;
}

base::TimeTicks AdaptiveCongestionControl::EstimatedSendingTime(
    FrameId frame_id,
    double estimated_bitrate) {
  const base::TimeTicks now = clock_->NowTicks();

  // Starting with the time of the latest acknowledgement, extrapolate forward
  // to determine an estimated sending time for |frame_id|.
  //
  // |estimated_sending_time| will contain the estimated sending time for each
  // frame after the last ACK'ed frame.  It is possible for multiple frames to
  // be in-flight; and therefore it is common for the |estimated_sending_time|
  // for those frames to be before |now|.  The initial estimate is based on the
  // last ACKed frame and the RTT.
  base::TimeTicks estimated_sending_time = last_checkpoint_time_ - rtt_;
  for (FrameId f = last_checkpoint_frame_ + 1; f < frame_id; ++f) {
    FrameStats* const stats = GetFrameStats(f);

    // |estimated_ack_time| is the local time when the sender receives the ACK,
    // and not the time when the ACK left the receiver.
    base::TimeTicks estimated_ack_time = stats->ack_time;

    // Do not update the estimate if this frame's packets will never again enter
    // the packet send queue; unless there is no estimate yet.
    if (!estimated_ack_time.is_null())
      continue;

    // Model: The |estimated_sending_time| is the time at which the first byte
    // of the encoded frame is transmitted.  Then, assume the transmission of
    // the remaining bytes is paced such that the last byte has just left the
    // sender at |frame_transmit_time| later.  This last byte then takes
    // ~RTT/2 amount of time to travel to the receiver.  Finally, the ACK from
    // the receiver is sent and this takes another ~RTT/2 amount of time to
    // reach the sender.
    const base::TimeDelta frame_transmit_time =
        base::Seconds(stats->frame_size_in_bits / estimated_bitrate);
    estimated_ack_time = std::max(estimated_sending_time, stats->enqueue_time) +
                         frame_transmit_time + rtt_;

    if (estimated_ack_time < now) {
      // The current frame has not yet been ACK'ed and the yet the computed
      // |estimated_ack_time| is before |now|.  This contradiction must be
      // resolved.
      //
      // The solution below is a little counter-intuitive, but it seems to
      // work.  Basically, when we estimate that the ACK should have already
      // happened, we figure out how long ago it should have happened and
      // guess that the ACK will happen half of that time in the future.  This
      // will cause some over-estimation when acks are late, which is actually
      // the desired behavior.
      estimated_ack_time = now + (now - estimated_ack_time) / 2;
    }

    // Since we [in the common case] do not wait for an ACK before we start
    // sending the next frame, estimate the next frame's sending time as the
    // time just after the last byte of the current frame left the sender (see
    // Model comment above).
    estimated_sending_time =
        std::max(estimated_sending_time, estimated_ack_time - rtt_);
  }

  FrameStats* const frame_stats = GetFrameStats(frame_id);
  DCHECK(frame_stats);
  if (frame_stats->enqueue_time.is_null()) {
    // The frame has not yet been enqueued for transport.  Since it cannot be
    // enqueued in the past, ensure the result is lower-bounded by |now|.
    estimated_sending_time = std::max(estimated_sending_time, now);
  } else {
    // |frame_stats->enqueue_time| is the time the frame was enqueued for
    // transport.  The frame may not actually start being sent until a
    // point-in-time after that, because the transport is waiting for prior
    // frames to be acknowledged.
    estimated_sending_time =
        std::max(estimated_sending_time, frame_stats->enqueue_time);
  }

  return estimated_sending_time;
}

int AdaptiveCongestionControl::GetBitrate(base::TimeTicks playout_time,
                                          base::TimeDelta playout_delay) {
  const double safe_bitrate = CalculateSafeBitrate();
  // Estimate when we might start sending the next frame.
  const base::TimeDelta time_to_catch_up =
      playout_time -
      EstimatedSendingTime(last_enqueued_frame_ + 1, safe_bitrate);

  double empty_buffer_fraction = time_to_catch_up / playout_delay;
  empty_buffer_fraction = std::min(empty_buffer_fraction, 1.0);
  empty_buffer_fraction = std::max(empty_buffer_fraction, 0.0);

  const int bits_per_second = base::ClampRound(
      safe_bitrate * (empty_buffer_fraction / kTargetEmptyBufferFraction));
  VLOG(3) << " FBR:" << (bits_per_second / 1E6)
          << " EBF:" << empty_buffer_fraction
          << " SBR:" << (safe_bitrate / 1E6);
  TRACE_COUNTER_ID1("cast.stream", "Empty Buffer Fraction", this,
                    empty_buffer_fraction);

  return base::clamp(bits_per_second, min_bitrate_configured_,
                     max_bitrate_configured_);
}

}  // namespace cast
}  // namespace media


text:
/**
 * This class is generated by jOOQ
 */
package pl.pg.eti.kio.skroom.model.dba.tables.records;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.Record2;
import org.jooq.Row2;
import org.jooq.impl.TableRecordImpl;

import pl.pg.eti.kio.skroom.model.dba.tables.SqliteSequence;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.8.4"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class SqliteSequenceRecord extends TableRecordImpl<SqliteSequenceRecord> implements Record2<Object, Object> {

    private static final long serialVersionUID = 236725428;

    /**
     * Setter for sqlite_sequence.name.
     */
    public void setName(Object value) {
        set(0, value);
    }

    /**
     * Getter for sqlite_sequence.name.
     */
    public Object getName() {
        return (Object) get(0);
    }

    /**
     * Setter for sqlite_sequence.seq.
     */
    public void setSeq(Object value) {
        set(1, value);
    }

    /**
     * Getter for sqlite_sequence.seq.
     */
    public Object getSeq() {
        return (Object) get(1);
    }

    // -------------------------------------------------------------------------
    // Record2 type implementation
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Row2<Object, Object> fieldsRow() {
        return (Row2) super.fieldsRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Row2<Object, Object> valuesRow() {
        return (Row2) super.valuesRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Object> field1() {
        return SqliteSequence.SQLITE_SEQUENCE.NAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Object> field2() {
        return SqliteSequence.SQLITE_SEQUENCE.SEQ;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object value1() {
        return getName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object value2() {
        return getSeq();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SqliteSequenceRecord value1(Object value) {
        setName(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SqliteSequenceRecord value2(Object value) {
        setSeq(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SqliteSequenceRecord values(Object value1, Object value2) {
        value1(value1);
        value2(value2);
        return this;
    }

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    /**
     * Create a detached SqliteSequenceRecord
     */
    public SqliteSequenceRecord() {
        super(SqliteSequence.SQLITE_SEQUENCE);
    }

    /**
     * Create a detached, initialised SqliteSequenceRecord
     */
    public SqliteSequenceRecord(Object name, Object seq) {
        super(SqliteSequence.SQLITE_SEQUENCE);

        set(0, name);
        set(1, seq);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace kronos
{

class Socket
{
public:
    Socket();
    ~Socket();
    int bindaddr(const char *ip, const uint32_t port);
    int listenaddr();
    void acceptcon(Socket &socket);
    void closecon();
    int sData(unsigned char *buffer, uint32_t size);
    int rData(unsigned char *buffer, uint32_t size);
    void setWsaData(const WSADATA wsadata);
    void setSocket(const SOCKET socket);
    void setAddress(const SOCKADDR_IN address);
    WSADATA getWsaData() const;
    SOCKET getSocket() const;
    SOCKET getSocketAccept() const;
    SOCKADDR_IN getAddress() const;
private:
    WSADATA m_wsaData;
    SOCKET m_socket;
    SOCKADDR_IN m_address;
};

}

#endif // _WIN32

#endif // SOCKET_H


text:
package bootstrap.liftweb

import java.io.File
import java.io.IOException

import com.secdec.codepulse.userSettings

import scala.util.control.Exception.catching
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import org.apache.commons.io.IOUtils
import net.liftweb.common.Loggable
import net.liftweb.http.JsonResponse
import net.liftweb.http.LiftRules
import net.liftweb.http.LiftRulesMocker.toLiftRules
import net.liftweb.json.JsonDSL.pair2jvalue
import net.liftweb.json.JsonDSL.string2jvalue
import com.secdec.codepulse.util.ManualOnDiskFileParamHolder

object FileUploadSetup extends Loggable {

	def init(liftRules: LiftRules) = {
		setupMimeHandler(liftRules)
		setupUploadProgress(liftRules)
		// FileUtils.forceMkdir(tempFileDir)
	}

	def createTempUpload(extension: String): File = {
		val tempFile = File.createTempFile("upload", s".$extension")
		tempFile.deleteOnExit
		tempFile
	}

	def setupMimeHandler(liftRules: LiftRules) = {

		val size = userSettings.maxFileUploadSizeBytes
		liftRules.maxMimeFileSize = size
		liftRules.maxMimeSize = size

		// Send uploaded files to a temp folder instead of putting them in memory
		liftRules.handleMimeFile = (fieldName, contentType, fileName, stream) => {
			/** The session is different between browsers. If you open up chrome and
			  * firefox and browse to the same page, the session will be different
			  * between them. As a counterpoint, 2 separate instances of chrome on
			  * the same computer (e.g. 2 tabs) will connect to the same session, from
			  * what I've seen.
			  * ~Dylan
			  */
			//println("session id (boxed) is " + S.session.map { s => s.uniqueId })

			val uploadFile = {
				import scala.util.control.Exception._
				//copy the stream to a local temp file:
				val tempFile = createTempUpload(Option(FilenameUtils getExtension fileName) getOrElse "data")
				val output = catching(classOf[java.io.IOException]) opt { FileUtils.openOutputStream(tempFile) }
				for (o <- output) {
					try {
						IOUtils.copy(stream, o)
					} catch {
						case e: Exception => logger.error("Exception while handling File Upload", e)
					} finally {
						try {
							// Note: IOUtils.closeQuietly is deprecated
							try { o.close() } catch { case _: Throwable => }
							try { stream.close() } catch { case _: Throwable => }
						}
					}
				}
				tempFile
			}

			logger.debug("handleMimeFile(%s, %s, %s)".format(fieldName, contentType, fileName))
			val result = new ManualOnDiskFileParamHolder(fieldName, contentType, fileName, uploadFile)
			/** The OnDiskFile.. goes to a temp file in your temp folder.
			  */

			result
		}

		liftRules.exceptionHandler.prepend {
			case (mode, req, exc: SizeLimitExceededException) => {
				logger.error(exc)

				val limit = liftRules.maxMimeFileSize / 1024 / 1024
				JsonResponse(("error" -> s"The file is too large (the limit is ${limit} MB)."), List.empty, List.empty, 500)
			}
		}
	}

	def setupUploadProgress(liftRules: LiftRules) = {
		// this is called while uploading files
		liftRules.progressListener = {
			val original = LiftRules.progressListener
			val ret: (Long, Long, Int) => Unit =
				(numRead, numTotal, pItems) =>
					{
						//println("progress Listener " + numRead + " / " + numTotal)
						original(numRead, numTotal, pItems)
					}
			ret

			/** Default implementation just does nothing. If we want to start
			  * streaming uploads and get progress bars, we should leverage this
			  * function, as well as the S.session variable.
			  */
			//println("Read %d / %d bytes on item %d".format(numRead, numTotal, pItems))
		}

	}
}


text:
apt-get update
apt-get install -y python-pip python2.7-dev libzmq-dev
pip install "ipython[notebook]==3.2.1"
pip install emoji


text:
int main(int argc, char *argv[]) {
  try {
    using namespace kaldi;
    typedef kaldi::int32 int32;
    typedef kaldi::int64 int64;
    using fst::SymbolTable;
    using fst::VectorFst;
    using fst::StdArc;

    const char *usage =
        "Copy lattices (e.g. useful for changing to text mode or changing\n"
        "format to standard from compact lattice.)\n"
        "Usage: lattice-copy [options] lattice-rspecifier lattice-wspecifier\n"
        " e.g.: lattice-copy --write-compact=false ark:1.lats ark,t:text.lats\n"
        "See also: lattice-to-fst, and the script "
        "egs/wsj/s5/utils/convert_slf.pl\n";

    ParseOptions po(usage);
    bool write_compact = true;
    po.Register("write-compact", &write_compact,
                "If true, write in normal (compact) form.");

    po.Read(argc, argv);

    if (po.NumArgs() != 2) {
      po.PrintUsage();
      exit(1);
    }

    std::string lats_rspecifier = po.GetArg(1), lats_wspecifier = po.GetArg(2);

    int32 n_done = 0;

    if (write_compact) {
      SequentialCompactLatticeReader lattice_reader(lats_rspecifier);
      CompactLatticeWriter lattice_writer(lats_wspecifier);
      for (; !lattice_reader.Done(); lattice_reader.Next(), n_done++)
        lattice_writer.Write(lattice_reader.Key(), lattice_reader.Value());
    } else {
      SequentialLatticeReader lattice_reader(lats_rspecifier);
      LatticeWriter lattice_writer(lats_wspecifier);
      for (; !lattice_reader.Done(); lattice_reader.Next(), n_done++)
        lattice_writer.Write(lattice_reader.Key(), lattice_reader.Value());
    }
    KALDI_LOG << "Done copying " << n_done << " lattices.";
    return (n_done != 0 ? 0 : 1);
  } catch (const std::exception &e) {
    std::cerr << e.what();
    return -1;
  }
}


text:
<?php

/**
 * Class Properties:
 * @property integer $id
 * @property integer $page_id
 * @property integer $order_Id
 * @property string $title
 * @property string $description
 * @property string $filename
 * @property datetime $date_created
 * @property datetime $date_updated
 */

// Define namespace

namespace Sonic\Model\CMS\Page;

// Start Image Class

class Image extends \Sonic\Model
{

	/**
	 * Database table
	 * @var string
	 */

	public static $dbTable	= 'cms_page_image';

	/**
	 * Class attributes
	 * @var array
	 */

	protected static $attributes = array (
		'id'			=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_INT,
			'charset'	=> 'int_unsigned',
			'min'		=> 1,
			'max'		=> self::INT_MAX_UNSIGNED,
			'default'	=> 0
		),
		'page_id'		=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_INT,
			'charset'	=> 'int_unsigned',
			'min'		=> self::MEDIUMINT_MIN_UNSIGNED,
			'max'		=> self::MEDIUMINT_MAX_UNSIGNED,
			'default'	=> 0,
			'relation'	=> 'Sonic\Model\CMS\Page'
		),
		'order_id'		=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_INT,
			'charset'	=> 'int_unsigned',
			'min'		=> self::INT_MIN_UNSIGNED,
			'max'		=> self::INT_MAX_UNSIGNED,
			'default'	=> 0
		),
		'title'			=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_STRING,
			'charset'	=> 'default',
			'min'		=> self::SMALLINT_MIN_UNSIGNED,
			'max'		=> 1000,
			'default'	=> ''
		),
		'description'	=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_STRING,
			'charset'	=> 'default',
			'min'		=> self::SMALLINT_MIN_UNSIGNED,
			'max'		=> 1000,
			'default'	=> ''
		),
		'filename'		=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_STRING,
			'charset'	=> 'default',
			'min'		=> self::SMALLINT_MIN_UNSIGNED,
			'max'		=> 200,
			'default'	=> ''
		),
		'date_created'	=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_DATETIME,
			'charset'	=> 'datetime',
			'min'		=> 0,
			'max'		=> 19,
			'default'	=> 'CURRENT_UTC_DATE',
			'deupdate'	=> TRUE
		),
		'date_updated'	=> array (
			'get'		=> TRUE,
			'set'		=> TRUE,
			'type'		=> self::TYPE_DATETIME,
			'charset'	=> 'datetime',
			'min'		=> 0,
			'max'		=> 19,
			'default'	=> 'CURRENT_UTC_DATE',
			'creation'	=> TRUE
		)
	);

	/**
	 * Images to manage for this object
	 * This is used to create/resize variations of the uploaded image
	 * and remove all copies when the object is removed.
	 * @var array
	 */

	protected static $images = array (
		'original'	=> array (
			'path'		=> CMS_IMAGE_PATH_ABS,
			'url'		=> CMS_IMAGE_PATH_URL,
		),
		'admin'		=> array (
			'path'		=> CMS_IMAGE_PATH_ABS_ADMIN,
			'url'		=> CMS_IMAGE_PATH_URL_ADMIN,
			'width'		=> 86,
			'height'	=> 65,
			'resize'	=> \Sonic\Resource\Image::RESIZE_CROP,
			'prop'		=> TRUE
		)
	);

	/**
	 * Create the object
	 * @param array $exclude Attributes not to set
	 * @param \PDO $db Database connection to use, default to master resource
	 * @return boolen
	 */

	public function Create ($exclude = array (), &$db = FALSE)
	{

		// If there is no order ID set the next one

		if (!$this->order_id)
		{
			$this->set ('order_id', $this->getNextOrderID ());
		}

		// Call parent method

		$return	= parent::Create ($exclude, $db);

		// If the object was not created

		if (!$return)
		{
			return FALSE;
		}

		// Reindex pages

		$this->reindex ();

		// Return TRUE

		return TRUE;

	}

	/**
	 * Update the object
	 * @param array $exclude Attributes not to set
	 * @param \PDO $db Database connection to use, default to master resource
	 * @return boolean
	 */

	public function Update ($exclude = array (), &$db = FALSE)
	{

		// Call parent method

		$return	= parent::Update ($exclude, $db);

		// If the object was not updated

		if (!$return)
		{
			return FALSE;
		}

		// Reindex pages

		$this->reindex ();

		// Return TRUE

		return TRUE;

	}

	/**
	 * Delete the object
	 * @param array|integer $params Primary key value or parameter array
	 * @param \PDO $db Database connection to use, default to master resource
	 * @param boolean $first First time called, used to process transactions
	 * @return boolan
	 */

	public function Delete ($params = FALSE, &$db = FALSE, $first = TRUE)
	{

		// If there is no file path read the object

		if (!$this->filename)
		{
			$this->Read ();
		}

		// Remove file

		if (!$this->RemoveFile ())
		{
			return FALSE;
		}

		// Call parent

		return parent::Delete ();

	}

	/**
	 * Remove file
	 * @return boolean
	 */

	public function RemoveFile ()
	{

		// If no file return TRUE anyway to delete the database entry

		if (!$this->filename)
		{
			return TRUE;
		}

		foreach (self::$images as $image)
		{
			if (file_exists ($image['path'] . $this->filename) &&
				!unlink ($image['path'] . $this->filename))
			{
				return FALSE;
			}
		}

		// All removed that exist

		return TRUE;

	}

	/**
	 * Return the URL for a file type
	 * @return string
	 */

	public function getURL ($type)
	{

		if (!isset (self::$images[$type]) || !isset (self::$images[$type]['url']))
		{
			return FALSE;
		}

		return self::$images[$type]['url'] . $this->filename;

	}

	/**
	 * Return the admin icon URL
	 * @return string
	 */

	public function getAdminIconURL ()
	{
		return $this->getURL ('admin');
	}

	/**
	 * Upload file
	 * @param array $image File Upload
	 * return boolean
	 */

	public function Upload ($image)
	{

		// Set filename

		$this->filename	= $this->page_id . '_' . $image['name'];

		// Create image object

		$objImage	= new \Sonic\Resource\Image;

		// Set upload

		if (!$objImage->Upload ($image))
		{
			return FALSE;
		}

		// Create uploads

		foreach (self::$images as $image)
		{

			if (!$objImage->setPath ($image['path']))
			{
				$this->RemoveFile ();
				return FALSE;
			}

			$width	= isset ($image['width'])? $image['width'] : FALSE;
			$height	= isset ($image['height'])? $image['height'] : FALSE;
			$resize	= isset ($image['resize'])? $image['resize'] : FALSE;
			$prop	= isset ($image['prop'])? $image['prop'] : FALSE;

			if (!$objImage->createFromUpload ($this->filename, $width, $height, $resize, $prop))
			{
				$this->RemoveFile ();
				return FALSE;
			}

		}

		// Return TRUE

		return TRUE;

	}

	/**
	 * Return the next order ID
	 * @return integer
	 */

	public function getNextOrderID ()
	{

		// Set params

		$params	= array (
			'select'	=> 'order_id',
			'where'		=> array (
				array ('page_id', $this->page_id)
			),
			'orderby'	=> 'order_id DESC'
		);

		// Get order ID

		$orderID	= $this->getValue ($params);

		// Return next ID

		return (int)$orderID + 1;

	}

	/**
	 * Reindex a page image order ids
	 * @return void
	 */

	public function reindex ()
	{

		// Set parameters

		$params['where'][]	= array ('page_id',	$this->page_id);
		$params['orderby'] = 'order_id ASC, date_updated DESC';

		// Get images

		$images	= static::_getObjects ($params);

		// Only continue if there are images

		if (!$images)
		{
			return;
		}

		// Prepare update query

		$query	= $this->db->prepare ('
			UPDATE ' . static::$dbTable . '
			SET order_id = :order_id
			WHERE ' . static::$pk . ' = :image_id
		');

		// Reindex each page

		foreach ($images as $key => $image)
		{

			// Bind params

			$query->bindValue (':order_id',	$key + 1);
			$query->bindValue (':image_id',	$image->getPK ());

			// Execute query

			try
			{
				$query->execute ();
			}

			// Catch PDOException

			catch (PDOException $e)
			{
				new \Sonic\Message ('error', $e->getMessage ());
			}

		}

	}

	/**
	 * Export JSON string of object properties and admin icon URL
	 * @return string
	 */

	public function exportJSON ()
	{
		return json_encode ($this->toArray (array ('id', 'page_id', 'order_id', 'title', 'description', 'filename'),
			array (
				'icon' => array ('$this', 'getAdminIconURL')
			)
		));
	}

}

// End Image Class


text:
const convertLocationSearchToObject = (locationSearch: string): Record<string, string> => {
  return locationSearch
    .replace('?', '')
    .split('&')
    .filter(Boolean)
    .reduce((allOptions, option) => {
      const [optionName, optionValue] = option.split('=').slice(0, 2);
      return { ...allOptions, [optionName]: optionValue };
    }, {});
};

export { convertLocationSearchToObject };


text:
package com.koch.ambeth.ioc;

/**
 * Interface for beans that need to initialize or check things after all injections have been made.
 */
public interface IInitializingBean {
	/**
	 * Implement initializations and checks in this method to be run after the bean has been prepared
	 * by the IoC container.
	 *
	 * @throws Throwable
	 */
	void afterPropertiesSet() throws Throwable;
}


text:
NSString * const CLURLAboutSites = @"http://www.craigslist.org/about/sites";

@interface ContinentsViewController ()
@property (nonatomic,strong) NSDictionary *locationsTree;
@end

@implementation ContinentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(loadData)];
    [self loadData];
}

- (void) loadData {
    NSURL *URLlocationsXSL = [[NSBundle mainBundle] URLForResource:@"locations" withExtension:@"xsl"];
    NSURL *URL = [NSURL URLWithString:CLURLAboutSites];
    NSString *baseURL = [[URL.scheme stringByAppendingString:@"://"] stringByAppendingString:URL.host];
    SkyXSLTransformation *transformation = [[SkyXSLTransformation alloc] initWithXSLTURL:URLlocationsXSL];
    SkyHTMLResponseSerializer *serializer = [SkyHTMLResponseSerializer serializerWithXSLTransformation:transformation params:@{@"URL":QUOTED(RSLASH(URL.absoluteString)),@"baseURL":QUOTED(baseURL)} modelAdapter:nil];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager new];
    manager.responseSerializer = serializer;

    __typeof(self) __weak weakSelf = self;
    [manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        weakSelf.locationsTree = responseObject;
        NSLog(@"locationstree=%@",responseObject);
        [weakSelf redisplayData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        NSLog(@"%@",error);
    }];

    [SVProgressHUD showWithStatus:@"Loading locations..."];
}

- (void) redisplayData {
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.locationsTree[@"continents"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"StateCell"];
    cell.textLabel.text = self.locationsTree[@"continents"][indexPath.row][@"name"];
    return cell;
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    StatesViewController *statesVC = segue.destinationViewController;
    NSDictionary *continent = self.locationsTree[@"continents"][[self.tableView indexPathForSelectedRow].row];
    statesVC.states = continent[@"states"];
    statesVC.title = continent[@"name"];
}

@end


text:
require 'molinillo/dependency_graph/action'
module Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#delete_edge)
    class DeleteEdge < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :delete_edge
      end

      # (see Action#up)
      def up(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges.delete(edge)
        edge.destination.incoming_edges.delete(edge)
      end

      # (see Action#down)
      def down(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges << edge
        edge.destination.incoming_edges << edge
        edge
      end

      # @!group DeleteEdge

      # @return [String] the name of the origin of the edge
      attr_reader :origin_name

      # @return [String] the name of the destination of the edge
      attr_reader :destination_name

      # @return [Object] the requirement that the edge represents
      attr_reader :requirement

      # @param  [DependencyGraph] graph the graph to find vertices from
      # @return [Edge] The edge this action adds
      def make_edge(graph)
        Edge.new(
          graph.vertex_named(origin_name),
          graph.vertex_named(destination_name),
          requirement
        )
      end

      # Initialize an action to add an edge to a dependency graph
      # @param [String] origin_name the name of the origin of the edge
      # @param [String] destination_name the name of the destination of the edge
      # @param [Object] requirement the requirement that the edge represents
      def initialize(origin_name, destination_name, requirement)
        @origin_name = origin_name
        @destination_name = destination_name
        @requirement = requirement
      end
    end
  end
end


text:
% Author: Carl Doersch (cdoersch at cs dot cmu dot edu)
%
% builtin strcmp returns false for empty strings that have different 'sizes'
function res=mystrcmp(str1, str2)
  res=((numel(str1)==0)&&(numel(str2)==0))||strcmp(str1,str2);
end


text:
package org.gradoop.flink.model.impl.operators.neighborhood.functions;

import org.apache.flink.api.common.functions.GroupReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import org.gradoop.common.model.impl.pojo.Edge;
import org.gradoop.common.model.impl.pojo.Vertex;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.api.functions.EdgeAggregateFunction;

/**
 * Sets the aggregation result as property for each vertex. All edges together with the
 * relevant vertex were grouped.
 */
public class NeighborEdgeReduceFunction
  extends NeighborEdgeFunction
  implements GroupReduceFunction<Tuple2<Edge, Vertex>, Vertex> {

  /**
   * Valued constructor.
   *
   * @param function edge aggregation function
   */
  public NeighborEdgeReduceFunction(EdgeAggregateFunction function) {
    super(function);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void reduce(Iterable<Tuple2<Edge, Vertex>> tuples, Collector<Vertex> collector) throws
    Exception {

    PropertyValue propertyValue = PropertyValue.NULL_VALUE;
    Vertex vertex = null;
    Edge edge;
    boolean isFirst = true;

    for (Tuple2<Edge, Vertex> tuple: tuples) {
      edge = tuple.f0;
      if (isFirst) {
        //each tuple contains the same vertex
        vertex = tuple.f1;
        isFirst = false;
        propertyValue = getFunction().getEdgeIncrement(edge);
      } else {
        propertyValue = getFunction()
          .aggregate(propertyValue, getFunction().getEdgeIncrement(edge));
      }
    }
    vertex.setProperty(getFunction().getAggregatePropertyKey(), propertyValue);
    collector.collect(vertex);
  }
}


text:
package net.liutikas.mrsad;

import com.badlogic.gdx.graphics.Color;

public class Constants {
    // World constants
    public static final float WORLD_SIZE = 128f;
    public static final Color WORLD_COLOR = Color.SKY;
    public static final float WORLD_DEATH_PLANE = -128f;

    // Player constants
    public static final float PLAYER_WALK_SPEED = 80f;
    public static final float PLAYER_JUMP_SPEED = 120f;
    public static final float PLAYER_MAX_JUMP_DURATION = 0.3f;
    public static final float PLAYER_TEXTURE_WIDTH = 32f;
    public static final float PLAYER_FEET_WIDTH = 15f;
    public static final float GRAVITY_ACCELERATION = 500f;

    // Assets constants
    public static final String TEXTURE_ATLAS = "images/mrsad.pack.atlas";
    public static final String PLATFORM_BACKGROUND = "platform";
    public static final int PLATFORM_EDGE = 10;
    public static final String STANDING_LEFT = "player-left";
    public static final String STANDING_RIGHT = "player-right";
    public static final String JUMPING_LEFT = "player-jumping-left";
    public static final String JUMPING_RIGHT = "player-jumping-right";
    public static final float WALK_LOOP_DURATION = 0.15f;
    public static final String WALKING_RIGHT_1 = "player-walking-right-1";
    public static final String WALKING_RIGHT_2 = "player-walking-right-2";
    public static final String WALKING_RIGHT_3 = "player-walking-right-3";
    public static final String WALKING_LEFT_1 = "player-walking-left-1";
    public static final String WALKING_LEFT_2 = "player-walking-left-2";
    public static final String WALKING_LEFT_3 = "player-walking-left-3";
    public static final String SAD_PILL = "sad-pill";

    // Level Loading
    public static final String LEVEL_COMPOSITE = "composite";
    public static final String LEVEL_9PATCHES = "sImage9patchs";
    public static final String LEVEL_ERROR_MESSAGE = "There was a problem loading the level.";
    public static final String LEVEL_X_KEY = "x";
    public static final String LEVEL_Y_KEY = "y";
    public static final String LEVEL_WIDTH_KEY = "width";
    public static final String LEVEL_HEIGHT_KEY = "height";
    public static final String LEVEL_1 = "levels/Level1.dt";
}


text:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace ownshotLin
{
	class MainClass
	{
		static int ssnamelength = 4;
		public static void Main(string[] args)
		{
			var configpath = Path.GetDirectoryName(Application.ExecutablePath) + "/";
			var chars = "abcdefghijklmnopqrstuvwxyz0123456789"; //ABCDEFGHIJKLMNOPQRSTUVWXYZ
			var stringChars = new char[ssnamelength];
			var random = new Random();
			for (int i = 0; i < stringChars.Length; i++)
			{
				stringChars[i] = chars[random.Next(chars.Length)];
			}
			var finalString = new string(stringChars) + ".png";
			TakeScreenshot(configpath + finalString);
			Console.WriteLine(finalString);

			try
			{
				var request = (FtpWebRequest)WebRequest.Create(File.ReadAllText(configpath + "ftpdir.txt").Replace("imagename", finalString));
				request.Method = WebRequestMethods.Ftp.UploadFile;

				request.Credentials = new NetworkCredential(File.ReadAllText(configpath + "ftpuser.txt"), File.ReadAllText(configpath + "ftppass.txt"));

				var fileContents = File.ReadAllBytes(configpath + finalString);
				request.ContentLength = fileContents.Length;

				var requestStream = request.GetRequestStream();
				requestStream.Write(fileContents, 0, fileContents.Length);
				requestStream.Close();

				var link = File.ReadAllText(configpath + "serverlink.txt").Replace("imagename", finalString);
				var response = (FtpWebResponse)request.GetResponse();

				var proc = new System.Diagnostics.Process();
				proc.StartInfo.FileName = "/usr/bin/notify-send";
				proc.StartInfo.Arguments = ("'Screenshot Get!' '" + link + "' --icon=dialog-information");
				proc.StartInfo.UseShellExecute = false;
				proc.StartInfo.RedirectStandardOutput = false;
				proc.Start();

				requestStream.Dispose();
				response.Close();

			}
			catch
			{
				var proc = new System.Diagnostics.Process();
				proc.StartInfo.FileName = "/usr/bin/notify-send";
				proc.StartInfo.Arguments = ("'Error while uploading!' 'Please try again!' --icon=dialog-error");
				proc.StartInfo.UseShellExecute = false;
				proc.StartInfo.RedirectStandardOutput = false;
				proc.Start();
			}
		}

		public static void TakeScreenshot(string filePath)
		{
			using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
				                                 Screen.PrimaryScreen.Bounds.Height)) {
				using (Graphics g = Graphics.FromImage(bmpScreenCapture)) {
					g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
						Screen.PrimaryScreen.Bounds.Y,
						0, 0,
						bmpScreenCapture.Size,
						CopyPixelOperation.SourceCopy);
				}
				bmpScreenCapture.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
			}
		}
	}
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Esprima: Speed Comparison</title>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>

← Home

Code

Documentation

Issues

Compare with other parsers

Time measurement is carried out using Benchmark.js.

Esprima version .

Please wait...
<input id="run" type="submit" value="Run speed comparison" disabled />

        Source
        Size (KiB)
        Esprima
        parse-js
        ZeParser
        Narcissus

        jQuery 1.7.1

        Prototype 1.7.0.0

        MooTools 1.4.1

        Ext Core 3.1.0

        Total

Warning: Since each parser has a different format for the syntax tree, the speed is not fully comparable (the cost of constructing different result is not taken into account). These tests exist only to ensure that Esprima parser is not ridiculously slow compare to other parsers.

parse-js is the parser used in UglifyJS. It's a JavaScript port of the Common LISP version. This test uses parse-js from UglifyJS version 1.2.5 (Jan 13 2011).

ZeParser is from github.com/qfox/ZeParser revision 0072a617 (dated May 29 2012). Beside the syntax tree, ZeParser also provides location info for the syntax nodes, as well as the list of all tokens.

Narcissus is Mozilla's JavaScript engine implemented in JavaScript. This test uses the parser from Narcissus, taken from its
code repository revision b5caa7df (dated Oct 26 2011). Narcissus supports many extensions (generators, comprehension, destructuring, etc) and therefore it takes longer to parse JavaScript code. Narcissus parser output also contains the location info for the syntax node. Note: Narcissus will not work if Object.create and Object.defineProperty are not available.

Esprima is created by
Ariya Hidayat. Follow @ariyahidayat on Twitter.


text:
#pragma once
#include <aws/events/CloudWatchEvents_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace CloudWatchEvents
{
namespace Model
{

  /**
   *
Information about the EC2 instances that are to be sent the command,
   * specified as key-value pairs. Each RunCommandTarget block can
   * include only one key, but this key may specify multiple values.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_CLOUDWATCHEVENTS_API RunCommandTarget
  {
  public:
    RunCommandTarget();
    RunCommandTarget(Aws::Utils::Json::JsonView jsonValue);
    RunCommandTarget& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline const Aws::String& GetKey() const{ return m_key; }

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline bool KeyHasBeenSet() const { return m_keyHasBeenSet; }

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline void SetKey(const Aws::String& value) { m_keyHasBeenSet = true; m_key = value; }

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline void SetKey(Aws::String&& value) { m_keyHasBeenSet = true; m_key = std::move(value); }

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline void SetKey(const char* value) { m_keyHasBeenSet = true; m_key.assign(value); }

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline RunCommandTarget& WithKey(const Aws::String& value) { SetKey(value); return *this;}

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline RunCommandTarget& WithKey(Aws::String&& value) { SetKey(std::move(value)); return *this;}

    /**
     *
Can be either tag: tag-key or
     * InstanceIds.

     */
    inline RunCommandTarget& WithKey(const char* value) { SetKey(value); return *this;}

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline const Aws::Vector<Aws::String>& GetValues() const{ return m_values; }

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline bool ValuesHasBeenSet() const { return m_valuesHasBeenSet; }

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline void SetValues(const Aws::Vector<Aws::String>& value) { m_valuesHasBeenSet = true; m_values = value; }

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline void SetValues(Aws::Vector<Aws::String>&& value) { m_valuesHasBeenSet = true; m_values = std::move(value); }

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline RunCommandTarget& WithValues(const Aws::Vector<Aws::String>& value) { SetValues(value); return *this;}

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline RunCommandTarget& WithValues(Aws::Vector<Aws::String>&& value) { SetValues(std::move(value)); return *this;}

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline RunCommandTarget& AddValues(const Aws::String& value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline RunCommandTarget& AddValues(Aws::String&& value) { m_valuesHasBeenSet = true; m_values.push_back(std::move(value)); return *this; }

    /**
     *
If Key is tag: tag-key, Values
     * is a list of tag values. If Key is InstanceIds,
     * Values is a list of Amazon EC2 instance IDs.

     */
    inline RunCommandTarget& AddValues(const char* value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }

  private:

    Aws::String m_key;
    bool m_keyHasBeenSet = false;

    Aws::Vector<Aws::String> m_values;
    bool m_valuesHasBeenSet = false;
  };

} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws


text:
<?php require_once("config.php"); ?>
<?php include("header.php"); ?>

Harambe
                the heroic gorilla

Home

About Harambe

It was only one day after his 17th birthday.
                Harambe was killed right after a 3 year old child fell into his habitat in Cincinnati Zoo.
                Although Harambe did not do any harm to the boy and carried him to a safer place, zoo officials were agreed upon killing Harambe.
                A single gunshot was fired.
                Maybe it was the right decision, however he should not have been put in a cage in the first place.
                Animals should be free, and so are the softwares.

As long as he is remembered, he will not really die at all.

 Further reading

<?php include("footer.php"); ?>


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

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

    <title>Penlight Documentation</title>
    <link rel="stylesheet" href="../ldoc_fixed.css" type="text/css" />

<big></big>

Penlight

GitHub Project

Documentation

Contents

Purpose

To Inject or not to Inject?

What are function arguments in Penlight?

Pros and Cons of Loopless Programming

Generally useful functions

Application Support

Simplifying Object-Oriented Programming in Lua

Manual

Introduction

Tables and Arrays

Strings. Higher-level operations on strings.

Paths and Directories

Date and Time

Data

Functional Programming

Additional Libraries

Technical Choices

Libraries

pl

pl.app

pl.array2d

pl.class

pl.compat

pl.comprehension

pl.config

pl.data

pl.dir

pl.file

pl.func

pl.import_into

pl.input

pl.lapp

pl.lexer

pl.luabalanced

pl.operator

pl.path

pl.permute

pl.pretty

pl.seq

pl.sip

pl.strict

pl.stringio

pl.stringx

pl.tablex

pl.template

pl.test

pl.text

pl.types

pl.url

pl.utils

pl.xml

Classes

pl.Date

pl.List

pl.Map

pl.MultiMap

pl.OrderedMap

pl.Set

Examples

seesubst.lua

sipscan.lua

symbols.lua

test-cmp.lua

test-data.lua

test-listcallbacks.lua

test-pretty.lua

test-symbols.lua

testclone.lua

testconfig.lua

testglobal.lua

testinputfields.lua

testinputfields2.lua

testxml.lua

which.lua

Introduction

Purpose

It is often said of Lua that it does not include batteries. That is because the
goal of Lua is to produce a lean expressive language that will be used on all
sorts of machines, (some of which don't even have hierarchical filesystems). The
Lua language is the equivalent of an operating system kernel; the creators of Lua
do not see it as their responsibility to create a full software ecosystem around
the language. That is the role of the community.

A principle of software design is to recognize common patterns and reuse them. If
you find yourself writing things like `io.write(string.format('the answer is %d
',42))` more than a number of times then it becomes useful just to define a
function printf. This is good, not just because repeated code is harder to
maintain, but because such code is easier to read, once people understand your
libraries.

Penlight captures many such code patterns, so that the intent of your code
becomes clearer. For instance, a Lua idiom to copy a table is {unpack(t)}, but
this will only work for 'small' tables (for a given value of 'small') so it is
not very robust. Also, the intent is not clear. So tablex.deepcopy is provided,
which will also copy nested tables and and associated metatables, so it can be
used to clone complex objects.

The default error handling policy follows that of the Lua standard libraries: if
a argument is the wrong type, then an error will be thrown, but otherwise we
return nil,message if there is a problem. There are some exceptions; functions
like input.fields default to shutting down the program immediately with a
useful message. This is more appropriate behaviour for a script than providing
a stack trace. (However, this default can be changed.) The lexer functions always
throw errors, to simplify coding, and so should be wrapped in pcall.

If you are used to Python conventions, please note that all indices consistently
start at 1.

The Lua function table.foreach has been deprecated in favour of the for in
statement, but such an operation becomes particularly useful with the
higher-order function support in Penlight. Note that tablex.foreach reverses
the order, so that the function is passed the value and then the key. Although
perverse, this matches the intended use better.

The only important external dependence of Penlight is
LuaFileSystem
(lfs), and if you want dir.copyfile to work cleanly on Windows, you will need
either alien or be using
LuaJIT as well. (The fallback is to call the equivalent
shell commands.)

To Inject or not to Inject?

It was realized a long time ago that large programs needed a way to keep names
distinct by putting them into tables (Lua), namespaces (C++) or modules
(Python).  It is obviously impossible to run a company where everyone is called
'Bruce', except in Monty Python skits. These 'namespace clashes' are more of a
problem in a simple language like Lua than in C++, because C++ does more
complicated lookup over 'injected namespaces'.  However, in a small group of
friends, 'Bruce' is usually unique, so in particular situations it's useful to
drop the formality and not use last names. It depends entirely on what kind of
program you are writing, whether it is a ten line script or a ten thousand line
program.

So the Penlight library provides the formal way and the informal way, without
imposing any preference. You can do it formally like:

local utils = require 'pl.utils'
utils.printf("%s\n","hello, world!")

or informally like:

require 'pl'
utils.printf("%s\n","That feels better")

require 'pl' makes all the separate Penlight modules available, without needing
to require them each individually.

Generally, the formal way is better when writing modules, since then there are no
global side-effects and the dependencies of your module are made explicit.

Andrew Starks has contributed another way, which balances nicely between the
formal need to keep the global table uncluttered and the informal need for
convenience. require'pl.import_into' returns a function, which accepts a table
for injecting Penlight into, or if no table is given, it passes back a new one.

local pl = require'pl.import_into'()

The table pl is a 'lazy table' which loads modules as needed, so we can then
use pl.utils.printf and so forth, without an explicit `require' or harming any
globals.

If you are using _ENV with Lua 5.2 to define modules, then here is a way to
make Penlight available within a module:

local _ENV,M = require 'pl.import_into' ()

function answer ()
    -- all the Penlight modules are available!
    return pretty.write(utils.split '10 20  30', '')
end

return M

The default is to put Penlight into \_ENV, which has the unintended effect of
making it available from the module (much as module(...,package.seeall) does).
To satisfy both convenience and safety, you may pass true to this function, and
then the module M is not the same as \_ENV, but only contains the exported
functions.

Otherwise, Penlight will not bring in functions into the global table, or
clobber standard tables like 'io'.  require('pl') will bring tables like
'utils','tablex',etc into the global table if they are used. This
'load-on-demand' strategy ensures that the whole kitchen sink is not loaded up
front,  so this method is as efficient as explicitly loading required modules.

You have an option to bring the pl.stringx methods into the standard string
table. All strings have a metatable that allows for automatic lookup in string,
so we can say s:upper(). Importing stringx allows for its functions to also
be called as methods: s:strip(),etc:

require 'pl'
stringx.import()

or, more explicitly:

require('pl.stringx').import()

A more delicate operation is importing tables into the local environment. This is
convenient when the context makes the meaning of a name very clear:

> require 'pl'
> utils.import(math)
> = sin(1.2)
0.93203908596723

utils.import can also be passed a module name as a string, which is first
required and then imported. If used in a module, import will bring the symbols
into the module context.

Keeping the global scope simple is very necessary with dynamic languages. Using
global variables in a big program is always asking for trouble, especially since
you do  not have the spell-checking provided by a compiler. The pl.strict
module enforces a simple rule: globals must be 'declared'.  This means that they
must be assigned before use; assigning to nil is sufficient.

> require 'pl.strict'
> print(x)
stdin:1: variable 'x' is not declared
> x = nil
> print(x)
nil

The strict module provided by Penlight is compatible with the 'load-on-demand'
scheme used by require 'pl.

strict also disallows assignment to global variables, except in the main
program. Generally, modules have no business messing with global scope; if you
must do it, then use a call to rawset. Similarly, if you have to check for the
existence of a global, use rawget.

If you wish to enforce strictness globally, then just add require 'pl.strict'
at the end of pl/init.lua, otherwise call it from your main program.

As from 1.1.0, this module provides a strict.module function which creates (or
modifies) modules so that accessing an unknown function or field causes an error.

For example,

-- mymod.lua
local strict = require 'pl.strict'
local M = strict.module (...)

function M.answer ()
    return 42
end

return M

If you were to accidently type mymod.Answer(), then you would get a runtime
error: "variable 'Answer' is not declared in 'mymod'".

This can be applied to existing modules. You may desire to have the same level
of checking for the Lua standard libraries:

strict.make_all_strict(_G)

Thereafter a typo such as math.cosine will give you an explicit error, rather
than merely returning a nil that will cause problems later.

What are function arguments in Penlight?

Many functions in Penlight themselves take function arguments, like map which
applies a function to a list, element by element.  You can use existing
functions, like math.max, anonymous functions (like `function(x,y) return x > y
end ), or operations by name (e.g '*' or '..').  The module pl.operator` exports
all the standard Lua operations, like the Python module of the same name.
Penlight allows these to be referred to by name, so operator.gt can be more
concisely expressed as '>'.

Note that the map functions pass any extra arguments to the function, so we can
have ls:filter('>',0), which is a shortcut for
ls:filter(function(x) return x > 0 end).

Finally, pl.func supports placeholder expressions in the Boost lambda style,
so that an anonymous function to multiply the two arguments can be expressed as
\1*\2.

To use them directly, note that all function arguments in Penlight go through
utils.function_arg. pl.func registers itself with this function, so that you
can directly use placeholder expressions with standard methods:

> _1 = func._1
> = List{10,20,30}:map(_1+1)
{11,21,31}

Another option for short anonymous functions is provided by
utils.string_lambda; this is invoked automatically:

> = List{10,20,30}:map '|x| x + 1'
{11,21,31}

Pros and Cons of Loopless Programming

The standard loops-and-ifs 'imperative' style of programming is dominant, and
often seems to be the 'natural' way of telling a machine what to do. It is in
fact very much how the machine does things, but we need to take a step back and
find ways of expressing solutions in a higher-level way.  For instance, applying
a function to all elements of a list is a common operation:

local res = {}
for i = 1,#ls do
    res[i] = fun(ls[i])
end

This can be efficiently and succintly expressed as ls:map(fun). Not only is
there less typing but the intention of the code is clearer. If readers of your
code spend too much time trying to guess your intention by analyzing your loops,
then you have failed to express yourself clearly. Similarly, ls:filter('>',0)
will give you all the values in a list greater than zero. (Of course, if you
don't feel like using List, or have non-list-like tables, then pl.tablex
offers the same facilities. In fact, the List methods are implemented using
tablex functions.)

A common observation is that loopless programming is less efficient, particularly
in the way it uses memory. ls1:map2('*',ls2):reduce '+' will give you the dot
product of two lists, but an unnecessary temporary list is created.  But
efficiency is relative to the actual situation, it may turn out to be fast
enough, or may not appear in any crucial inner loops, etc.

Writing loops is 'error-prone and tedious', as Stroustrup says. But any
half-decent editor can be taught to do much of that typing for you. The question
should actually be: is it tedious to read loops?  As with natural language,
programmers tend to read chunks at a time. A for-loop causes no surprise, and
probably little brain activity. One argument for loopless programming is the
loops that you do write stand out more, and signal 'something different
happening here'.  It should not be an all-or-nothing thing, since most programs
require a mixture of idioms that suit the problem.  Some languages (like APL) do
nearly everything with map and reduce operations on arrays, and so solutions can
sometimes seem forced. Wisdom is knowing when a particular idiom makes a
particular problem easy to solve and the solution easy to explain afterwards.

Generally useful functions.

The function printf discussed earlier is included in pl.utils because it
makes properly formatted output easier. (There is an equivalent fprintf which
also takes a file object parameter, just like the C function.)

Splitting a string using a delimiter is a fairly common operation, hence split.

Utility functions like is_type help with identifying what
kind of animal you are dealing with.
The Lua type function handles the basic types, but can't distinguish between
different kinds of objects, which are all tables. So is_type handles both
cases, like is_type(s,"string") and is_type(ls,List).

A common pattern when working with Lua varargs is capturing all the arguments in
a table:

function t(...)
    local args = {...}
    ...
end

But this will bite you someday when nil is one of the arguments, since this
will put a 'hole' in your table. In particular, #ls will only give you the size
upto the nil value.  Hence the need for table.pack - this is a new Lua 5.2
function which Penlight defines also for Lua 5.1.

function t(...)
    local args,n = table.pack(...)
    for i = 1,n do
      ...
    end
end

The 'memoize' pattern occurs when you have a function which is expensive to call,
but will always return the same value subsequently. utils.memoize is given a
function, and returns another function. This calls the function the first time,
saves the value for that argument, and thereafter for that argument returns the
saved value.  This is a more flexible alternative to building a table of values
upfront, since in general you won't know what values are needed.

sum = utils.memoize(function(n)
    local sum = 0
    for i = 1,n do sum = sum + i end
    return sum
end)
...
s = sum(1e8) --takes time!
...
s = sum(1e8) --returned saved value!

Penlight is fully compatible with Lua 5.1, 5.2 and LuaJIT 2. To ensure this,
utils also defines the global Lua 5.2
load function as utils.load

the input (either a string or a function)

the source name used in debug information

the mode is a string that can have either or both of 'b' or 't', depending on
    whether the source is a binary chunk or text code (default is 'bt')

the environment for the compiled chunk

Using utils.load should reduce the need to call the deprecated function setfenv,
and make your Lua 5.1 code 5.2-friendly.

The utils module exports getfenv and setfenv for
Lua 5.2 as well, based on code by Sergey Rozhenko.  Note that these functions can fail
for functions which don't access any globals.

Application Support

app.parse_args is a simple command-line argument parser. If called without any
arguments, it tries to use the global arg array.  It returns the flags
(options begining with '-') as a table of name/value pairs, and the arguments
as an array.  It knows about long GNU-style flag names, e.g. --value, and
groups of short flags are understood, so that -ab is short for -a -b. The
flags result would then look like {value=true,a=true,b=true}.

Flags may take values. The command-line --value=open -n10 would result in
{value='open',n='10'}; generally you can use '=' or ':' to separate the flag
from its value, except in the special case where a short flag is followed by an
integer.  Or you may specify upfront that some flags have associated values, and
then the values will follow the flag.

> require 'pl'
> flags,args = app.parse_args({'-o','fred','-n10','fred.txt'},{o=true})
> pretty.dump(flags)
{o='fred',n='10'}

parse_args is not intelligent or psychic; it will not convert any flag values
or arguments for you, or raise errors. For that, have a look at
Lapp.

An application which consists of several files usually cannot use require to
load files in the same directory as the main script.  app.require_here()
ensures that the Lua module path is modified so that files found locally are
found first. In the examples directory, test-symbols.lua uses this function
to ensure that it can find symbols.lua even if it is not run from this directory.

app.appfile will create a filename that your application can use to store its
private data, based on the script name. For example, app.appfile "test.txt"
from a script called testapp.lua produces the following file on my Windows
machine:

C:\Documents and Settings\SJDonova\.testapp\test.txt

and the equivalent on my Linux machine:

/home/sdonovan/.testapp/test.txt

If .testapp does not exist, it will be created.

Penlight makes it convenient to save application data in Lua format. You can use
pretty.dump(t,file) to write a Lua table in a human-readable form to a file,
and pretty.read(file.read(file)) to generate the table again, using the
pretty module.

Simplifying Object-Oriented Programming in Lua

Lua is similar to JavaScript in that the concept of class is not directly
supported by the language. In fact, Lua has a very general mechanism for
extending the behaviour of tables which makes it straightforward to implement
classes. A table's behaviour is controlled by its metatable. If that metatable
has a \\index function or table, this will handle looking up anything which is
not found in the original table. A class is just a table with an __index key
pointing to itself. Creating an object involves making a table and setting its
metatable to the class; then when handling obj.fun, Lua first looks up fun in
the table obj, and if not found it looks it up in the class. obj:fun(a) is
just short for obj.fun(obj,a). So with the metatable mechanism and this bit of
syntactic sugar, it is straightforward to implement classic object orientation.

-- animal.lua

class = require 'pl.class'

class.Animal()

function Animal:_init(name)
    self.name = name
end

function Animal:__tostring()
  return self.name..': '..self:speak()
end

class.Dog(Animal)

function Dog:speak()
  return 'bark'
end

class.Cat(Animal)

function Cat:_init(name,breed)
    self:super(name)  -- must init base!
    self.breed = breed
end

function Cat:speak()
  return 'meow'
end

class.Lion(Cat)

function Lion:speak()
  return 'roar'
end

fido = Dog('Fido')
felix = Cat('Felix','Tabby')
leo = Lion('Leo','African')

$ lua -i animal.lua
> = fido,felix,leo
Fido: bark      Felix: meow     Leo: roar
> = leo:is_a(Animal)
true
> = leo:is_a(Dog)
false
> = leo:is_a(Cat)
true

All Animal does is define \\tostring, which Lua will use whenever a string
representation is needed of the object. In turn, this relies on speak, which is
not defined. So it's what C++ people would call an abstract base class; the
specific derived classes like Dog define speak. Please note that if derived
classes have their own constructors, they must explicitly call the base
constructor for their base class; this is conveniently available as the super
method.

Note that (as always) there are multiple ways to implement OOP in Lua; this method
uses the classic 'a class is the __index of its objects' but does 'fat inheritance';
methods from the base class are copied into the new class. The advantage of this is
that you are not penalized for long inheritance chains, for the price of larger classes,
but generally objects outnumber classes! (If not, something odd is going on with your design.)

All such objects will have a is_a method, which looks up the inheritance chain
to find a match.  Another form is class_of, which can be safely called on all
objects, so instead of leo:is_a(Animal) one can say Animal:class_of(leo).

There are two ways to define a class, either class.Name() or Name = class();
both work identically, except that the first form will always put the class in
the current environment (whether global or module); the second form provides more
flexibility about where to store the class. The first form does name the class
by setting the _name field, which can be useful in identifying the objects of
this type later. This session illustrates the usefulness of having named classes,
if no __tostring method is explicitly defined.

> class.Fred()
> a = Fred()
> = a
Fred: 00459330
> Alice = class()
> b = Alice()
> = b
table: 00459AE8
> Alice._name = 'Alice'
> = b
Alice: 00459AE8

So Alice = class(); Alice._name = 'Alice' is exactly the same as class.Alice().

This useful notation is borrowed from Hugo Etchegoyen's
classlib which further
extends this concept to allow for multiple inheritance. Notice that the
more convenient form puts the class name in the current environment! That is,
you may use it safely within modules using the old-fashioned module()
or the new _ENV mechanism.

There is always more than one way of doing things in Lua; some may prefer this
style for creating classes:

local class = require 'pl.class'

class.Named {
    _init = function(self,name)
        self.name = name
    end;

    __tostring = function(self)
        return 'boo '..self.name
    end;
}

b = Named 'dog'
print(b)
--> boo dog

Note that you have to explicitly declare self and end each function definition
with a semi-colon or comma, since this is a Lua table. To inherit from a base class,
set the special field _base to the class in this table.

Penlight provides a number of useful classes; there is List, which is a Lua
clone of the standard Python list object, and Set which represents sets. There
are three kinds of map defined: Map, MultiMap (where a key may have
multiple values) and OrderedMap (where the order of insertion is remembered.).
There is nothing special about these classes and you may inherit from them.

A powerful thing about dynamic languages is that you can redefine existing classes
and functions, which is often called 'monkey patching' It's entertaining and convenient,
but ultimately anti-social; you may modify List but then any other modules using
this shared resource can no longer be sure about its behaviour. (This is why you
must say stringx.import() explicitly if you want the extended string methods - it
would be a bad default.)  Lua is particularly open to modification but the
community is not as tolerant of monkey-patching as the Ruby community, say. You may
wish to add some new methods to List? Cool, but that's what subclassing is for.

class.Strings(List)

function Strings:my_method()
...
end

It's definitely more useful to define exactly how your objects behave
in unknown conditions. All classes have a catch method you can use to set
a handler for unknown lookups; the function you pass looks exactly like the
__index metamethod.

Strings:catch(function(self,name)
    return function() error("no such method "..name,2) end
end)

In this case we're just customizing the error message, but
creative things can be done. Consider this code from test-vector.lua:

Strings:catch(List.default_map_with(string))

ls = Strings{'one','two','three'}
asserteq(ls:upper(),{'ONE','TWO','THREE'})
asserteq(ls:sub(1,2),{'on','tw','th'})

So we've converted a unknown method invocation into a map using the function of
that name found in string.  So for a Vector (which is a specialization of List
for numbers) it makes sense to make math the default map so that v:sin() makes
sense.

Note that map operations return a object of the same type - this is often called
covariance. So ls:upper() itself returns a Strings object.

This is not always what you want, but objects can always be cast to the desired type.
(cast doesn't create a new object, but returns the object passed.)

local sizes = ls:map '#'
asserteq(sizes, {3,3,5})
asserteq(utils.type(sizes),'Strings')
asserteq(sizes:is_a(Strings),true)
sizes = Vector:cast(sizes)
asserteq(utils.type(sizes),'Vector')
asserteq(sizes+1,{4,4,6})

About utils.type: it can only return a string for a class type if that class does
in fact have a _name field.

Properties are a useful object-oriented pattern. We wish to control access to a
field, but don't wish to force the user of the class to say obj:get_field()
etc. This excerpt from tests/test-class.lua shows how it is done:

local MyProps = class(class.properties)
local setted_a, got_b

function MyProps:_init ()
    self._a = 1
    self._b = 2
end

function MyProps:set_a (v)
    setted_a = true
    self._a = v
end

function MyProps:get_b ()
    got_b = true
    return self._b
end

local mp = MyProps()

mp.a = 10

asserteq(mp.a,10)
asserteq(mp.b,2)
asserteq(setted_a and got_b, true)

The convention is that the internal field name is prefixed with an underscore;
when reading mp.a, first a check for an explicit getter get_a and then only
look for _a. Simularly, writing mp.a causes the setter set_a to be used.

This is cool behaviour, but like much Lua metaprogramming, it is not free. Method
lookup on such objects goes through \\index as before, but now \\index is a
function which has to explicitly look up methods in the class, before doing any
property indexing, which is not going to be as fast as field lookup. If however,
your accessors actually do non-trivial things, then the extra overhead could be
worth it.

This is not really intended for access control because external code can write
to mp._a directly. It is possible to have this kind of control in Lua, but it
again comes with run-time costs.

generated by LDoc 1.4.6


text:
from perfkitbenchmarker import flags
from perfkitbenchmarker import linux_packages
from perfkitbenchmarker import object_storage_service
from perfkitbenchmarker import providers
from perfkitbenchmarker import vm_util

FLAGS = flags.FLAGS

AWS_CREDENTIAL_LOCATION = '.aws'
DEFAULT_AWS_REGION = 'us-east-1'
# The endpoints in this table are subdomains of 'amazonaws.com'. So
# where the table says 's3-us-west-2', you should connect to
# 's3-us-west-2.amazonaws.com'. This table comes from
# http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
AWS_S3_REGION_TO_ENDPOINT_TABLE = {
    'us-east-1': 's3-external-1',
    'us-west-2': 's3-us-west-2',
    'us-west-1': 's3-us-west-1',
    'eu-west-1': 's3-eu-west-1',
    'eu-central-1': 's3-eu-central-1',
    'ap-southeast-1': 's3-ap-southeast-1',
    'ap-southeast-2': 's3-ap-southeast-2',
    'ap-northeast-1': 's3-ap-northeast-1',
    'ap-northeast-2': 's3-ap-northeast-2',
    'sa-east-1': 's3-sa-east-1'
}
AWS_S3_ENDPOINT_SUFFIX = '.amazonaws.com'

class S3Service(object_storage_service.ObjectStorageService):
  """Interface to Amazon S3."""

  STORAGE_NAME = providers.AWS

  def PrepareService(self, location):
    self.region = location or DEFAULT_AWS_REGION

  def MakeBucket(self, bucket_name):
    vm_util.IssueCommand(
        ['aws', 's3', 'mb',
         's3://%s' % bucket_name,
         '--region=%s' % self.region])

  def DeleteBucket(self, bucket):
    vm_util.IssueCommand(
        ['aws', 's3', 'rb',
         's3://%s' % bucket,
         '--region', self.region,
         '--force'])  # --force deletes even if bucket contains objects.

  def EmptyBucket(self, bucket):
    vm_util.IssueCommand(
        ['aws', 's3', 'rm',
         's3://%s' % bucket,
         '--region', self.region,
         '--recursive'])

  def PrepareVM(self, vm):
    vm.Install('awscli')
    vm.Install('boto')

    vm.PushFile(
        object_storage_service.FindCredentialFile('~/' +
                                                  AWS_CREDENTIAL_LOCATION),
        AWS_CREDENTIAL_LOCATION)
    vm.PushFile(object_storage_service.FindBotoFile(),
                object_storage_service.DEFAULT_BOTO_LOCATION)

  def CleanupVM(self, vm):
    vm.Uninstall('awscli')

  def CLIUploadDirectory(self, vm, directory, file_names, bucket):
    return vm.RemoteCommand(
        'time aws s3 sync %s s3://%s/' % (directory, bucket))

  def CLIDownloadBucket(self, vm, bucket, objects, dest):
    return vm.RemoteCommand(
        'time aws s3 sync s3://%s/ %s' % (bucket, dest))

  def Metadata(self, vm):
    return {object_storage_service.BOTO_LIB_VERSION:
            linux_packages.GetPipPackageVersion(vm, 'boto')}

  def APIScriptArgs(self):
    if FLAGS.s3_custom_endpoint:
      return ['--host=' + FLAGS.s3_custom_endpoint]
    else:
      hostname = AWS_S3_REGION_TO_ENDPOINT_TABLE[self.region]
      return ['--host=' + hostname + AWS_S3_ENDPOINT_SUFFIX]

  @classmethod
  def APIScriptFiles(cls):
    return ['boto_service.py', 's3.py']


text:
const assert = require('assert');
const { makePath } = require('../../lib/utils/uri');

describe('uri', () => {
  describe('makePath()', () => {
    it('should exist', () => {
      assert.equal(typeof makePath, 'function');
    });

    // @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-7.2.2
    const tests = [
      { name: '#', parts: ['http://x.y.z/rootschema.json#'], res: 'http://x.y.z/rootschema.json#' },
      { name: '#/schema1', parts: ['http://x.y.z/rootschema.json#', '#foo'], res: 'http://x.y.z/rootschema.json#foo' },
      { name: '#/schema2', parts: ['http://x.y.z/rootschema.json#', 'otherschema.json'], res: 'http://x.y.z/otherschema.json#' },
      { name: '#/schema2/nested', parts: ['http://x.y.z/rootschema.json#', 'otherschema.json', '#bar'], res: 'http://x.y.z/otherschema.json#bar' },
      { name: '#/schema2/alsonested', parts: ['http://x.y.z/rootschema.json#', 't/inner.json#a'], res: 'http://x.y.z/t/inner.json#a' },
      { name: '#/schema3', parts: ['http://x.y.z/rootschema.json#', 'some://where.else/completely#'], res: 'some://where.else/completely#' },
      {
        name: '#/custom1',
        parts: [
          'http://localhost:1234/object',
          'name.json#/definitions/orNull',
          'name.json#/definitions/orNull'
        ],
        res: 'http://localhost:1234/name.json#/definitions/orNull'
      }
    ];

    tests.forEach((test) => {
      it(`should make correct path for ${test.name}`, () => {
        assert.equal(makePath(test.parts), test.res);
      });
    });
  });
});


text:
(function() {
    'use strict';

    angular
        .module('app.core')
        .constant('toastr', toastr)
        .constant('moment', moment);
})();


text:
layout: page
title: Kontakt
permalink: kontakt/
---

{% if site.github_username %}

{% include icon-github.html username=site.github_username %}

{% endif %}
{% if site.twitter_username %}

{% include icon-twitter.html username=site.twitter_username %}

{% endif %}
{% if site.linkedin_username %}

{% include icon-linkedin.html username=site.linkedin_username %}

{% endif %}
{% if site.codepen_username %}

{% include icon-codepen.html username=site.codepen_username %}

{% endif %}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Robogirl Style: Leek Spin"</title>
		<link>http://bvs.wikidot.com/forum/t-47512/robogirl-style:leek-spin</link>
		<description>Posts in the discussion thread "Robogirl Style: Leek Spin"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:59:13 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-47512#post-144839</guid>
				<title>(no title)</title>
				<link>http://bvs.wikidot.com/forum/t-47512/robogirl-style:leek-spin#post-144839</link>
				<description></description>
				<pubDate>Mon, 14 Apr 2008 16:51:01 +0000</pubDate>
				<wikidot:authorName>Ren Po Ken</wikidot:authorName>				<wikidot:authorUserId>103468</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

A leek is a kind of stem onion (as opposed to a bulb onion).

By the time you get Robogirl, +4 Gen levels really isn't that amazing. There are usually better jutsu to use.

You can get Robogirl at Genin. When exactly is +4 Gen levels amazing? Ninja Academy Student? When you're prenatal? Additionally, this is 4 Gen Levels you can use on Reaper Missions.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-47512#post-126896</guid>
				<title>(no title)</title>
				<link>http://bvs.wikidot.com/forum/t-47512/robogirl-style:leek-spin#post-126896</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 03:55:14 +0000</pubDate>
				<wikidot:authorName>sutasafaia</wikidot:authorName>				<wikidot:authorUserId>90006</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

A leek is a plant

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-47512#post-126888</guid>
				<title>(no title)</title>
				<link>http://bvs.wikidot.com/forum/t-47512/robogirl-style:leek-spin#post-126888</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 03:25:00 +0000</pubDate>
				<wikidot:authorName>BvS-Uzuki</wikidot:authorName>				<wikidot:authorUserId>78144</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

What is a leek?

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-47512#post-126871</guid>
				<title>Leek spin</title>
				<link>http://bvs.wikidot.com/forum/t-47512/robogirl-style:leek-spin#post-126871</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 02:44:28 +0000</pubDate>
				<wikidot:authorName>Anonymous</wikidot:authorName>								<content:encoded>
					<![CDATA[

Oriheme is seen spinning a leek in the second episode of bleach (this is also the video used in leek spin)

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
{{-- 由LaravelMenu或自動生成 --}}

    <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>

        {{ config('app.name') }}
        {{-- 左側選單 --}}

            @include(config('laravel-menu.views.bootstrap-items'), array('items' => Menu::get('left')->roots()))

        {{-- 右側選單 --}}

            @include(config('laravel-menu.views.bootstrap-items'), array('items' => Menu::get('right')->roots()))


text:
require "values"

module Elrio
  Point = Value.new(:x, :y)

  Size = Value.new(:width, :height)

  Rect = Value.new(:x, :y, :width, :height)

  Pattern = Value.new(:start, :end, :size)

  class Insets < Value.new(:top, :left, :bottom, :right, :pattern_width, :pattern_height)
    def to_s
      [top, left, bottom, right].to_s
    end

    def *(factor)
      Insets.new(
        (factor * top).ceil,
        (factor * left).ceil,
        (factor * bottom).ceil,
        (factor * right).ceil,
        pattern_width,
        pattern_height
      )
    end

    def /(factor)
      self * (1.0 / factor)
    end

    def coerce(number)
      [self, number]
    end
  end
end


text:
import React, {useState} from 'react'
import {
   EuiButton,
   EuiFieldNumber,
   EuiFormRow,
   EuiModal,
   EuiModalBody,
   EuiModalFooter,
   EuiModalHeader,
   EuiModalHeaderTitle,
   EuiSpacer,
   EuiText,
} from "@elastic/eui";

export const RepartitionModal = ({onClose, submit, partitionCount}) => {

   const [count, setCount] = useState(partitionCount);

   function onConfirm() {
      submit(count);
   }

   return (
      <EuiModal onClose={onClose}>
         <EuiModalHeader>
            <EuiModalHeaderTitle>
Repartition Topic
</EuiModalHeaderTitle>
         </EuiModalHeader>

         <EuiModalBody>
            <EuiText>

It is recommended to set the partition count to at least the same as the number of brokers.

            </EuiText>
            <EuiSpacer/>
            <EuiFormRow label="Enter the new partition count for this topic">
               <EuiFieldNumber
                  value={count}
                  onChange={event => setCount(event.target.value)}
               />
            </EuiFormRow>
         </EuiModalBody>

         <EuiModalFooter>
            <EuiButton onClick={onClose} color="text">Close</EuiButton>
            <EuiButton onClick={onConfirm} fill>Confirm</EuiButton>
         </EuiModalFooter>
      </EuiModal>
   )
}


text:
<?php

namespace Scrutinizer\PhpAnalyzer\DataFlow\TypeInference\FunctionInterpreter;

use Scrutinizer\PhpAnalyzer\Model\GlobalFunction;

class ChainableFunctionInterpreter implements FunctionInterpreterInterface
{
    private $interpreters;

    /**
     * @param array<FunctionInterpreterInterface> $interpreters
     */
    public function __construct(array $interpreters)
    {
        $this->interpreters = $interpreters;
    }

    public function getPreciserFunctionReturnTypeKnowingArguments(GlobalFunction $function, array $argValues, array $argTypes)
    {
        foreach ($this->interpreters as $interpreter) {
            if (null !== $restrictedType = $interpreter->getPreciserFunctionReturnTypeKnowingArguments($function, $argValues, $argTypes)) {
                return $restrictedType;
            }
        }

        return null;
    }
}