text:
package org.sourcepit.b2.its;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.sourcepit.common.utils.file.FileUtils.deleteFileOrDirectory;
import static org.sourcepit.common.utils.io.IO.osgiIn;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.Scm;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsEqual;
import org.junit.Test;
import org.sourcepit.b2.its.util.GitSCM;
import org.sourcepit.b2.its.util.SCM;
import org.sourcepit.b2.its.util.SvnSCM;
import org.sourcepit.common.manifest.osgi.BundleManifest;
import org.sourcepit.common.manifest.osgi.resource.BundleManifestResourceImpl;
import org.sourcepit.common.manifest.resource.ManifestResource;
import org.sourcepit.common.utils.io.IOOperation;

public class ReleaseIT extends AbstractB2IT {
   @Override
   protected boolean isDebug() {
      return false;
   }

   @Test
   public void testSvn() throws Exception {
      final File rootModuleDir = getResource(getClass().getSimpleName());
      final File repoDir = workspace.newDir("repo");
      SCM scm = new SvnSCM(repoDir, rootModuleDir);
      test(rootModuleDir, scm, false);
   }

   @Test
   public void testGit() throws Exception {
      final File rootModuleDir = getResource(getClass().getSimpleName());
      final SCM scm = new GitSCM(rootModuleDir);
      test(rootModuleDir, scm, false);
   }

   @Test
   public void testQualifiedReleaseVersion() throws Exception {
      final File rootModuleDir = getResource(getClass().getSimpleName());
      final File repoDir = workspace.newDir("repo");
      SCM scm = new SvnSCM(repoDir, rootModuleDir);

      final String releaseVersion = "2.0.0-rc1";
      final String developmentVersion = "3.0.0-SNAPSHOT";
      test(rootModuleDir, scm, false, releaseVersion, developmentVersion);
   }

   @Test
   public void testTwoStepRelease() throws Exception {
      final File rootModuleDir = getResource(getClass().getSimpleName());
      final File repoDir = workspace.newDir("repo");
      SCM scm = new SvnSCM(repoDir, rootModuleDir);
      test(rootModuleDir, scm, true);
   }

   private void test(final File rootModuleDir, SCM scm, boolean isTwoStep) throws FileNotFoundException, IOException,
      XmlPullParserException {
      final String releaseVersion = "2.0.0";
      final String developmentVersion = "3.0.0-SNAPSHOT";
      test(rootModuleDir, scm, isTwoStep, releaseVersion, developmentVersion);
   }

   private void test(final File rootModuleDir, SCM scm, boolean isTwoStep, final String releaseVersion,
      final String developmentVersion) throws FileNotFoundException, IOException, XmlPullParserException {
      final File moduleADir = new File(rootModuleDir, "module-a");
      assertTrue(moduleADir.exists());
      final File moduleBDir = new File(rootModuleDir, "module-b");
      assertTrue(moduleBDir.exists());

      final List<File> moduleXmls = new ArrayList<File>();
      collectModuleXmls(moduleXmls, rootModuleDir);
      assertThat(moduleXmls.size(), Is.is(3));

      setScm(scm, moduleXmls);

      scm.create();

      execRelease(rootModuleDir, releaseVersion, developmentVersion, isTwoStep);

      scm.switchVersion(releaseVersion);

      assertMavenModel(scm, rootModuleDir, releaseVersion);
      assertMavenModel(scm, moduleADir, releaseVersion);
      assertMavenModel(scm, moduleBDir, releaseVersion);

      BundleManifest bundleManifest = readBundleManifest(new File(moduleBDir, "bundle.b"));
      assertThat(bundleManifest.getBundleVersion().toString(), IsEqual.equalTo(releaseVersion.replace('-', '.')));

      scm.switchVersion(null);

      assertMavenModel(scm, rootModuleDir, developmentVersion);
      assertMavenModel(scm, moduleADir, developmentVersion);
      assertMavenModel(scm, moduleBDir, developmentVersion);

      bundleManifest = readBundleManifest(new File(moduleBDir, "bundle.b"));
      assertThat(bundleManifest.getBundleVersion().toString(),
         IsEqual.equalTo(developmentVersion.replaceAll("-SNAPSHOT", ".qualifier")));
   }

   private void execRelease(final File rootModuleDir, final String releaseVersion, final String developmentVersion,
      boolean isTwoStep) throws IOException {
      if (isTwoStep) {
         File b2Dir = environment.getMavenHome();

         File mavenDir = new File(environment.getBuildDir(), "maven-without-b2");
         FileUtils.copyDirectory(b2Dir, mavenDir);
         deleteFileOrDirectory(new File(mavenDir, "lib/ext"));

         List<String> args = new ArrayList<String>();
         args.add("-e");
         args.add("-B");
         args.add("clean");
         args.add("-Dtycho.mode=maven");

         build(b2Dir, rootModuleDir, args.toArray(new String[args.size()]));

         args = new ArrayList<String>();
         args.add("-e");
         args.add("-B");
         args.add("release:prepare");
         args.add("release:perform");
         args.add("-Dtycho.mode=maven");
         args.add("-DreleaseVersion=" + releaseVersion);
         args.add("-DdevelopmentVersion=" + developmentVersion);
         args.add("-Dresume=false");
         args.add("-DignoreSnapshots=true");

         build(mavenDir, rootModuleDir, args.toArray(new String[args.size()]));
      }
      else {
         final List<String> args = new ArrayList<String>();
         args.add("-e");
         args.add("-B");
         args.add("clean");
         args.add("release:prepare");
         args.add("release:perform");
         args.add("-Dtycho.mode=maven");
         args.add("-DreleaseVersion=" + releaseVersion);
         args.add("-DdevelopmentVersion=" + developmentVersion);
         args.add("-Dresume=false");
         args.add("-DignoreSnapshots=true");

         build(rootModuleDir, args.toArray(new String[args.size()]));
      }
   }

   private static BundleManifest readBundleManifest(final File projectDir) {
      final ManifestResource resource = new BundleManifestResourceImpl();
      final IOOperation<InputStream> ioop = new IOOperation<InputStream>(osgiIn(projectDir, "META-INF/MANIFEST.MF")) {
         @Override
         protected void run(InputStream openResource) throws IOException {
            resource.load(openResource, null);
         }
      };
      try {
         ioop.run();
         return (BundleManifest) resource.getContents().get(0);
      }
      finally {
         resource.getContents().clear();
      }
   }

   private static void assertMavenModel(SCM scm, File moduleDir, final String releaseVersion)
      throws FileNotFoundException, IOException, XmlPullParserException {
      Model model = readMavenModel(new File(moduleDir, "module.xml"));
      assertThat(model.getVersion(), IsEqual.equalTo(releaseVersion));
      Scm scmConnection = scm.createMavenScmModel(moduleDir, releaseVersion);
      assertScmEqual(model.getScm(), scmConnection);
   }

   private static void assertScmEqual(Scm actual, Scm expected) {
      if (actual == null) {
         assertNull(expected);
         return;
      }
      if (expected == null) {
         assertNull(actual);
         return;
      }
      assertThat(actual.getConnection(), IsEqual.equalTo(expected.getConnection()));
      assertThat(actual.getDeveloperConnection(), IsEqual.equalTo(expected.getDeveloperConnection()));
      assertThat(actual.getTag(), IsEqual.equalTo(expected.getTag()));
      assertThat(actual.getUrl(), IsEqual.equalTo(expected.getUrl()));
   }

   public static void setScm(SCM scm, final List<File> moduleXmls) throws FileNotFoundException, IOException,
      XmlPullParserException {
      for (File moduleXml : moduleXmls) {
         final File projectDir = moduleXml.getParentFile();
         final Scm scmModel = scm.createMavenScmModel(projectDir, null);
         if (scmModel != null) {
            final Model moduleModel = readMavenModel(moduleXml);
            moduleModel.setScm(scmModel);
            writeMavenModel(moduleXml, moduleModel);
         }
      }
   }

   private static void collectModuleXmls(List<File> moduleXmls, File projectDir) {
      moduleXmls.add(new File(projectDir, "module.xml"));

      for (File file : projectDir.listFiles()) {
         if (file.isDirectory() && new File(file, "module.xml").exists()) {
            moduleXmls.add(new File(file, "module.xml"));
         }
      }
   }

}

redpajama_set_name: RedPajamaGithub


text:
require "date"

class Reservation < ApplicationRecord

  acts_as_paranoid # soft deletes
  has_paper_trail

  include DateHelper
  include Reservations::DateSupport
  include Reservations::Validations
  include Reservations::Rendering
  include Reservations::RelaySupport
  include Reservations::MovingUp

  # Associations
  #####
  belongs_to :product
  belongs_to :instrument, foreign_key: :product_id
  belongs_to :order_detail, inverse_of: :reservation
  belongs_to :created_by, class_name: "User"
  has_one :order, through: :order_detail

  ## Virtual attributes
  #####

  # Represents a resevation time that is unavailable, but is not an admin reservation
  # Used by timeline view
  attr_accessor :blackout

  # used for overriding certain restrictions
  attr_accessor :reserved_by_admin

  # Used when we want to force the order to complete even if it doesn't meet the
  # requirements of order_completeable?, e.g. the reservation time isn't over yet.
  attr_accessor :force_completion

  # Delegations
  #####
  delegate :note, :note=, :ordered_on_behalf_of?, :complete?, :account, :order,
           :complete!, :price_policy, :reference_id, :reference_id=, to: :order_detail, allow_nil: true

  delegate :account, :in_cart?, :user, to: :order, allow_nil: true
  delegate :facility, to: :product, allow_nil: true
  delegate :lock_window, to: :product, prefix: true
  delegate :owner, to: :account, allow_nil: true

  def canceled?
    return false unless order_detail
    order_detail.canceled_at?
  end

  ## AR Hooks
  before_save :set_billable_minutes
  after_update :auto_save_order_detail, if: :order_detail

  # Scopes
  #####

  scope :admin_and_offline, -> { where(type: %w(AdminReservation OfflineReservation)) }
  scope :purchased, -> { joins(order_detail: :order).merge(Order.purchased) }

  def self.active
    not_canceled
      .user
      .where(orders: { state: ["purchased", nil] })
      .joins_order
  end

  scope :ends_in_the_future, lambda {
    where(reserve_end_at: nil).or(where("reserve_end_at > ?", Time.current))
  }

  def self.joins_order
    joins("LEFT JOIN order_details ON order_details.id = reservations.order_detail_id")
      .joins("LEFT JOIN orders ON orders.id = order_details.order_id")
  end

  scope :not_canceled, -> { where(order_details: { canceled_at: nil }) } # dubious
  scope :not_started, -> { where(actual_start_at: nil) }
  scope :not_ended, -> { where(actual_end_at: nil) }

  def self.not_this_reservation(reservation)
    if reservation.id
      where("reservations.id <> ?", reservation.id)
    else
      all
    end
  end

  scope :ongoing, -> { not_ended.where("actual_start_at <= ?", Time.current) }

  scope :current_in_use, lambda {
    not_canceled
      .joins_order
      .ends_in_the_future
      .not_ended
      .where("reserve_start_at <= ? OR actual_start_at IS NOT NULL", Time.current)
      .where(orders: { state: [nil, :purchased] })
  }

  def self.today
    for_date(Time.current)
  end

  def self.for_date(date)
    in_range(date.beginning_of_day, date.end_of_day)
  end

  def self.in_range(start_time, end_time)
    where("reserve_end_at >= ?", start_time)
      .where("reserve_start_at < ?", end_time)
  end

  def self.upcoming(t = Time.current)
    # If this is a named scope differences emerge between Oracle & MySQL on #reserve_end_at querying.
    # Eliminate by letting Rails filter by #reserve_end_at
    joins("LEFT JOIN order_details ON order_details.id = reservations.order_detail_id")
      .joins("LEFT JOIN orders ON orders.id = order_details.order_id")
      .not_canceled
      .where("orders.state" => [nil, "purchased"])
      .order(reserve_end_at: :asc)
      .to_a
      .delete_if { |reservation| reservation.reserve_end_at < t }
  end

  def self.overlapping(start_at, end_at)
    # remove millisecond precision from time
    tstart_at = Time.zone.parse(start_at.to_s)
    tend_at   = Time.zone.parse(end_at.to_s)

    where("((reserve_start_at <= :start AND reserve_end_at >= :end) OR
          (reserve_start_at >= :start AND reserve_end_at <= :end) OR
          (reserve_start_at <= :start AND reserve_end_at > :start) OR
          (reserve_start_at < :end AND reserve_end_at >= :end) OR
          (reserve_start_at = :start AND reserve_end_at = :end))",
          start: tstart_at, end: tend_at)
  end

  def self.relay_in_progress
    where("actual_start_at IS NOT NULL AND actual_end_at IS NULL")
  end

  def self.upcoming_offline(start_at_limit)
    user
      .where(product_id: OfflineReservation.current.pluck(:product_id))
      .not_canceled
      .not_ended
      .merge(OrderDetail.purchased)
      .joins(:order_detail)
      .where(order_details: { state: %w(new inprocess), problem: false })
      .where("reserve_start_at <= ?", start_at_limit)
  end

  scope :user, -> { where(type: nil) }

  def self.for_timeline(date, instrument_ids)
    admin_and_offline_reservations = admin_and_offline.for_date(date).where(product_id: instrument_ids)
    purchased_reservations = purchased.for_date(date).where(product_id: instrument_ids)
    (admin_and_offline_reservations + purchased_reservations).sort_by(&:reserve_start_at)
  end

  # Instance Methods
  #####

  def end_at_required?
    true
  end

  # Is there enough information to move an associated order to complete/problem?
  def order_completable?
    force_completion || actual_end_at || reserve_end_at < Time.current
  end

  def force_dirty!
    # The actual attribute doesn't matter, we just need to make sure this object
    # is marked as ActiveModel::Dirty when this method is called.
    actual_start_at_will_change!
  end

  def start_reservation!
    # If there are any reservations running over their time on the shared schedule,
    # kick them over to the problem queue.
    product.schedule.products.flat_map(&:started_reservations).each do |reservation|
      # If we're in the grace period for this reservation, but the other reservation
      # has not finished its reserved time, this will fail and this reservation will
      # not start.
      MoveToProblemQueue.move!(reservation.order_detail, user: reservation.user, cause: :reservation_started)
    end
    update!(actual_start_at: Time.current)
  end

  def end_reservation!
    update!(actual_end_at: Time.current)
    order_detail.complete!
  end

  def round_reservation_times
    interval = product.reserve_interval.minutes # Round to the nearest reservation interval
    self.reserve_start_at = time_ceil(reserve_start_at, interval) if reserve_start_at
    self.reserve_end_at   = time_ceil(reserve_end_at, interval) if reserve_end_at
    self
  end

  def assign_actuals_off_reserve
    self.actual_start_at ||= reserve_start_at
    self.actual_end_at   ||= reserve_end_at
  end

  def valid_as_user?(user)
    if user.operator_of?(product.facility)
      self.reserved_by_admin = true
      valid?
    else
      self.reserved_by_admin = false
      valid?(context: :user_purchase)
    end
  end

  def save_as_user(user)
    if user.operator_of?(product.facility)
      self.reserved_by_admin = true
      save
    else
      self.reserved_by_admin = false
      save(context: :user_purchase)
    end
  end

  def save_as_user!(user)
    raise ActiveRecord::RecordInvalid.new(self) unless save_as_user(user)
  end

  def display_user
    user
  end

  def kiosk?
    admin? || can_switch_instrument?
  end

  def offline?
    type == "OfflineReservation"
  end

  def admin?
    order.nil? && !blackout?
  end

  def admin_removable?
    true
  end

  def blackout?
    blackout.present?
  end

  def can_start_early?
    return false unless in_grace_period?
    # no other reservation ongoing; no res between now and reserve_start;

    Reservation
      .not_started
      .where("reserve_start_at > :now", now: Time.current)
      .where("reserve_start_at < :reserve_start_at", reserve_start_at: reserve_start_at)
      .where(product_id: product_id)
      .joins(:order_detail)
      .where("order_detail_id IS NULL OR order_details.state IN ('new', 'inprocess')")
      .none?
  end

  # can the CUSTOMER cancel the order
  def can_cancel?
    !canceled? && reserve_start_at > Time.current && actual_start_at.nil? && actual_end_at.nil?
  end

  def can_customer_edit?
    !canceled? && !complete? && (reserve_start_at_editable? || reserve_end_at_editable?)
  end

  def reserve_start_at_editable?
    before_lock_window? && !started?
  end

  def reserve_end_at_editable?
    Time.current <= reserve_end_at && extendable? && actual_end_at.blank?
  end

  def extendable?
    next_available = product.next_available_reservation(after: reserve_end_at, options: { ignore_cutoff: true })

    return false unless next_available

    current_end_at = reserve_end_at.change(sec: 0)
    next_start_at = next_available.reserve_start_at.change(sec: 0)

    current_end_at == next_start_at
  end

  def before_lock_window?
    Time.current < reserve_start_at - product_lock_window.hours
  end

  def inside_lock_window?
    !before_lock_window?
  end

  def admin_editable?
    new_record? || !canceled?
  end

  # TODO: does this need to be more robust?
  def can_edit_actuals?
    return false if order_detail.nil?
    complete?
  end

  def reservation_changed?
    reserve_start_at_changed? || reserve_end_at_changed?
  end

  def valid_before_purchase?
    satisfies_minimum_length? &&
      satisfies_maximum_length? &&
      allowed_in_schedule_rules? &&
      does_not_conflict_with_other_user_reservation? &&
      (reserved_by_admin || does_not_conflict_with_admin_reservation?)
  end

  def has_actuals?
    actual_start_at.present? && actual_end_at.present? && actual_end_at > actual_start_at
  end

  def started?
    actual_start_at.present?
  end

  def ongoing?
    !complete? && started? && actual_end_at.blank?
  end

  def requires_but_missing_actuals?
    !!(!canceled? && product.control_mechanism != Relay::CONTROL_MECHANISMS[:manual] && !has_actuals?) # TODO: refactor?
  end

  def problem_description_key
    :missing_actuals if requires_but_missing_actuals?
  end

  def locked?
    !(admin_editable? || can_edit_actuals?)
  end

  # Used in instrument utilization reports
  def quantity
    1
  end

  def update_billable_minutes
    update_column(:billable_minutes, calculated_billable_minutes)
  end

  private

  def auto_save_order_detail
    if (%w(actual_start_at actual_end_at reserve_start_at reserve_end_at) & saved_changes.keys).any?
      order_detail.save
    end
  end

  def in_grace_period?(at = Time.current)
    at = at.to_i
    grace_period_end = reserve_start_at.to_i
    grace_period_begin = (reserve_start_at - grace_period_duration).to_i

    # Compare int values, not timestamps. If you do the
    # latter fractions of a second can cause false positives.
    at >= grace_period_begin && at <= grace_period_end
  end

  def grace_period_duration
    SettingsHelper.setting("reservations.grace_period") || 5.minutes
  end

  def set_billable_minutes
    self.billable_minutes = calculated_billable_minutes
  end

  def calculated_billable_minutes
    if order_detail&.complete? && order_detail&.canceled_at.blank? && price_policy.present?
      case price_policy.charge_for
      when InstrumentPricePolicy::CHARGE_FOR.fetch(:reservation)
        TimeRange.new(reserve_start_at, reserve_end_at).duration_mins
      when InstrumentPricePolicy::CHARGE_FOR.fetch(:usage)
        TimeRange.new(actual_start_at, actual_end_at).duration_mins
      when InstrumentPricePolicy::CHARGE_FOR.fetch(:overage)
        end_time = [reserve_end_at, actual_end_at].max
        TimeRange.new(reserve_start_at, end_time).duration_mins
      end
    end
  end

end


text:
#ifndef GUARD_filtered_entry_list_ctrl_hpp_790944654397175
#define GUARD_filtered_entry_list_ctrl_hpp_790944654397175

#include "account.hpp"
#include "entry_list_ctrl.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <sqloxx/handle.hpp>
#include <sqloxx/sql_statement_fwd.hpp>
#include <wx/window.h>
#include <memory>

namespace dcm
{

// begin forward declarations

class Entry;

// end forward declarations

namespace gui
{

/**
 * An EntryListCtrl which is filtered by Account and may also be
 * filtered by date.
 *
 * Shows only \e actual (non-budget) and ordinary (non-draft) Entries.
 */
class FilteredEntryListCtrl: public EntryListCtrl
{
public:
    FilteredEntryListCtrl
    (   wxWindow* p_parent,
        wxSize const& p_size,
        sqloxx::Handle<Account> const& p_account,
        boost::optional<boost::gregorian::date> const& p_maybe_min_date,
        boost::optional<boost::gregorian::date> const& p_maybe_max_date
    );

    FilteredEntryListCtrl(FilteredEntryListCtrl const&) = delete;
    FilteredEntryListCtrl(FilteredEntryListCtrl&&) = delete;
    FilteredEntryListCtrl& operator=(FilteredEntryListCtrl const&) = delete;
    FilteredEntryListCtrl& operator=(FilteredEntryListCtrl&&) = delete;
    virtual ~FilteredEntryListCtrl();

protected:
    sqloxx::Handle<Account> const& account() const;
    boost::gregorian::date min_date() const;

private:

    virtual bool do_require_progress_log() const override;

    virtual void do_insert_non_date_columns() = 0;

    virtual bool do_approve_entry
    (   sqloxx::Handle<Entry> const& p_entry
    ) const override;

    virtual void do_set_column_widths() override;

    virtual int do_get_num_columns() const = 0;

    virtual int do_get_comment_col_num() const = 0;

    virtual std::unique_ptr<sqloxx::SQLStatement>
        do_create_entry_selector() override;

    sqloxx::Handle<Account> const m_account;
    boost::gregorian::date m_min_date;
    boost::optional<boost::gregorian::date> const m_maybe_max_date;

};  // class FilteredEntryListCtrl

}  // namespace gui
}  // namespace dcm

#endif  // GUARD_filtered_entry_list_ctrl_hpp_790944654397175


text:
namespace AjTalk.Exceptions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class ErrorException : Exception
    {
        public ErrorException(string message)
            : base(message)
        {
        }
    }
}


text:
**Cropper** is a jQuery widget to add cropping by zoom and pan to any application. The cropping area is set by dragging the image 'under' the widget, and zooming with a slider. **Cropper** should work in any modern browser.

You can see **Cropper** in action [here](http://www.sjaakpriester.nl/software/cropper).

Here is **Cropper**'s  [GitHub page](https://github.com/sjaakp/cropper).

## Install ##

Install **Cropper** with [Bower](http://bower.io/):

	bower install sjaakp-cropper

You can also manually install **Cropper** by [downloading the source in ZIP-format](https://github.com/sjaakp/cropper/archive/master.zip).

## Dependencies ##

**Cropper** depends on jQuery and jQuery.ui.
It is tested with jQuery 2.1.1, and jQuery.ui 1.10.4.

Of the jQuery.ui library, only the slider widget is used. Therefore, only the following modules are required:

- slider
- core
- widget
- position
- mouse

## Usage ##

#### Load resources ####

In the `header` part of the HTML-page, link to the style sheets (`.css`) of jQuery.ui and of **Cropper**, like:

    <link href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet">
    <link href="css/jquery.cropper.min.css" rel="stylesheet">

At the end of the `body` part, load the jQuery and jQuery.ui libraries:

    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>

And load the **Cropper** code:

    <script src="js/jquery.cropper.js"></script>

#### Load from CDN ####

You may also load the **Cropper** files from a content distribution network (CDN), like so:

    <link href="https://unpkg.com/@sjaakp/cropper/css/jquery.cropper.min.css" rel="stylesheet">

And:

    <script src="https://unpkg.com/@sjaakp/cropper/js/jquery.cropper.min.js"></script>

#### Set-up ####

**Cropper** is loaded like most other jQuery.ui widgets. The code might look something like:

    <script>
        $(document).ready(function () {
            $("#cropper").cropper({
                ... cropper options ...
            });
        });
    </script>

One ore more (or zero) options may be set, like:

    <script>
        $(document).ready(function () {
            $("#cropper").cropper({
                aspectRatio: .75,
                sliderPosition: "left"
            });
        });
    </script>

## Loading an image ##

After set-up, an image can be loaded in **Cropper** as follows:

    $("#cropper").cropper({"loadImage", src});

Where `src` can be anything that can be `src` of an HTML `img`. So, to load a picture of Newton, the code might be:

    $("#cropper").cropper({"loadImage", "img/Newton.jpg"});

`src` can be an image url, but also a Web `File` or a `FileList`, like those from a HTML file input. Take a look at the source code of `demo.html` for an example.

If `src` is `false` **Cropper** will be emptied.

## Options ##

Options can be set at set-up time (see above) or at run time. The technique is the same as with most other jQuery.ui widgets. So, to set `aspectRatio` to 1.33 after **Cropper** has been initialized, use something like:

    $("#cropper").cropper({"option", "aspectRatio", 1.33});

To read an option:

    var asp = $("#cropper").cropper({"option", "aspectRatio"});

The options have immediate effect after they have been set, so changes are in real time.

#### aspectRatio ####

A float describing the dimensions of the cropped area, i.e. width / height. A square cropped area will have `aspectRatio: 1`, while a portrait layout may have `aspectRatio: .75`, and a landscape layout `aspectRatio: 1.5`. Default is 1.

#### margin ####

The width of **Cropper**'s area margin, in pixels. Default is 40.

#### diagonal ####

The diagonal of the cropping area, in pixels. If `aspectRatio` changes, both width and height of the cropping area change, but the diagonal is constant. Default: 300.

#### minSize ####

The minimal size of the cropped area in pixels. The size is the length of the greatest side, so for a portrait layout it will be the height. If an image is too small, it will not be cropped. `minSize` also determines the maximum zoom factor of the image. Default: 240.

#### sliderPosition ####

Position of the slider with respect to the preview area. Possible values: `"top"`, `"bottom"`, `"left"`, `"right"`. Default is `"bottom"`.

#### change ####

The handler of the `change` event. See below.

## Events ##

#### change ####

Whenever something changes, **Cropper** fires the `change` event. This can be used to update other elements on the page, f.i. hidden inputs.

The event handler has to be a  function or a closure with the signature `function(evt, data)`, where `evt` is the usual Javascript event object. `data` is an object containing the following **Cropper** information:

    {
        aspect: ...		// the current aspect ratio
		x: ...			// left position of the crop area
		y: ...			// top position of the crop area
		w: ...			// width of the crop area
		y: ...			// height of the crop area
    }

The crop dimensions are all in pixels. All the members of `data` are floats (with an almost ridiculous precision), including the pixel values. Keep that in mind when processing them.

`demo.html` contains an example how the `change` event may be utilised. In this case, the handler function is set as the `change` option at set-up time.

## Acknowledgements ##

I drew inspiration from [Rabona's Image Crop](https://codecanyon.net/item/image-crop/5348464) for the look and feel.  However, **Cropper** was coded from scratch.


text:
//<applet code=QT width=500 height=750>
/**
 * Java Applet
 * An Applet that communicate with a server to
 * cluster informations by database tables
 *
 * @author Colaci Simone
 * @version 1.00, 30 Jun 2015
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketException;

import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class QT extends JApplet{
	/**
	 * Main Applet class
	 *
	 * @param serialVersionUID Default constant
	 * @param out ObjectOutputStream variable to stream out informations to the server
	 * @param in ObjectInputStream variable to receive informations from the server
	 */
	private static final long serialVersionUID = 1L;
	ObjectOutputStream out;
	ObjectInputStream in;

	private class TabbedPane extends JPanel{
		/**
		 * Main panel class
		 *
		 * @param serialVersionUID default constant
		 * @param panelDB Panel to load file from DB
		 * @param panelFile Panel to load file from file
		 */
		private static final long serialVersionUID = 1L;
		private JPanelCluster panelDB;
		private JPanelCluster panelFile;
		private class JPanelCluster extends JPanel{
			/**
			 * TabbedPane skeleton
			 *
			 * @param serialVersionUID default constant
			 * @param tableText JTextField to set the table DB name
			 * @param parameterText JTextField to set the radius value
			 * @param distanceText JTextField to set which distance to calculate
			 * @param clusterOutput JTextField to print output
			 * @param executeButton JButton to send the informations to the Applet
			 */
			private static final long serialVersionUID = 1L;
			private JTextField tableText;
			private JTextField parameterText;
			private JTextField distanceText;
			private JTextArea clusterOutput;
			private JButton executeButton;
			/**
			 * Class constructor
			 *
			 * @param buttonName String to decide which panel stream (panelDB of panelFile)
			 * @param a java.awt.event.ActionListener for executeButton
			 */
			JPanelCluster(String buttonName, java.awt.event.ActionListener a){
				if(buttonName.equals("MINE")){
					tableText=new JTextField(20);
					parameterText=new JTextField(10);
					distanceText=new JTextField(10);
					clusterOutput=new JTextArea(20, 55);

					JPanel up = new JPanel();
					up.setLayout(new FlowLayout());
					up.add(new JLabel("Table:"));
					up.add(tableText);
					up.add(new JLabel("Parameter:"));
					up.add(parameterText);
					up.add(new JLabel("Distance:"));
					up.add(distanceText);
					add(up);

					JPanel center = new JPanel();
					center.setLayout(new FlowLayout());
					clusterOutput.setEditable(false);
					clusterOutput.setLineWrap (true);
					center.add(clusterOutput);
					JScrollPane scrollPane = new JScrollPane(clusterOutput);
					add(scrollPane);
					add(center);
					JPanel down = new JPanel();
					down.setLayout(new FlowLayout());
					executeButton = new JButton("WRITE ON FILE");
					executeButton.addActionListener(a);
					down.add(executeButton);
					add(down, BorderLayout.SOUTH);

				}else if(buttonName.equals("STORE FROM FILE")){
					tableText=new JTextField(20);
					parameterText=new JTextField(10);
					distanceText=new JTextField(10);
					clusterOutput=new JTextArea(20, 55);

					JPanel up = new JPanel();
					up.setLayout(new FlowLayout());
					up.add(new JLabel("Table:"));
					up.add(tableText);
					up.add(new JLabel("Parameter:"));
					up.add(parameterText);
					up.add(new JLabel("Distance:"));
					up.add(distanceText);
					add(up);

					JPanel center = new JPanel();
					center.setLayout(new FlowLayout());
					clusterOutput.setEditable(false);
					clusterOutput.setLineWrap (true);
					center.add(clusterOutput);
					JScrollPane scrollPane = new JScrollPane(clusterOutput);
					add(scrollPane);
					add(center);

					JPanel down = new JPanel();
					down.setLayout(new FlowLayout());
					executeButton = new JButton("WRITE ON FILE");
					executeButton.addActionListener(a);
					down.add(executeButton);
					add(down, BorderLayout.SOUTH);
				}
			}
		}
		/**
		 * Class costructor
		 */
		TabbedPane() {
			super(new GridLayout(1, 1));
			JTabbedPane tabbedPane = new JTabbedPane();

			java.net.URL imgURL = getClass().getResource("img/db.jpg");
			try {
				imgURL = new java.net.URL("img/db.jpg");
			} catch (MalformedURLException e2) {
				e2.printStackTrace();
			}
			ImageIcon iconDB = new ImageIcon(imgURL);
			panelDB = new JPanelCluster("MINE", new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						clusteringFromDBAction();
					} catch (SocketException e1) {
						System.out.println(e1);

					} catch (FileNotFoundException e1) {
						System.out.println(e1);

					} catch (IOException e1) {
						System.out.println(e1);

					} catch (ClassNotFoundException e1) {
						System.out.println(e1);
					}
				}
			});
	        tabbedPane.addTab("DB", iconDB, panelDB, "Does nothing");

	        imgURL = getClass().getResource("img/file.jpg");
	        try {
				imgURL = new java.net.URL("img/file.jpg");
			} catch (MalformedURLException e2) {
				e2.printStackTrace();
			}
	        ImageIcon iconFile = new ImageIcon(imgURL);
	        panelFile = new JPanelCluster("STORE FROM FILE",new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						clusteringFromFileAction();
					} catch (SocketException e1) {
						System.out.println(e1);

					} catch (FileNotFoundException e1) {
						System.out.println(e1);

					} catch (IOException e1) {
						System.out.println(e1);

					} catch (ClassNotFoundException e1) {
						System.out.println(e1);
					}
				}
	        });
	        tabbedPane.addTab("FILE", iconFile, panelFile, "Does nothing");
	        add(tabbedPane);
	        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		}
		/**
		 * Method that take information from a table located in a DB, a radius,
		 * and a type of distance to calculate and send these informations
		 * to a server that respond with number of clusters and the result of
		 * the clustering process
		 */
		private void clusteringFromDBAction()throws SocketException,IOException,ClassNotFoundException{
			String tableName;
			try{
				tableName=new String(panelDB.tableText.getText());
				if (!tableName.toLowerCase().equals("playtennis"))
					throw new Exception("Invalid table name");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}			double radius;
			try{
				radius=new Double(panelDB.parameterText.getText()).doubleValue();
				if (radius<=0)
					throw new NumberFormatException("Radius<=0");
			} catch(NumberFormatException e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			String distance;
			boolean rightDist=false;
			try{
				distance=new String(panelDB.distanceText.getText());
				if (distance.toLowerCase().equals("edit")||distance.toLowerCase().equals("euclidea"))
					rightDist = true;

				if(!rightDist)
					throw new Exception("Invalid distance");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			out.writeObject(1);
			out.writeObject(tableName);
			String result;
			try{
				result = (String)in.readObject();
				if(!result.equals("OK"))
					throw new Exception("Name table request failed");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			out.writeObject(radius);
			out.writeObject(distance);
			try{
				result = (String)in.readObject();
				if(!result.equals("OK"))
					throw new Exception("Radius request failed");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			int numCluster = (int)in.readObject();
			String data = (String)in.readObject();
			panelDB.clusterOutput.append("Number of clusters:"+numCluster+"\n"+data);
			panelDB.clusterOutput.append("============================================\n");
			try{
				result = (String)in.readObject();
				if(!result.equals("OK"))
					throw new Exception("store cluster in file request failed");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			JOptionPane.showMessageDialog(this, "Success");
		}
		/**
		 * Method that take information from a file, a radius,
		 * and a type of distance to calculate and send these informations
		 * to a server that respond with the result of the clustering process
		 */
		private void clusteringFromFileAction() throws SocketException,IOException,ClassNotFoundException{
			String tableName;
			try{
				tableName=new String(panelFile.tableText.getText());
				if (!tableName.toLowerCase().equals("playtennis"))
					throw new Exception("Invalid table name");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			double radius;
			try{
				radius=new Double(panelFile.parameterText.getText()).doubleValue();
				if (radius<=0)
					throw new NumberFormatException("Radius<=0");
			} catch(NumberFormatException e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			String distance;
			boolean rightDist=false;
			try{
				distance=new String(panelFile.distanceText.getText());
				if (distance.toLowerCase().equals("edit")||distance.toLowerCase().equals("euclidea"))
					rightDist = true;

				if(!rightDist)
					throw new Exception("Invalid distance");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}

			out.writeObject(2);

			out.writeObject(tableName);
			out.writeObject(radius);
			out.writeObject(distance);
			try{
				String result = (String)in.readObject();
				if(!result.equals("OK"))
					throw new Exception("clustering from file request failed");
			} catch(Exception e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			String data = "";
			try{
				data = (String)in.readObject();
			}catch(NullPointerException e){
				JOptionPane.showMessageDialog(this,e.toString());
				return;
			}
			panelFile.clusterOutput.append(data);
			panelFile.clusterOutput.append("============================================\n");
			JOptionPane.showMessageDialog(this, "Success");
		}
	}
	/**
	 * Default method to start the Applet
	 */
	public void init(){
		TabbedPane tab=new TabbedPane();
		getContentPane().setLayout(new GridLayout(1,1));
		getContentPane().add(tab);
		String ip="localhost";
		int port=8080;
		//String ip=this.getParameter("ServerIP");
		//int port=new Integer(this.getParameter("Port")).intValue();
		try {
			InetAddress addr = InetAddress.getByName(ip); //ip
			System.out.println("addr = " + addr);
			Socket socket = new Socket(addr, port); //Port
			System.out.println(socket);

			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
		}catch(IOException e){
			System.exit(0);
		}

	}
}


text:
layout: default-bg
title: Terms & Conditions
active: none
---

Terms & Conditions

        Welcome to my Portfolio

        These terms and conditions outline the rules and regulations for the use of this Website,
        located at {{ site.weburl }}.

        By accessing this website i assume you accept these terms and conditions.
        Do not continue to use the website if you do not agree to take all of the terms and conditions stated on this page.

        The following terminology applies to these Terms and Conditions,
        Privacy Statement and Disclaimer Notice and all Agreements: "Client", "You" and "Your" refers to you, the person log on this website
        and compliant to the terms and conditions. "I", "Me", "Myself" refers to me the owner of this site. "This Website" refers to this website itself.
        "Ourselves", "We", "Our", "Party", "Parties", or "Us", refers to both you and me.
        All terms refer to the offer, acceptance and consideration of payment necessary to undertake the process of my assistance
        to the Client in the most appropriate manner for the express purpose of meeting the Client's needs in respect of provision of the stated services,
        in accordance with and subject to, prevailing law.
        Any use of the above terminology or other words in the singular, plural, capitalization and/or he/she or they, are taken as interchangeable and therefore as referring to same.

        If you have additional questions or require more information about the Terms & Conditions, do not hesitate to contact me through email at {{ site.email }}

    Cookies

        I do not employ the use of cookies. But, Third Party services used on this website may use cookies.
        By accessing this website, you agreed to use cookies in agreement with the website Privacy Policy.

    License

        Unless otherwise stated, me and/or its licensors own the intellectual property rights for all material on this website.
        All intellectual property rights are reserved.
        You may access this website for your own personal use subjected to restrictions set in these terms and conditions.

            You must not:

Republish material from this website

Sell, rent or sub-license material from

Reproduce, duplicate or copy material from

Redistribute content from

            You can:

Reuse this website as a template as its licensed under Apache License, Version 2.0 by agreeing its terms and conditions.

Use the images that are licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License by agreeing its terms and conditions.

        This Agreement shall begin on the date hereof.

    Hyperlinking to Content

        The following organizations may link to Website without prior written approval:

Government agencies

Search engines;

News organizations;

Online directory distributors may link to this Website in the same manner as they hyperlink to the Websites of other listed businesses; and

System wide Accredited Businesses except soliciting non-profit organizations, charity shopping malls, and charity fundraising groups which may not hyperlink to this Website.

            These organizations may link to this website home page, to publications or to other Website information so long as the link:

                (a) is not in any way deceptive;

                (b) does not falsely imply sponsorship, endorsement or approval of the linking party and its products and/or services; and

                (c) fits within the context of the linking party's site.

            I may consider and approve other link requests from the following types of organizations:

commonly-known consumer and/or business information sources;

dot.com community sites;

associations or other groups representing charities;

online directory distributors;

internet portals;

accounting, law and consulting firms; and

educational institutions and trade associations.

            i will approve link requests from these organizations if i decide that:

                (a) the link would not make me look unfavorably to myself or to my accredited businesses;

                (b) the organization does not have any negative records with me;

                (c) the benefit to me from the visibility of the hyperlink compensates the absence of this website; and

                (d) the link is in the context of general resource information.

            These organizations may link to our home page so long as the link:

                (a) is not in any way deceptive;

                (b) does not falsely imply sponsorship, endorsement or approval of the linking party and its products or services; and

                (c) fits within the context of the linking party's site.

            If you are one of the organizations listed in paragraph 2 above and are interested in linking to this website,
            you must inform me by sending an e-mail. Please include your name, your organization name,
            contact information as well as the URL of your site, a list of any URLs from which you intend to link to this Website,
            and a list of the URLs on our site to which you would like to link. Wait 2-3 weeks for a response.

            Approved organizations may hyperlink to this Website as follows:

By use of my name; or

By use of the uniform resource locator being linked to; or

By use of any other description of this Website being linked to that makes sense within the context and format of content on the linking party's site.

    iFrames

        Without prior approval and written permission, you may not create frames around this website Webpages
        that alter in any way the visual presentation or appearance of this Website.

    Content Liability

        I shall not be hold responsible for any content that appears on your Website.
        You agree to protect and defend me against all claims that is rising on your Website.
        No link(s) should appear on any Website that may be interpreted as libelous, obscene or criminal, or which infringes, otherwise violates,
        or advocates the infringement or other violation of, any third party rights.

    Your Privacy

        Please read  Privacy Policy

    Reservation of Rights

        I reserve the right to request that you remove all links or any particular link to this Website.
        You approve to immediately remove all links to our Website upon request.
        I also reserve the right to amend these terms and conditions and it's linking policy at any time.
        By continuously linking to this Website, you agree to be bound to and follow these linking terms and conditions.

    Removal of links from this website

        If you find any link on this Website that is offensive for any reason, you are free to contact and inform me any moment.
        I will consider requests to remove links but i am not obligated to or so or to respond to you directly.

        I do not ensure that the information on this website is correct, i do not warrant its completeness or accuracy;
        nor do i promise to ensure that the website remains available or that the material on the website is kept up to date.

    Disclaimer

        To the maximum extent permitted by applicable law, i exclude all representations, warranties and conditions
        relating to this website and the use of this website. Nothing in this disclaimer will:

limit or exclude me or your liability for death or personal injury;

limit or exclude me or your liability for fraud or fraudulent misrepresentation;

limit me or any of your liabilities in any way that is not permitted under applicable law; or

exclude me or any of your liabilities that may not be excluded under applicable law.

            The limitations and prohibitions of liability set in this Section and elsewhere in this disclaimer:
            (a) are subject to the preceding paragraph; and
            (b) govern all liabilities arising under the disclaimer, including liabilities arising in contract, in tort and for breach of statutory duty.

            As long as the website and the information and services on the website are provided free of charge,
            i will not be liable for any loss or damage of any nature.

    General

        I reserve the right to modify these Terms & Conditions at any time.

        Content that you see on the site is subject to changes as and when they happen and i am not obligated to give you prior notice of it.

    Consent

        By using this website, you hereby agree to its Terms and Conditions and consent to its Privacy Policy.


text:
/* eslint-disable new-cap */
import React, { PropTypes } from "react";
import Radium from "radium";

const Cell = (props) => {
  return (
    <div style={props.style}>
      {props.children}
    </div>
  );
};

const horizontalPropType = PropTypes.oneOf(["left", "center", "right"]);
const verticalPropType = PropTypes.oneOf(["top", "middle", "bottom"]);
Cell.propTypes = {
  width: PropTypes.string,
  horizontalAlign: horizontalPropType,
  verticalAlign: verticalPropType,
  order: PropTypes.number,

  smallWidth: PropTypes.string,
  smallHorizontalAlign: horizontalPropType,
  smallVerticalAlign: verticalPropType,
  smallOrder: PropTypes.number,

  mediumWidth: PropTypes.string,
  mediumHorizontalAlign: horizontalPropType,
  mediumVerticalAlign: verticalPropType,
  mediumOrder: PropTypes.number,

  largeWidth: PropTypes.string,
  largeHorizontalAlign: horizontalPropType,
  largeVerticalAlign: verticalPropType,
  largeOrder: PropTypes.number,

  xlargeWidth: PropTypes.string,
  xlargeHorizontalAlign: horizontalPropType,
  xlargeVerticalAlign: verticalPropType,
  xlargeOrder: PropTypes.number,

  children: PropTypes.node,
  style: PropTypes.object
};

export default Radium(Cell);


text:
package msg

import (
	"github.com/name5566/leaf/network/json"
	"github.com/name5566/leaf/network/protobuf"
)

var (
	JSONProcessor     = json.NewProcessor()
	ProtobufProcessor = protobuf.NewProcessor()
)

type _Base struct {
	Request *struct {
	} `json:"request,omitempty"`
	Response *struct {
	} `json:"response,omitempty"`
}
type Hello struct {
	Request *struct {
		S_name string `json:"name,omitempty"`
	} `json:"request,omitempty"`
	Response *struct {
		S_name string `json:"name,omitempty"`
	} `json:"response,omitempty"`
}

type Test struct {
	Request *struct {
		S_name string `json:"name,omitempty"`
	} `json:"request,omitempty"`
	Response *struct {
		S_name string `json:"name,omitempty"`
		I_code int    `json:"code"`
	} `json:"response,omitempty"`
}

type Login struct {
	Request struct {
		S_name string `json:"name,omitempty"`
		S_pwd  string `json:"pwd,omitempty"`
	} `json:"request,omitempty"`
	Response struct {
		S_name string `json:"name,omitempty"`
		I_code int    `json:"code"`
	} `json:"response,omitempty"`
}
type Join struct {
	Request struct {
		S_name string `json:"name,omitempty"`
		I_no   int    `json:"no,omitempty"`
	} `json:"request,omitempty"`
	Response struct {
		S_text string `json:"text,omitempty"`
		I_code int    `json:"code"`
	} `json:"response,omitempty"`
}
type Activity struct {
	Request struct {
		S_name        string `json:"name,omitempty"`
		I_green_pos_x string `json:"green_pos_x,omitempty"`
		I_green_pos_y string `json:"green_pos_y,omitempty"`
		I_grey_pos_x  string `json:"grey_pos_x,omitempty"`
		I_grey_pos_y  string `json:"grey_pos_y,omitempty"`
	} `json:"request,omitempty"`
	Response struct {
		S_text        string `json:"text,omitempty"`
		I_code        int    `json:"code"`
		S_name        string `json:"name,omitempty"`
		I_green_pos_x string `json:"green_pos_x,omitempty"`
		I_green_pos_y string `json:"green_pos_y,omitempty"`
		I_grey_pos_x  string `json:"grey_pos_x,omitempty"`
		I_grey_pos_y  string `json:"grey_pos_y,omitempty"`
	} `json:"response,omitempty"`
}
type GameInfo struct {
	S_name        string `json:"name,omitempty"`
	I_green_pos_x string `json:"green_pos_x,omitempty"`
	I_green_pos_y string `json:"green_pos_y,omitempty"`
	I_grey_pos_x  string `json:"grey_pos_x,omitempty"`
	I_grey_pos_y  string `json:"grey_pos_y,omitempty"`
}

func init() {
	//helper.INFO("msg init")
	JSONProcessor.Register(&Hello{})
	JSONProcessor.Register(&Login{})
	JSONProcessor.Register(&Join{})
	JSONProcessor.Register(&Activity{})
	JSONProcessor.Register(&GameInfo{})
}


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

namespace DataSetTools
{
    public class CompareBuilder
    {
        private DataTableProducer a;
        private DataTableProducer b;
        private string outputFolder;
        private TextWriter logWriter;

        public CompareBuilder(string outputFolder, TextWriter logWriter)
        {
            this.outputFolder = outputFolder;
            this.logWriter = logWriter;
        }

        public static DataSetComparer Build(string outputFolder, TextWriter logWriter, Func<CompareBuilder, DataSetComparer> func)
        {
            return func(new CompareBuilder(outputFolder, logWriter));
        }
        public CompareBuilder To(InputTypes inputType, string query, string connectionString = "", string tableNickName = "")
        {
            this.b = DataTableProducer.Factory.Create(new CompareBuilderOptions
            {
                InputType = inputType,
                Query = query,
                ConnectionString = connectionString,
                TableNickName = tableNickName
            });
            return this;
        }
        public CompareBuilder Compare(InputTypes inputType, string query, string connectionString = "", string tableNickName = "")
        {
            a = DataTableProducer.Factory.Create(new CompareBuilderOptions
            {
                InputType = inputType,
                Query = query,
                ConnectionString = connectionString,
                TableNickName = tableNickName
            });
            return this;
        }
        public CompareBuilder Compare(DataTable dt, string resultNick)
        {
            if (dt == null)
                throw new ArgumentNullException("dt");

            a = DataTableProducer.Factory.Create(new CompareBuilderOptions
            {
                InputType = InputTypes.DataTable,
                Query = resultNick,
                DataTable = dt,
                TableNickName = resultNick,
                ConnectionString = ""
            });
            return this;
        }
        public CompareBuilder To(DataTable dt, string resultNick)
        {
            if (dt == null)
                throw new ArgumentNullException("dt");

            b = DataTableProducer.Factory.Create(new CompareBuilderOptions
            {
                InputType = InputTypes.DataTable,
                Query = resultNick,
                DataTable = dt,
                TableNickName = resultNick,
                ConnectionString = ""
            });
            return this;
        }

        public DataSetComparer End()
        {
            if (a == null)
                throw new ArgumentNullException("a");
            if (b == null)
                throw new ArgumentNullException("b");

            return new DataSetComparer(outputFolder, logWriter, a, b);
        }
    }

    public class CompareBuilderOptions
    {
        public InputTypes InputType { set; get; }
        public string Query { set; get; }
        public string ConnectionString { set; get; }
        public string TableNickName { get; set; }

        public DataTable DataTable { get; set; }
    }

    /// <summary>
    /// Class for creating lazy DataTable producers
    /// </summary>
    public class DataTableProducer
    {
        public static class Factory
        {
            public static DataTableProducer Create(CompareBuilderOptions options)
            {
                switch (options.InputType)
                {
                    case InputTypes.Query:
                        return DataTableProducer.FromQuery(options);
                    case InputTypes.CsvFile:
                        return DataTableProducer.FromCsvFile(options);
                    case InputTypes.DataTable:
                        return DataTableProducer.FromDataTable(options);
                    default:
                        throw new ArgumentException("Unimplemented argument for InputType");
                }
            }
        }

        private Action<DataTable> Callback;
        public CompareBuilderOptions Options { get; set; }

        public void Fill(DataTable dt)
        {
            if (this.Callback == null)
            {
                throw new InvalidProgramException("Producer is not initialized");
            }

            Callback(dt);
        }

        private DataTableProducer(CompareBuilderOptions options, Action<DataTable> func)
        {
            this.Options = options;
            this.Callback = func;
        }

        public static DataTableProducer FromQuery(CompareBuilderOptions options)
        {
            return new DataTableProducer(options, new Action<DataTable>(dt =>
            {
                Fill(dt, options.Query, options.ConnectionString);
            }));
        }
        public static DataTableProducer FromDataTable(CompareBuilderOptions options)
        {
            return new DataTableProducer(options, new Action<DataTable>(dt =>
            {
                foreach (DataColumn col in options.DataTable.Columns)
                {
                    dt.Columns.Add(new DataColumn(col.ColumnName));
                }
                foreach (DataRow row in options.DataTable.Rows)
                {
                    var nRow = dt.NewRow();
                    nRow.ItemArray = row.ItemArray;
                    dt.Rows.Add(nRow);
                }
                //dt = options.DataTable;
            }));
        }
        public static DataTableProducer FromCsvFile(CompareBuilderOptions options)
        {
            return new DataTableProducer(options, new Action<DataTable>(dt =>
            {
                using (var reader = File.OpenText(options.Query))
                {
                    DataTableSerializer.FromTextReader(dt, reader);
                }
            }));
        }
        public static DataTableProducer FromCsvString(CompareBuilderOptions options, TextReader reader)
        {
            return new DataTableProducer(options, new Action<DataTable>(dt =>
            {
                DataTableSerializer.FromTextReader(dt, reader);
            }));
        }

        private static DataTable Fill(DataTable dt, string sql, string connectionString)
        {
            using (var con = new SqlConnection(connectionString))
            {
                con.Open();
                using (var da = new SqlDataAdapter(sql, con))
                {
                    da.SelectCommand.CommandTimeout = int.MaxValue;
                    da.Fill(dt);
                    return dt;
                }
            }
        }
    }
}


text:
/* -----------------------------------------------------------------------------
 *  *
 *  * File Name:  Node.hpp
 *  * Author: Danny Tran
 *  * Description:  Node.hpp implementation file for Node class
 *  * Date: 17 Feb 2017
 *  *
 *  ---------------------------------------------------------------------------- */

template<typename T>
Node<T>::Node(T value)
{
	m_next=nullptr;
	m_value=value;
}

template<typename T>
void Node<T>::setValue(T value)
{
	m_value=value;
}

template<typename T>
T& Node<T>::getValue()
{
	return(m_value);
}

template<typename T>
Node<T>* Node<T>::getNext() const
{
	return m_next;
}

template<typename T>
void Node<T>::setNext(Node<T>* nextNodePtr)
{
	m_next=nextNodePtr;
}


text:
package com.fluentinterface.proxy.internal;

import com.fluentinterface.proxy.BuilderState;
import com.fluentinterface.proxy.Instantiator;

/**
 * Instantiates an object using its default empty constructor.
 */
class EmptyConstructor<T> implements Instantiator<T> {
    private Class<T> targetClass;

    EmptyConstructor(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public T instantiate(BuilderState state) throws InstantiationException {
        try {
            return targetClass.newInstance();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
USAGE () {
  echo "USAGE: mkkconfig.sh [-d] [-h] [-m <menu>] [-o <kconfig-file>] [-mindepth <mindepth>] [-maxdepth <maxdepth>]"
  echo "Where:"
  echo " <-d>:"
  echo "   Enables debug output"
  echo " -m <menu>:"
  echo "   Menu description"
  echo " -o <kconfig-file>:"
  echo "   Identifies the specific configuratin for the selected <board-name>."
  echo "   This must correspond to a sub-directory under the board directory at"
  echo "   under build/configs/<board-name>/."
  echo " -mindepth <mindepth>:"
  echo "   Set the minimum depth to find configurations in sub-directory"
  echo " -maxdepth <maxdepth>:"
  echo "   Set the maximum depth to find configurations in sub-directory"
  echo " <-h>:"
  echo "   Prints this message and exits."
}

KCONFIG=Kconfig
unset MENU
DEPTH_MIN=2
DEPTH_MAX=2

while [ ! -z "$1" ]; do
  case $1 in
    -d )
      set -x
      ;;
    -m )
      shift
      MENU=$1
      ;;
    -o )
      shift
      KCONFIG=$1
      ;;
    -h )
      USAGE
      exit 0
      ;;
    -mindepth )
      shift
      DEPTH_MIN=$1
      ;;
    -maxdepth )
      shift
      DEPTH_MAX=$1
      ;;
    * )
      echo "ERROR: Unrecognized argument: $1"
      USAGE
      exit 1
      ;;
    esac
  shift
done

if [ ${DEPTH_MIN} -gt ${DEPTH_MAX} ]; then
  { echo "ERROR: Invalid depths, min ${DEPTH_MIN}, max ${DEPTH_MAX}"; exit 1; }
fi

if [ -f ${KCONFIG} ]; then
  rm ${KCONFIG} || { echo "ERROR: Failed to remove $PWD/${KCONFIG}"; exit 1; }
fi

echo mkkconfig in $PWD

KCONFIG_LIST=`find $PWD -mindepth ${DEPTH_MIN} -maxdepth ${DEPTH_MAX} -name ${KCONFIG} | sort -n`

echo "#" > ${KCONFIG}
echo "# For a description of the syntax of this configuration file," >> ${KCONFIG}
echo "# see kconfig-language at https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt" >> ${KCONFIG}
echo "#" >> ${KCONFIG}
echo "# This file is autogenerated, do not edit." >> ${KCONFIG}
echo "#" >> ${KCONFIG}
echo "" >> ${KCONFIG}

if [ ! -z "${MENU}" ]; then
  echo "menu \"${MENU}\"" >> ${KCONFIG}
fi

for FILE in ${KCONFIG_LIST}; do
  echo "source \"${FILE}\"" >> ${KCONFIG}
done

if [ ! -z "${MENU}" ]; then
  echo "endmenu # ${MENU}" >> ${KCONFIG}
fi


text: cp system_profiler-completion /usr/local/etc/bash_completion.d


text:
using System;

class HexDecFormat
{
    static void Main()
    {
        byte hexDecNum = 0xFE;
        Console.WriteLine("Integer variable {0} in hexadecimal format: {0:X}", hexDecNum, hexDecNum);
    }
}


text:
XCode source editor extension for quick moving cursor between lines.

Allows to move two or five lines up/down.

## Requirements
Xcode 8 and Swift 3.0

## Installation
Source editor extensions are still in beta at the time of writing so there is no easy way to run them.

In general running extension requires next steps:
- Check that you have Xcode 8 installed
- Open project and run extension scheme
- In dialog appeared choose Xcode as a target app. Double check that it's also Xcode 8
- You'll see a new instance of Xcode with gray icon meaning its a separate instance for testing extension
- Extension is installed in both instances and you can use it

Remember that after stopping target Xcode instance (one with gray icon) extension will go away.

## Troubleshooting
- If you dont see `Jump` menu item under `Editor` menu try run `sudo /usr/libexec/xpccachectl` and restart
- Also remember that signing should be enabled on both application and extension targets

## Using extension
This is just proof of concept and maybe a starting template for you to play with extensions.

Extensions are not ready for everyday use due to complicated installation process and lack of possibility to persist them between Xcode runs.

## License
`Jump` is available under the MIT license. See the [LICENSE](LICENSE) file for more info.


text:
using Hyena;
using FSpot.Core;
using FSpot.Utils;

namespace FSpot
{
    public class PhotoVersion : IPhotoVersion
    {
        public string Name { get; set; }
        public IPhoto Photo { get; private set; }
        public SafeUri BaseUri { get; set; }
        public string Filename { get; set; }

        public SafeUri Uri {
            get { return BaseUri.Append (Filename); }
            set {
                BaseUri = value.GetBaseUri ();
                Filename = value.GetFilename ();
            }
        }

        public string ImportMD5 { get; set; }
        public uint VersionId { get; private set; }
        public bool IsProtected { get; private set; }

        public PhotoVersion (IPhoto photo, uint version_id, SafeUri base_uri, string filename, string md5_sum, string name, bool is_protected)
        {
            Photo = photo;
            VersionId = version_id;
            BaseUri = base_uri;
            Filename = filename;
            ImportMD5 = md5_sum;
            Name = name;
            IsProtected = is_protected;
        }
    }
}


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

namespace magic.lore
{
    public class Mage
    {
        public string[] spells = null;

        public void initialize()
        {
            spells = new string[3];
        }
    }
}


text:
// Copyright 2007 - 2021, Alan Antonuk and the rabbitmq-c contributors.
// SPDX-License-Identifier: mit

/** \file */

/**
 * A TCP socket connection.
 */

#ifndef RABBITMQ_C_TCP_SOCKET_H
#define RABBITMQ_C_TCP_SOCKET_H

#include <rabbitmq-c/amqp.h>
#include <rabbitmq-c/export.h>

AMQP_BEGIN_DECLS

/**
 * Create a new TCP socket.
 *
 * Call amqp_connection_close() to release socket resources.
 *
 * \return A new socket object or NULL if an error occurred.
 *
 * \since v0.4.0
 */
AMQP_EXPORT
amqp_socket_t *AMQP_CALL amqp_tcp_socket_new(amqp_connection_state_t state);

/**
 * Assign an open file descriptor to a socket object.
 *
 * This function must not be used in conjunction with amqp_socket_open(), i.e.
 * the socket connection should already be open(2) when this function is
 * called.
 *
 * \param [in,out] self A TCP socket object.
 * \param [in] sockfd An open socket descriptor.
 *
 * \since v0.4.0
 */
AMQP_EXPORT
void AMQP_CALL amqp_tcp_socket_set_sockfd(amqp_socket_t *self, int sockfd);

AMQP_END_DECLS

#endif /* RABBITMQ_C_TCP_SOCKET_H */


text:
set -ex
MAVEN_JAR=target/c5db-${project.version}-jar-with-dependencies.jar
if [ -f ${MAVEN_JAR} ]
then
	echo "skiping maven"
else
	mvn assembly:single
fi
java -cp ${MAVEN_JAR}:target/c5db-${project.version}.jar c5db.Main


text:
require 'db_spec_helper'

module Bosh::Director
  describe 'add_errands' do
    let(:db) { DBSpecHelper.db }
    let(:migration_file) { '20170116235940_add_errand_runs.rb' }
    let(:instance) do
      {
        job: 'job',
        index: 1,
        deployment_id: 1,
        cloud_properties: 'cloud_properties',
        dns_records: 'dns_records',
        spec_json: 'spec_json',
        credentials_json: 'credentials_json',
        state: 'running'
      }
    end

    before do
      DBSpecHelper.migrate_all_before(migration_file)

      db[:deployments] << {
        name: 'deployment_with_teams',
        link_spec_json: 'link_spec_json'
      }

      db[:instances] << instance
    end

    it 'creates the table with default value for ran_successfully' do
      DBSpecHelper.migrate(migration_file)
      db[:errand_runs] << {id: 1, instance_id: 1, successful_configuration_hash: 'some_hash', successful_packages_spec: 'long_json'}

      expect(db[:errand_runs].first[:instance_id]).to eq(1)
      expect(db[:errand_runs].first[:successful]).to be_falsey
      expect(db[:errand_runs].first[:successful_configuration_hash]).to eq('some_hash')
      expect(db[:errand_runs].first[:successful_packages_spec]).to eq('long_json')
    end

    it 'does not allow null values for instance' do
      DBSpecHelper.migrate(migration_file)
      expect {
        db[:errand_runs] << {id: 1}
      }.to raise_error Sequel::DatabaseError
    end
  end
end


text: export var nested;


text:
Step 3 - Reading the Service Configuration

        Services typically have configuration. Configurations are directly supported in Polygene™. A
        ConfigurationComposite is a subtype of EntityComposite. That is because
        configurations are stored in EntityStores, can be modified in runtime by client code and has
        the same semantics as regular entities.

        Polygene™ also handles the bootstrapping of configuration for the services. If the ConfigurationComposite is
        not found in the configured entity store, then Polygene™ will automatically locate a properties file for each
        service instance, read those properties into a ConfigurationComposite instance, save that to the
        entity store and provide the values to the service. The properties file must be with the same name as
        the service instance with the extension "properties" in the same package as the service.

        For this exercise, create a LibraryConfiguration that contains "titles", "authors" and "copies".
        The first two are a string with a comma separated list, and the "copies" is just an Integer with how many
        copies are made of each title.

Steps to do.

Create a LibraryConfiguration interface that extends ConfigurationComposite,
            and has three Property instances named "titles", "authors" and
            "copies", where the first two are of String type and the last is of
            Integer type.

Delete the LibraryActivator and remove the @Activators annotation from the
            LibraryService and the corresponding createInitialData method.

            In the LibraryMixin remove the member injection of the ValueBuilderFactory, and
            instead inject the ValueBuilderFactory in the constructor.

            Inject the LibraryConfiguration via the constructor. The injection scope is @This.

            Create a resource called LibraryService.properties and place it in the directory
            org/apache/polygene/tutorials/services/step4 in the classpath (for instance, src/main/resources
            ).
            Put something like;

titles=Domain Driven Design, Pragmatic Programmer, Extreme Programming Explained
authors=Eric Evans, Andy Hunt, Kent Beck

#Number of copies of each book.
copies=3

            in this file.

            Load initial data from the LibraryConfiguration in the LibraryMixin constructor.


text:
import cgi
import datetime
import json
import urllib

from google.appengine.api import users
from google.appengine.api import search
from google.appengine.api.images import get_serving_url
from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

import webapp2

class Stream(ndb.Expando):
    name = ndb.StringProperty()
    tags = ndb.StringProperty()
    cover_url = ndb.StringProperty()
    followers = ndb.StringProperty(repeated=True)
    date = ndb.DateTimeProperty(auto_now_add=True)
    def to_dict(self):
        d = super(Stream, self).to_dict()
        d['id'] = self.key.id()
        return d

class Image(ndb.Model):
    image_url = ndb.StringProperty()
    latitude = ndb.FloatProperty()
    longitude = ndb.FloatProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)
    def to_dict(self):
        d = super(Image, self).to_dict()
        d['id'] = self.key.id()
        return d

class ManPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write('Hello, class!')
        self.response.write("""

I've created my own Connexus web API for the Android miniproject and I'd like to share it with the class.

Git repo

It's not completely functional, but here are the things that do work:

Get all streams:
connexus-api.appspot.com/allstreams

Get subscribed streams:

connexus-api.appspot.com/mystreams?email=zachbwhaley@gmail.com

Add stream:

curl --data "name=greyhounds&tags=greyhound&cover_url=http://imgur.com/IcCcXYg"
connexus-api.appspot.com/addstream

Get stream images:

connexus-api.appspot.com/images?stream=5629499534213120

Subscribe to a stream:

curl --data "email=zachbwhaley@gmail.com&stream=5629499534213120" connexus-api.appspot.com/subscribe

Image uploading

This is a two part call

1st: get the upload URL

connexus-api.appspot.com/upload/geturl

2nd: Send the URL with Latitude Longitude, a Stream id, and the location of your image as multipart data

curl -F "latitude=30.267549" -F "longitude=-97.743645" -F "stream=5629499534213120" -F "image=@/path/to/image.jpg"
http://connexus-api.appspot.com/url-given-from-above

Nearby Streams

connexus-api.appspot.com/nearbystreams?latitude=30.267549&longitude=-97.743645

Feel free to use these in your Android app :-)

Let me know if I'm missing anything, and please feel free to contribute.

""")

class AddStream(webapp2.RequestHandler):
    def post(self):
        stream = Stream()
        stream.name = self.request.get('name')
        stream.tags = self.request.get('tags')
        stream.cover_url = self.request.get('cover_url')
        stream.put()

class GetUploadUrl(webapp2.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload/handler')
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(upload_url)

class UploadImage(webapp2.RequestHandler):
    def post(self):
        upload_url = blobstore.create_upload_url('/upload/handler')
        self.response.headers['Content-Type'] = 'multipart/form-data'

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('image')
        blob_info = upload_files[0]
        key = blob_info.key()

        serving_url = get_serving_url(key)
        stream_id = self.request.get('stream')
        latitude = float(self.request.get('latitude'))
        longitude = float(self.request.get('longitude'))
        stream = Stream.get_by_id(long(stream_id))

        geopoint = search.GeoPoint(latitude, longitude)
        doc = search.Document(fields=[
            search.TextField(name='id', value=str(stream.key.id())),
            search.GeoField(name='loc', value=geopoint)])
        search.Index(name='geopoints').put(doc)

        image = Image(parent=stream.key)
        image.image_url = serving_url
        image.latitude = latitude
        image.longitude = longitude
        if stream.cover_url == '':
            stream.cover_url = serving_url
            stream.put()
        image.put()
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(image.to_dict(), cls=DateSkipper))

class Subscribe(webapp2.RequestHandler):
    def post(self):
        stream_id = self.request.get('stream')
        email = self.request.get('email')
        stream = Stream.get_by_id(long(stream_id))
        stream.followers.append(email)
        stream.put()

class AllStreams(webapp2.RequestHandler):
    def get(self):
        query = Stream.query().order(-Stream.date)
        streams = [stream.to_dict() for stream in query.fetch()]
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(streams, cls=DateSkipper))

class MyStreams(webapp2.RequestHandler):
    def get(self):
        query = Stream.query().order(-Stream.date)
        email = self.request.get('email')
        streams = [stream.to_dict() for stream in query.fetch() if email in stream.followers]
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(streams, cls=DateSkipper))

class NearbyStreams(webapp2.RequestHandler):
    def get(self):
        latitude = self.request.get('latitude')
        longitude = self.request.get('longitude')
        index = search.Index('geopoints')
        query = 'distance(loc, geopoint(%s, %s)) < 1000' % (latitude, longitude)
        results = index.search(query)
        ids = [long(doc.field('id').value) for doc in results]
        streams = Stream.query().order(-Stream.date).fetch()
        streams = [s.to_dict() for s in streams if s.key.id() in ids]
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(streams, cls=DateSkipper))

class StreamImages(webapp2.RequestHandler):
    def get(self):
        stream_id = self.request.get('stream')
        stream = Stream.get_by_id(long(stream_id))
        query = Image.query(ancestor=stream.key)
        images = [image.to_dict() for image in query.fetch()]
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(images, cls=DateSkipper))

class DateSkipper(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return
        return json.JSONEncoder.default(self, obj)

application = webapp2.WSGIApplication([
    ('/', ManPage),
    ('/addstream', AddStream),
    ('/allstreams', AllStreams),
    ('/mystreams', MyStreams),
    ('/nearbystreams', NearbyStreams),
    ('/images', StreamImages),
    ('/subscribe', Subscribe),
    ('/upload/geturl', GetUploadUrl),
    ('/upload', UploadImage),
    ('/upload/handler', UploadHandler),
], debug=True)


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Blog | Manuvr</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="canonical" href="">
  <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
  <link rel="icon" type="image/png" href="/favicon-196x196.png" sizes="196x196">
  <link rel="icon" type="image/png" href="/favicon-160x160.png" sizes="160x160">
  <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
  <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
  <meta name="msapplication-TileColor" content="#2f83cd">
  <meta name="msapplication-TileImage" content="/mstile-144x144.png">
  <link rel="stylesheet" href="/css/style.css" type="text/css">

  <link href="//fonts.googleapis.com/css?family=Lato:300,700" rel="stylesheet" type="text/css">
  <link href="//fonts.googleapis.com/css?family=Source+Code+Pro:400,700" rel="stylesheet" type="text/css">
  <link rel="alternative" href="/atom.xml" title="Manuvr.io" type="application/atom+xml">
  <meta name="description" content="Manuvr is a low cost gesture control data glove.">
<meta property="og:type" content="website">
<meta property="og:title" content="Blog">
<meta property="og:url" content="http://manuvr.io/blog/2015/">
<meta property="og:site_name" content="Manuvr.io">
<meta property="og:description" content="Manuvr is a low cost gesture control data glove.">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Blog">
<meta name="twitter:description" content="Manuvr is a low cost gesture control data glove.">
<meta name="twitter:site" content="@manuvrglove">

        Manuvr

              Technology

              Docs

              Company

              Blog

Blog

      Wearables, silicone, and artwork

    <time datetime="2015-01-27T19:42:19.000Z" itemprop="datePublished">Jan 27 2015</time>

      Scheduler Refactor

    <time datetime="2015-01-26T18:39:30.000Z" itemprop="datePublished">Jan 26 2015</time>

      The state of things

    <time datetime="2015-01-16T07:00:00.000Z" itemprop="datePublished">Jan 16 2015</time>

        © 2015 Manuvr.io

        Twitter
        GitHub


text:
namespace llvm {

class AsmPrinter;
class MCExpr;
class MCStreamer;

/// \brief MI-level patchpoint operands.
///
/// MI patchpoint operations take the form:
/// [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
///
/// IR patchpoint intrinsics do not have the <cc> operand because calling
/// convention is part of the subclass data.
///
/// SD patchpoint nodes do not have a def operand because it is part of the
/// SDValue.
///
/// Patchpoints following the anyregcc convention are handled specially. For
/// these, the stack map also records the location of the return value and
/// arguments.
class PatchPointOpers {
public:
  /// Enumerate the meta operands.
  enum { IDPos, NBytesPos, TargetPos, NArgPos, CCPos, MetaEnd };

private:
  const MachineInstr *MI;
  bool HasDef;
  bool IsAnyReg;

public:
  explicit PatchPointOpers(const MachineInstr *MI);

  bool isAnyReg() const { return IsAnyReg; }
  bool hasDef() const { return HasDef; }

  unsigned getMetaIdx(unsigned Pos = 0) const {
    assert(Pos < MetaEnd && "Meta operand index out of range.");
    return (HasDef ? 1 : 0) + Pos;
  }

  const MachineOperand &getMetaOper(unsigned Pos) {
    return MI->getOperand(getMetaIdx(Pos));
  }

  unsigned getArgIdx() const { return getMetaIdx() + MetaEnd; }

  /// Get the operand index of the variable list of non-argument operands.
  /// These hold the "live state".
  unsigned getVarIdx() const {
    return getMetaIdx() + MetaEnd +
           MI->getOperand(getMetaIdx(NArgPos)).getImm();
  }

  /// Get the index at which stack map locations will be recorded.
  /// Arguments are not recorded unless the anyregcc convention is used.
  unsigned getStackMapStartIdx() const {
    if (IsAnyReg)
      return getArgIdx();
    return getVarIdx();
  }

  /// \brief Get the next scratch register operand index.
  unsigned getNextScratchIdx(unsigned StartIdx = 0) const;
};

/// MI-level Statepoint operands
///
/// Statepoint operands take the form:
///   <id>, <num patch bytes >, <num call arguments>, <call target>,
///   [call arguments], <StackMaps::ConstantOp>, <calling convention>,
///   <StackMaps::ConstantOp>, <statepoint flags>,
///   <StackMaps::ConstantOp>, <num other args>, [other args],
///   [gc values]
class StatepointOpers {
private:
  // These values are aboolute offsets into the operands of the statepoint
  // instruction.
  enum { IDPos, NBytesPos, NCallArgsPos, CallTargetPos, MetaEnd };

  // These values are relative offests from the start of the statepoint meta
  // arguments (i.e. the end of the call arguments).
  enum { CCOffset = 1, FlagsOffset = 3, NumVMSArgsOffset = 5 };

public:
  explicit StatepointOpers(const MachineInstr *MI) : MI(MI) {}

  /// Get starting index of non call related arguments
  /// (calling convention, statepoint flags, vm state and gc state).
  unsigned getVarIdx() const {
    return MI->getOperand(NCallArgsPos).getImm() + MetaEnd;
  }

  /// Return the ID for the given statepoint.
  uint64_t getID() const { return MI->getOperand(IDPos).getImm(); }

  /// Return the number of patchable bytes the given statepoint should emit.
  uint32_t getNumPatchBytes() const {
    return MI->getOperand(NBytesPos).getImm();
  }

  /// Returns the target of the underlying call.
  const MachineOperand &getCallTarget() const {
    return MI->getOperand(CallTargetPos);
  }

private:
  const MachineInstr *MI;
};

class StackMaps {
public:
  struct Location {
    enum LocationType {
      Unprocessed,
      Register,
      Direct,
      Indirect,
      Constant,
      ConstantIndex
    };
    LocationType Type;
    unsigned Size;
    unsigned Reg;
    int64_t Offset;
    Location() : Type(Unprocessed), Size(0), Reg(0), Offset(0) {}
    Location(LocationType Type, unsigned Size, unsigned Reg, int64_t Offset)
        : Type(Type), Size(Size), Reg(Reg), Offset(Offset) {}
  };

  struct LiveOutReg {
    unsigned short Reg;
    unsigned short DwarfRegNum;
    unsigned short Size;

    LiveOutReg() : Reg(0), DwarfRegNum(0), Size(0) {}
    LiveOutReg(unsigned short Reg, unsigned short DwarfRegNum,
               unsigned short Size)
        : Reg(Reg), DwarfRegNum(DwarfRegNum), Size(Size) {}
  };

  // OpTypes are used to encode information about the following logical
  // operand (which may consist of several MachineOperands) for the
  // OpParser.
  typedef enum { DirectMemRefOp, IndirectMemRefOp, ConstantOp } OpType;

  StackMaps(AsmPrinter &AP);

  void reset() {
    CSInfos.clear();
    ConstPool.clear();
    FnStackSize.clear();
  }

  /// \brief Generate a stackmap record for a stackmap instruction.
  ///
  /// MI must be a raw STACKMAP, not a PATCHPOINT.
  void recordStackMap(const MachineInstr &MI);

  /// \brief Generate a stackmap record for a patchpoint instruction.
  void recordPatchPoint(const MachineInstr &MI);

  /// \brief Generate a stackmap record for a statepoint instruction.
  void recordStatepoint(const MachineInstr &MI);

  /// If there is any stack map data, create a stack map section and serialize
  /// the map info into it. This clears the stack map data structures
  /// afterwards.
  void serializeToStackMapSection();

private:
  static const char *WSMP;
  typedef SmallVector<Location, 8> LocationVec;
  typedef SmallVector<LiveOutReg, 8> LiveOutVec;
  typedef MapVector<uint64_t, uint64_t> ConstantPool;
  typedef MapVector<const MCSymbol *, uint64_t> FnStackSizeMap;

  struct CallsiteInfo {
    const MCExpr *CSOffsetExpr;
    uint64_t ID;
    LocationVec Locations;
    LiveOutVec LiveOuts;
    CallsiteInfo() : CSOffsetExpr(nullptr), ID(0) {}
    CallsiteInfo(const MCExpr *CSOffsetExpr, uint64_t ID,
                 LocationVec &&Locations, LiveOutVec &&LiveOuts)
        : CSOffsetExpr(CSOffsetExpr), ID(ID), Locations(std::move(Locations)),
          LiveOuts(std::move(LiveOuts)) {}
  };

  typedef std::vector<CallsiteInfo> CallsiteInfoList;

  AsmPrinter &AP;
  CallsiteInfoList CSInfos;
  ConstantPool ConstPool;
  FnStackSizeMap FnStackSize;

  MachineInstr::const_mop_iterator
  parseOperand(MachineInstr::const_mop_iterator MOI,
               MachineInstr::const_mop_iterator MOE, LocationVec &Locs,
               LiveOutVec &LiveOuts) const;

  /// \brief Create a live-out register record for the given register @p Reg.
  LiveOutReg createLiveOutReg(unsigned Reg,
                              const TargetRegisterInfo *TRI) const;

  /// \brief Parse the register live-out mask and return a vector of live-out
  /// registers that need to be recorded in the stackmap.
  LiveOutVec parseRegisterLiveOutMask(const uint32_t *Mask) const;

  /// This should be called by the MC lowering code _immediately_ before
  /// lowering the MI to an MCInst. It records where the operands for the
  /// instruction are stored, and outputs a label to record the offset of
  /// the call from the start of the text section. In special cases (e.g. AnyReg
  /// calling convention) the return register is also recorded if requested.
  void recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
                           MachineInstr::const_mop_iterator MOI,
                           MachineInstr::const_mop_iterator MOE,
                           bool recordResult = false);

  /// \brief Emit the stackmap header.
  void emitStackmapHeader(MCStreamer &OS);

  /// \brief Emit the function frame record for each function.
  void emitFunctionFrameRecords(MCStreamer &OS);

  /// \brief Emit the constant pool.
  void emitConstantPoolEntries(MCStreamer &OS);

  /// \brief Emit the callsite info for each stackmap/patchpoint intrinsic call.
  void emitCallsiteEntries(MCStreamer &OS);

  void print(raw_ostream &OS);
  void debug() { print(dbgs()); }
};
}

#endif


text:
package ro.adc.hra.employee;

import javax.inject.Inject;

import org.joda.time.LocalDateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import ro.adc.hra.base.OperationInfo;

import com.google.common.collect.ImmutableList;

@Controller
public class EmployeeController {

    private final EmployeeServices employeeServices;

    @Inject
    public EmployeeController(final EmployeeServices employeeServices) {
        this.employeeServices = employeeServices;
    }

    @RequestMapping("/employee")
    public String list(final ModelMap modelMap) {
        final FindEmployeesRq rq = new FindEmployeesRq();
        final FindEmployeesRs rs = employeeServices.findEmployees(rq);
        modelMap.put("employees", rs.getEmployees());
        modelMap.put("errors", rs.getMessages().getErrors());
        modelMap.put("infos", rs.getMessages().getInfos());
        return "employee/list";
    }

    @RequestMapping(value="/employee/create",method=RequestMethod.GET)
    public String createEmployee(final ModelMap modelMap) {
        modelMap.put("employeeDetail", new EmployeeDetail());
        return "employee/create";
    }

    @RequestMapping(value="/employee/create",method=RequestMethod.POST)
    public String createEmployee(@ModelAttribute("employeeDetail") final EmployeeDetail employee,
            final RedirectAttributes redirectAttributes,
            final BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            redirectAttributes.addAttribute("employeeDetail", employee);
            return "/redirect:employe/create";
        }
        final ModifyEmployeesRq rq = new ModifyEmployeesRq();
        final EmployeeCreation creation = new EmployeeCreation();
        creation.setEmployeeDetail(employee);
        rq.setOperations(ImmutableList.<EmployeeOperation>builder().add(creation).build());
        rq.setOperatorLocale("ro");;
        rq.setOperationInfo(new OperationInfo("user-todo", LocalDateTime.now()));
        employeeServices.modifyEmployees(rq);
        return "redirect:/employee";
    }

    @RequestMapping(value="/employee/{code}/update",method=RequestMethod.GET)
    public String showUpdateEmployee(@PathVariable("code") final String code,
            final ModelMap modelMap) {
        final FindEmployeesRq rq = new FindEmployeesRq();
        rq.setExpectsOne(Boolean.TRUE);
        rq.setEmployeeCodeIs(code);
        final FindEmployeesRs rs = employeeServices.findEmployees(rq);
        modelMap.put("employeeRecord", rs.getEmployee());
        if (!modelMap.containsKey("employeeDetail")) {
            modelMap.put("employeeDetail", rs.getEmployee().getDetail());
            modelMap.put("errors", rs.getMessages().getErrors());
            modelMap.put("infos", rs.getMessages().getInfos());
        }
        return "employee/update";
    }

    @RequestMapping(value="/employee/{code}/update", method=RequestMethod.POST)
    public String updateEmployee(@PathVariable("code") final String code,
            @ModelAttribute("employeeDetail") final EmployeeDetail employee,
            final RedirectAttributes redirectAttributes,
            final BindingResult bindingResult) {
        final ModifyEmployeesRq rq = new ModifyEmployeesRq();
        final EmployeeModification emplModif = new EmployeeModification();
        emplModif.setEmployeeCode(code);
        emplModif.setName(employee.getBasic().getName());
        rq.setOperations(ImmutableList.<EmployeeOperation>builder().add(emplModif).build());
        rq.setOperatorLocale("ro");;
        rq.setOperationInfo(new OperationInfo("user-todo", LocalDateTime.now()));
        final ModifyEmployeesRs rs = employeeServices.modifyEmployees(rq);
        redirectAttributes.addFlashAttribute("employeeDetail", employee);
        redirectAttributes.addFlashAttribute("errors", rs.getMessages().getErrors());
        redirectAttributes.addFlashAttribute("infos", rs.getMessages().getInfos());
        return String.format("redirect:/employee/%s/update", code);
    }
}


text:
Bibi.x({

    name: "JaTEx",
    description: "Japanese Typesetting Extra",
    author: "Satoru MATSUSHIMA (@satorumurmur)",
    version: "0.1.0",
    build: 20150722.1424,

    HTMLString: "", Current: 0, Log: false, LogCorrection: false, LogCancelation: false,

    parse: function(HTMLString, Scope) {
        if(HTMLString && typeof HTMLString == "object" && HTMLString.tagName) HTMLString = HTMLString.innerHTML;
        if(!HTMLString || typeof HTMLString != "string") return null;
        this.HTMLString = HTMLString, this.Current = 0;
        if(this.Log) {
            this.log(1, "BiB/i JaTEx");
            this.log(2, "parse");
            this.log(3, "HTMLString: " + this.HTMLString);
        }
        return this.parseInnerHTML();
    },

    parseInnerHTML: function() {
        var Foothold = this.Current, Parts = [];
        var Part = this.parsePart();
        while(Part !== null) {
            Parts.push(Part);
            Part = this.parsePart();
            if(!Part) break;
        }
        return (Parts.length ? Parts : null);
    },

    parsePart: function() {
        var Foothold = this.Current, Part = {};
        var HTMLSpecialPart = this.parseString(/^<[^>]*?>/);
        if(HTMLSpecialPart) {
            if(/^