text:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#include <grpc/byte_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>

#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channel_stack_builder.h"
#include "src/core/lib/config/core_configuration.h"
#include "src/core/lib/surface/channel_init.h"
#include "test/core/end2end/cq_verifier.h"
#include "test/core/end2end/end2end_tests.h"

enum { TIMEOUT = 200000 };

static void* tag(intptr_t t) { return reinterpret_cast<void*>(t); }

static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,
                                            const char* test_name,
                                            grpc_channel_args* client_args,
                                            grpc_channel_args* server_args) {
  grpc_end2end_test_fixture f;
  gpr_log(GPR_INFO, "Running test: %s/%s", test_name, config.name);
  f = config.create_fixture(client_args, server_args);
  config.init_server(&f, server_args);
  config.init_client(&f, client_args);
  return f;
}

static gpr_timespec n_seconds_from_now(int n) {
  return grpc_timeout_seconds_to_deadline(n);
}

static gpr_timespec five_seconds_from_now(void) {
  return n_seconds_from_now(5);
}

static void drain_cq(grpc_completion_queue* cq) {
  grpc_event ev;
  do {
    ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);
  } while (ev.type != GRPC_QUEUE_SHUTDOWN);
}

static void shutdown_server(grpc_end2end_test_fixture* f) {
  if (!f->server) return;
  grpc_server_shutdown_and_notify(f->server, f->cq, tag(1000));
  grpc_event ev;
  do {
    ev = grpc_completion_queue_next(f->cq, grpc_timeout_seconds_to_deadline(5),
                                    nullptr);
  } while (ev.type != GRPC_OP_COMPLETE || ev.tag != tag(1000));
  grpc_server_destroy(f->server);
  f->server = nullptr;
}

static void shutdown_client(grpc_end2end_test_fixture* f) {
  if (!f->client) return;
  grpc_channel_destroy(f->client);
  f->client = nullptr;
}

static void end_test(grpc_end2end_test_fixture* f) {
  shutdown_server(f);
  shutdown_client(f);

  grpc_completion_queue_shutdown(f->cq);
  drain_cq(f->cq);
  grpc_completion_queue_destroy(f->cq);
}

// Simple request to test that filters see a consistent view of the
// call context.
static void test_request(grpc_end2end_test_config config) {
  grpc_call* c;
  grpc_call* s;
  grpc_slice request_payload_slice =
      grpc_slice_from_copied_string("hello world");
  grpc_byte_buffer* request_payload =
      grpc_raw_byte_buffer_create(&request_payload_slice, 1);
  grpc_end2end_test_fixture f =
      begin_test(config, "filter_context", nullptr, nullptr);
  cq_verifier* cqv = cq_verifier_create(f.cq);
  grpc_op ops[6];
  grpc_op* op;
  grpc_metadata_array initial_metadata_recv;
  grpc_metadata_array trailing_metadata_recv;
  grpc_metadata_array request_metadata_recv;
  grpc_byte_buffer* request_payload_recv = nullptr;
  grpc_call_details call_details;
  grpc_status_code status;
  grpc_call_error error;
  grpc_slice details;
  int was_cancelled = 2;

  gpr_timespec deadline = five_seconds_from_now();
  c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,
                               grpc_slice_from_static_string("/foo"), nullptr,
                               deadline, nullptr);
  GPR_ASSERT(c);

  grpc_metadata_array_init(&initial_metadata_recv);
  grpc_metadata_array_init(&trailing_metadata_recv);
  grpc_metadata_array_init(&request_metadata_recv);
  grpc_call_details_init(&call_details);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->data.send_initial_metadata.metadata = nullptr;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  op->op = GRPC_OP_SEND_MESSAGE;
  op->data.send_message.send_message = request_payload;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  op->op = GRPC_OP_RECV_INITIAL_METADATA;
  op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
  op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
  op->data.recv_status_on_client.status = &status;
  op->data.recv_status_on_client.status_details = &details;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),
                                nullptr);
  GPR_ASSERT(GRPC_CALL_OK == error);

  error =
      grpc_server_request_call(f.server, &s, &call_details,
                               &request_metadata_recv, f.cq, f.cq, tag(101));
  GPR_ASSERT(GRPC_CALL_OK == error);

  CQ_EXPECT_COMPLETION(cqv, tag(101), 1);
  cq_verify(cqv);

  memset(ops, 0, sizeof(ops));
  op = ops;
  op->op = GRPC_OP_SEND_INITIAL_METADATA;
  op->data.send_initial_metadata.count = 0;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
  op->data.send_status_from_server.trailing_metadata_count = 0;
  op->data.send_status_from_server.status = GRPC_STATUS_UNIMPLEMENTED;
  grpc_slice status_string = grpc_slice_from_static_string("xyz");
  op->data.send_status_from_server.status_details = &status_string;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;
  op->data.recv_close_on_server.cancelled = &was_cancelled;
  op->flags = 0;
  op->reserved = nullptr;
  op++;
  error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102),
                                nullptr);
  GPR_ASSERT(GRPC_CALL_OK == error);

  CQ_EXPECT_COMPLETION(cqv, tag(102), 1);
  CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
  cq_verify(cqv);

  GPR_ASSERT(status == GRPC_STATUS_UNIMPLEMENTED);
  GPR_ASSERT(0 == grpc_slice_str_cmp(details, "xyz"));

  grpc_slice_unref(details);
  grpc_metadata_array_destroy(&initial_metadata_recv);
  grpc_metadata_array_destroy(&trailing_metadata_recv);
  grpc_metadata_array_destroy(&request_metadata_recv);
  grpc_call_details_destroy(&call_details);

  grpc_call_unref(s);
  grpc_call_unref(c);

  cq_verifier_destroy(cqv);

  grpc_byte_buffer_destroy(request_payload);
  grpc_byte_buffer_destroy(request_payload_recv);

  end_test(&f);
  config.tear_down_data(&f);
}

/*******************************************************************************
 * Test context filter
 */

struct call_data {
  grpc_call_context_element* context;
};

static grpc_error_handle init_call_elem(grpc_call_element* elem,
                                        const grpc_call_element_args* args) {
  call_data* calld = static_cast<call_data*>(elem->call_data);
  calld->context = args->context;
  gpr_log(GPR_INFO, "init_call_elem(): context=%p", args->context);
  return GRPC_ERROR_NONE;
}

static void start_transport_stream_op_batch(
    grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
  call_data* calld = static_cast<call_data*>(elem->call_data);
  // If batch payload context is not null (which will happen in some
  // cancellation cases), make sure we get the same context here that we
  // saw in init_call_elem().
  gpr_log(GPR_INFO, "start_transport_stream_op_batch(): context=%p",
          batch->payload->context);
  if (batch->payload->context != nullptr) {
    GPR_ASSERT(calld->context == batch->payload->context);
  }
  grpc_call_next_op(elem, batch);
}

static void destroy_call_elem(grpc_call_element* /*elem*/,
                              const grpc_call_final_info* /*final_info*/,
                              grpc_closure* /*ignored*/) {}

static grpc_error_handle init_channel_elem(
    grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) {
  return GRPC_ERROR_NONE;
}

static void destroy_channel_elem(grpc_channel_element* /*elem*/) {}

static const grpc_channel_filter test_filter = {
    start_transport_stream_op_batch,
    nullptr,
    grpc_channel_next_op,
    sizeof(call_data),
    init_call_elem,
    grpc_call_stack_ignore_set_pollset_or_pollset_set,
    destroy_call_elem,
    0,
    init_channel_elem,
    grpc_channel_stack_no_post_init,
    destroy_channel_elem,
    grpc_channel_next_get_info,
    "filter_context"};

/*******************************************************************************
 * Registration
 */

void filter_context(grpc_end2end_test_config config) {
  grpc_core::CoreConfiguration::RunWithSpecialConfiguration(
      [](grpc_core::CoreConfiguration::Builder* builder) {
        grpc_core::BuildCoreConfiguration(builder);
        for (auto type : {GRPC_CLIENT_CHANNEL, GRPC_CLIENT_SUBCHANNEL,
                          GRPC_CLIENT_DIRECT_CHANNEL, GRPC_SERVER_CHANNEL}) {
          builder->channel_init()->RegisterStage(
              type, INT_MAX, [](grpc_core::ChannelStackBuilder* builder) {
                // Want to add the filter as close to the end as possible, to
                // make sure that all of the filters work well together.
                // However, we can't add it at the very end, because the
                // connected channel filter must be the last one.  So we add it
                // right before the last one.
                auto it = builder->mutable_stack()->end();
                --it;
                builder->mutable_stack()->insert(it, &test_filter);
                return true;
              });
        }
      },
      [config] { test_request(config); });
}

void filter_context_pre_init(void) {}


text:
START_ATF_NAMESPACE
    struct tagEMRCREATECOLORSPACE
    {
        tagEMR emr;
        unsigned int ihCS;
        tagLOGCOLORSPACEA lcs;
    };
END_ATF_NAMESPACE

redpajama_set_name: RedPajamaGithub


text:
#ifdef _KERNEL

/* copy method of attr from lower to upper */
typedef enum _unionfs_copymode {
	UNIONFS_TRADITIONAL = 0,
	UNIONFS_TRANSPARENT,
	UNIONFS_MASQUERADE
} unionfs_copymode;

/* whiteout policy of upper layer */
typedef enum _unionfs_whitemode {
       UNIONFS_WHITE_ALWAYS = 0,
       UNIONFS_WHITE_WHENNEEDED
} unionfs_whitemode;

struct unionfs_mount {
	struct vnode   *um_lowervp;	/* VREFed once */
	struct vnode   *um_uppervp;	/* VREFed once */
	struct vnode   *um_rootvp;	/* ROOT vnode */
	unionfs_copymode um_copymode;
	unionfs_whitemode um_whitemode;
	uid_t		um_uid;
	gid_t		um_gid;
	u_short		um_udir;
	u_short		um_ufile;
};

/* unionfs status list */
struct unionfs_node_status {
	LIST_ENTRY(unionfs_node_status) uns_list;	/* Status list */
	pid_t		uns_pid;		/* current process id */
	int		uns_node_flag;		/* uns flag */
	int		uns_lower_opencnt;	/* open count of lower */
	int		uns_upper_opencnt;	/* open count of upper */
	int		uns_lower_openmode;	/* open mode of lower */
	int		uns_readdir_status;	/* read status of readdir */
};

/* union node status flags */
#define	UNS_OPENL_4_READDIR	0x01	/* open lower layer for readdir */

/* A cache of vnode references */
struct unionfs_node {
	struct vnode   *un_lowervp;		/* lower side vnode */
	struct vnode   *un_uppervp;		/* upper side vnode */
	struct vnode   *un_dvp;			/* parent unionfs vnode */
	struct vnode   *un_vnode;		/* Back pointer */
	LIST_HEAD(, unionfs_node_status) un_unshead;
						/* unionfs status head */
	LIST_HEAD(unionfs_node_hashhead, unionfs_node) *un_hashtbl;
						/* dir vnode hash table */
	LIST_ENTRY(unionfs_node)   un_hash;	/* hash list entry */
	u_long		un_hashmask;		/* bit mask */
	char           *un_path;		/* path */
	int		un_flag;		/* unionfs node flag */
};

/*
 * unionfs node flags
 * It needs the vnode with exclusive lock, when changing the un_flag variable.
 */
#define UNIONFS_OPENEXTL	0x01	/* openextattr (lower) */
#define UNIONFS_OPENEXTU	0x02	/* openextattr (upper) */

#define	MOUNTTOUNIONFSMOUNT(mp) ((struct unionfs_mount *)((mp)->mnt_data))
#define	VTOUNIONFS(vp) ((struct unionfs_node *)(vp)->v_data)
#define	UNIONFSTOV(xp) ((xp)->un_vnode)

int unionfs_init(struct vfsconf *vfsp);
int unionfs_uninit(struct vfsconf *vfsp);
int unionfs_nodeget(struct mount *mp, struct vnode *uppervp, struct vnode *lowervp, struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, struct thread *td);
void unionfs_noderem(struct vnode *vp, struct thread *td);
void unionfs_get_node_status(struct unionfs_node *unp, struct thread *td, struct unionfs_node_status **unspp);
void unionfs_tryrem_node_status(struct unionfs_node *unp, struct unionfs_node_status *unsp);

int unionfs_check_rmdir(struct vnode *vp, struct ucred *cred, struct thread *td);
int unionfs_copyfile(struct unionfs_node *unp, int docopy, struct ucred *cred, struct thread *td);
void unionfs_create_uppervattr_core(struct unionfs_mount *ump, struct vattr *lva, struct vattr *uva, struct thread *td);
int unionfs_create_uppervattr(struct unionfs_mount *ump, struct vnode *lvp, struct vattr *uva, struct ucred *cred, struct thread *td);
int unionfs_mkshadowdir(struct unionfs_mount *ump, struct vnode *duvp, struct unionfs_node *unp, struct componentname *cnp, struct thread *td);
int unionfs_mkwhiteout(struct vnode *dvp, struct componentname *cnp, struct thread *td, char *path);
int unionfs_relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp, struct componentname *cn, struct thread *td, char *path, int pathlen, u_long nameiop);
int unionfs_relookup_for_create(struct vnode *dvp, struct componentname *cnp, struct thread *td);
int unionfs_relookup_for_delete(struct vnode *dvp, struct componentname *cnp, struct thread *td);
int unionfs_relookup_for_rename(struct vnode *dvp, struct componentname *cnp, struct thread *td);

#ifdef DIAGNOSTIC
struct vnode   *unionfs_checklowervp(struct vnode *vp, char *fil, int lno);
struct vnode   *unionfs_checkuppervp(struct vnode *vp, char *fil, int lno);
#define	UNIONFSVPTOLOWERVP(vp) unionfs_checklowervp((vp), __FILE__, __LINE__)
#define	UNIONFSVPTOUPPERVP(vp) unionfs_checkuppervp((vp), __FILE__, __LINE__)
#else
#define	UNIONFSVPTOLOWERVP(vp) (VTOUNIONFS(vp)->un_lowervp)
#define	UNIONFSVPTOUPPERVP(vp) (VTOUNIONFS(vp)->un_uppervp)
#endif

extern struct vop_vector unionfs_vnodeops;

#ifdef MALLOC_DECLARE
MALLOC_DECLARE(M_UNIONFSNODE);
MALLOC_DECLARE(M_UNIONFSPATH);
#endif

#ifdef UNIONFS_DEBUG
#define UNIONFSDEBUG(format, args...) printf(format ,## args)
#else
#define UNIONFSDEBUG(format, args...)
#endif				/* UNIONFS_DEBUG */

#endif				/* _KERNEL */


text:
module PvOutputWrapper
  class Response
    require 'addressable/uri'
    attr_reader :response

    SERVICE_MAPPER = {
      # rubocop:disable Metrics/LineLength
      :getstatistic => %i(energy_generated energy_exported average_generation  minimum_generation maximum_generation average_efficiency outputs actual_date_from actual_date_to record_efficiency record_date energy_consumed peak_energy_import off_peak_energy_import shoulder_energy_import high_shoulder_energy_import average_consumption minimum_consumption maximum_consumption credit_amount debit_amount),
      :getstatus => %i(date time energy_generation power_generation energy_consumption power_consumption efficiency temperature voltage extended_value1 extended_value2 extended_value3 extended_value4 extended_value5 extended_value6),
      :getsystem => %i(system_name system_size postcode number_of_panels panel_power panel_brand number_of_inverters inverter_power inverter_brand orientation array_tilt shade install_date latitude longitude status_interval number_of_panels_secondary panel_power_secondary orientation_secondary array_tilt_secondary),
      :search => %i(system_name system_size postcode orientation outputs last_output system_id panel inverter distance latitude longitude),
      # rubocop:enable Metrics/LineLength
    }

    # @arg [Addressable::URI], [Net::HTTPOK].
    def initialize(uri, response)
      @uri = uri
      @response = response
    end

    # @return [String].
    def body
      @response.body.encode('UTF-8', { :invalid => :replace,
                                       :undef => :replace,
                                       :replace => '?',
                                     }
                           )
    end

    # TODO: response body changes depending on params!
    # TODO: fix specs
    # TODO: raise exception
    # @return [Hash], [Array] data mapped to keys.
    def parse
      # if body.chomp!
      if body.include?("\n")
        parse_multi_line
      else
        parse_line(response_keys, body)
      end
    end

    private

    # @arg [Array<Symbol>] keys for the hash.
    # [String] one line of the response body.
    # @return [Hash].
    def parse_line(keys, line)
      # Remove extended data, if any.
      before_semicolon = line.split(/;/)[0]
      values = before_semicolon.gsub(/,NaN,/, ',,').split(/,/)
      h = {}
      keys.each_with_index { |e, i| h[e] = values[i].to_s }
      h
    end

    # @return [Array].
    def parse_multi_line
      keys = response_keys
      raise hell unless keys

      # rubocop:disable Style/SingleLineBlockParams
      body.split("\n").reduce([]) { |a, line| a << parse_line(keys, line) }
      # rubocop:enable Style/SingleLineBlockParams
    end

    # @return [Array<Symbol>].
    def response_keys
      SERVICE_MAPPER[service]
    end

    # @return [Symbol].
    def service
      @uri.path.split('/').last.split('.').first.to_sym
    end

    # @return [Array<Symbol>].
    def param_keys
      @uri.query_values.keys.flat_map(:to_sym)
    end
  end
end


text:
package com.home.knowhunt.gameobjects;

import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;

import com.home.knowhunt.shared.Directions;

public abstract class Obstacle {

    private Node head;
    private int width;
    private int height;
    private int gameHeight;
    private boolean isAlive;
    private float rotation;
    private float lvl = 0.4f;
    private float lvlInc = 0.2f;
    private float maxLvl = 1.6f;

    public Obstacle(float x, float y, int width, int height) {
        head = new Node(new Vector2(x, y), Directions.NORTH);
        this.width = width;
        this.height = height;

        isAlive = true;
        rotation = 0f;
    }

    public void move(float delta) {
        switch (head.getDir()) {
            case NORTH:
                head.setY(head.getY() - delta);
                break;
            case EAST:
                head.setX(head.getX() + delta);
                break;
            case SOUTH:
                head.setY(head.getY() + delta);
                break;
            case WEST:
                head.setX(head.getX() - delta);
                break;
        }
    }

    /* x, y getters and setters */
    public float getX() { return head.getX(); }
    public float getY() { return head.getY(); }
    public void setX(float x) { head.setX(x); }
    public void setY(float y) { head.setY(y); }

    /* Directions getter and setter */
    public Directions getDir() { return head.getDir(); }
    public void setDir(Directions d) { head.setDir(d); }

    /* Node getter and setter */
    public Node getNode() { return head; }
    public void setNode(float x, float y) {
        head = new Node(new Vector2(x, y), getDir());
    }

    public int getWidth() { return width; }
    public int getHeight() { return height; }

    public void setGameHeight(int height) { this.gameHeight = height; }

    public void setAlive(boolean b) { isAlive = b; }
    public boolean isAlive()  { return isAlive; }

    public void setRotation(Directions d) { rotation = getRotation(d); }

    public static float getRotation(Directions d) {
        switch(d) {
            case NORTH: return -90;
            case SOUTH: return 90;
            case WEST: return 180;
            case EAST: return 0;
            default: return 0;
        }
    }

    public Rectangle getBoundingCircle() {return new Rectangle(getX(), getY(),
            getWidth() / 4.0f, getHeight() / 4.0f
            ); }

    public abstract void update(float delta);

    public boolean collides(Obstacle c) {
        return Intersector.overlaps(getBoundingCircle(), c.getBoundingCircle());
    }

    public boolean collides(Node n) {
        return Intersector.overlaps( n.getBoundingCircle(),getBoundingCircle());
    }
}


text:
@interface DDPBaseTableView ()<DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@end

@implementation DDPBaseTableView

- (void)endRefreshing {
    if (self.mj_header.isRefreshing) {
        [self.mj_header endRefreshing];
    }

    if (self.mj_footer.isRefreshing) {
        [self.mj_footer endRefreshing];
    }

    self.showEmptyView = YES;
    [self reloadEmptyDataSet];
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if (self = [super initWithFrame:frame style:style]) {
        [self commitInit];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self commitInit];
}

- (void)commitInit {
    self.emptyDataSetSource = self;
    self.emptyDataSetDelegate = self;
    self.backgroundColor = [UIColor ddp_backgroundColor];
    self.estimatedRowHeight = 0;
    self.estimatedSectionHeaderHeight = 0;
    self.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

@end


text:
package com.dmitriid.ji;

import com.ericsson.otp.erlang.OtpErlangDouble;

public class DoubleConverter extends AbstractErlangJavaConverter<Double, OtpErlangDouble>{
    public DoubleConverter() {
        super(Double.class, OtpErlangDouble.class);
    }

    protected OtpErlangDouble fromJava(Double in) {
        if(null == in) in = new Double(0);
        return new OtpErlangDouble(in);
    }

    protected Double fromErlang(OtpErlangDouble in) {
        return in.doubleValue();
    }
}


text:
/**
 * @jest-environment jsdom
 */
import { mount } from '@vue/test-utils';
import { Icon, iconExists } from '../../';
import { mockAPIData } from '@iconify/core/lib/api/modules/mock';
import { provider, nextPrefix } from './load';

const iconData = {
	body:
		'<path d="M4 19h16v2H4zm5-4h11v2H9zm-5-4h16v2H4zm0-8h16v2H4zm5 4h11v2H9z" fill="currentColor"/>',
	width: 24,
	height: 24,
};

const iconData2 = {
	body:
		'<path d="M19.031 4.281l-11 11l-.687.719l.687.719l11 11l1.438-1.438L10.187 16L20.47 5.719z" fill="currentColor"/>',
	width: 32,
	height: 32,
};

describe('Rendering icon', () => {
	test('changing icon property', done => {
		const prefix = nextPrefix();
		const name = 'changing-prop';
		const name2 = 'changing-prop2';
		const iconName = `@${provider}:${prefix}:${name}`;
		const iconName2 = `@${provider}:${prefix}:${name2}`;
		const className = `iconify iconify--${prefix} iconify--${provider}`;
		let onLoadCalled = ''; // Name of icon from last onLoad call

		const onLoad = name => {
			// onLoad should be called only once per icon
			switch (name) {
				// First onLoad call
				case iconName:
					expect(onLoadCalled).toBe('');
					break;

				// Second onLoad call
				case iconName2:
					expect(onLoadCalled).toBe(iconName);
					break;

				default:
					throw new Error(`Unexpected onLoad('${name}') call`);
			}
			onLoadCalled = name;
		};

		mockAPIData({
			type: 'icons',
			provider,
			prefix,
			response: {
				prefix,
				icons: {
					[name]: iconData,
				},
			},
			delay: next => {
				// Icon should not have loaded yet
				expect(iconExists(iconName)).toBe(false);

				// onLoad should not have been called yet
				expect(onLoadCalled).toBe('');

				// Send icon data
				next();

				// Test it again
				expect(iconExists(iconName)).toBe(true);

				// Check if state was changed
				// Wrapped in double setTimeout() because re-render takes 2 ticks (one to handle API response, one to re-render)
				setTimeout(() => {
					setTimeout(() => {
						expect(wrapper.html().replace(/\s*\n\s*/g, '')).toBe(
							'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24" class="' +
								className +
								'"><path d="M4 19h16v2H4zm5-4h11v2H9zm-5-4h16v2H4zm0-8h16v2H4zm5 4h11v2H9z" fill="currentColor"></path></svg>'
						);

						// onLoad should have been called
						expect(onLoadCalled).toBe(iconName);

						wrapper.setProps({
							icon: iconName2,
						});
					}, 0);
				}, 0);
			},
		});

		mockAPIData({
			type: 'icons',
			provider,
			prefix,
			response: {
				prefix,
				icons: {
					[name2]: iconData2,
				},
			},
			delay: next => {
				// Icon should not have loaded yet
				expect(iconExists(iconName2)).toBe(false);

				// onLoad should have been called only once for previous icon
				expect(onLoadCalled).toBe(iconName);

				// Send icon data
				next();

				// Test it again
				expect(iconExists(iconName2)).toBe(true);

				// Check if state was changed
				// Wrapped in double setTimeout() because re-render takes 2 ticks
				setTimeout(() => {
					setTimeout(() => {
						expect(wrapper.html().replace(/\s*\n\s*/g, '')).toBe(
							'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" class="' +
								className +
								'"><path d="M19.031 4.281l-11 11l-.687.719l.687.719l11 11l1.438-1.438L10.187 16L20.47 5.719z" fill="currentColor"></path></svg>'
						);

						// onLoad should have been called for second icon
						expect(onLoadCalled).toBe(iconName2);

						done();
					}, 0);
				}, 0);
			},
		});

		// Check if icon has been loaded
		expect(iconExists(iconName)).toBe(false);

		// Render component
		const wrapper = mount(Icon, {
			propsData: {
				icon: iconName,
				onLoad,
			},
		});

		// Should render placeholder
		expect(wrapper.html()).toBe('');

		// onLoad should not have been called yet
		expect(onLoadCalled).toBe('');
	});

	test('changing icon property while loading', done => {
		const prefix = nextPrefix();
		const name = 'changing-prop';
		const name2 = 'changing-prop2';
		const iconName = `@${provider}:${prefix}:${name}`;
		const iconName2 = `@${provider}:${prefix}:${name2}`;
		const className = `iconify iconify--${prefix} iconify--${provider}`;
		let isSync = true;

		mockAPIData({
			type: 'icons',
			provider,
			prefix,
			response: {
				prefix,
				icons: {
					[name]: iconData,
				},
			},
			delay: next => {
				// Should have been called asynchronously, which means icon name has changed
				expect(isSync).toBe(false);

				// Send icon data
				next();
			},
		});

		mockAPIData({
			type: 'icons',
			provider,
			prefix,
			response: {
				prefix,
				icons: {
					[name2]: iconData2,
				},
			},
			delay: next => {
				// Should have been called asynchronously
				expect(isSync).toBe(false);

				// Icon should not have loaded yet
				expect(iconExists(iconName2)).toBe(false);

				// Send icon data
				next();

				// Test it again
				expect(iconExists(iconName2)).toBe(true);

				// Check if state was changed
				// Wrapped in double setTimeout() because re-render takes 2 ticks (one to handle API response, one to re-render)
				setTimeout(() => {
					setTimeout(() => {
						expect(wrapper.html().replace(/\s*\n\s*/g, '')).toBe(
							'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" class="' +
								className +
								'"><path d="M19.031 4.281l-11 11l-.687.719l.687.719l11 11l1.438-1.438L10.187 16L20.47 5.719z" fill="currentColor"></path></svg>'
						);

						done();
					}, 0);
				}, 0);
			},
		});

		// Check if icon has been loaded
		expect(iconExists(iconName)).toBe(false);

		// Render component
		const wrapper = mount(Icon, {
			propsData: {
				icon: iconName,
			},
		});

		// Should render placeholder
		expect(wrapper.html()).toBe('');

		// Change icon name
		wrapper.setProps({
			icon: iconName2,
		});

		// Async
		isSync = false;
	});

	test('changing multiple properties', done => {
		const prefix = nextPrefix();
		const name = 'multiple-props';
		const iconName = `@${provider}:${prefix}:${name}`;
		const className = `iconify iconify--${prefix} iconify--${provider}`;

		mockAPIData({
			type: 'icons',
			provider,
			prefix,
			response: {
				prefix,
				icons: {
					[name]: iconData,
				},
			},
			delay: next => {
				// Icon should not have loaded yet
				expect(iconExists(iconName)).toBe(false);

				// Send icon data
				next();

				// Test it again
				expect(iconExists(iconName)).toBe(true);

				// Check if state was changed
				// Wrapped in double setTimeout() because re-render takes 2 ticks (one to handle API response, one to re-render)
				setTimeout(() => {
					setTimeout(() => {
						expect(wrapper.html().replace(/\s*\n\s*/g, '')).toBe(
							'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24" class="' +
								className +
								'"><path d="M4 19h16v2H4zm5-4h11v2H9zm-5-4h16v2H4zm0-8h16v2H4zm5 4h11v2H9z" fill="currentColor"></path></svg>'
						);

						// Add horizontal flip and style
						wrapper.setProps({
							icon: iconName,
							hFlip: true,
							// Vue 2 issue: changing style in unit test doesn't work, so changing color
							// TODO: test changing style in live demo to see if its a unit test bug or component issue
							color: 'red',
						});

						// Wait for 1 tick
						setTimeout(() => {
							expect(
								wrapper.html().replace(/\s*\n\s*/g, '')
							).toBe(
								'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24" class="' +
									className +
									'" style="color: red;"><g transform="translate(24 0) scale(-1 1)"><path d="M4 19h16v2H4zm5-4h11v2H9zm-5-4h16v2H4zm0-8h16v2H4zm5 4h11v2H9z" fill="currentColor"></path></g></svg>'
							);

							done();
						}, 0);
					}, 0);
				}, 0);
			},
		});

		// Check if icon has been loaded
		expect(iconExists(iconName)).toBe(false);

		// Render component with placeholder text
		const wrapper = mount(Icon, {
			propsData: {
				icon: iconName,
			},
		});

		// Should be empty
		expect(wrapper.html()).toBe('');
	});
});


text:
package org.apache.nifi.web.api.entity;

import io.swagger.annotations.ApiModelProperty;
import org.apache.nifi.web.api.dto.RevisionDTO;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.Map;

@XmlRootElement(name = "activateControllerServicesEntity")
public class ActivateControllerServicesEntity extends Entity {
    public static final String STATE_ENABLED = "ENABLED";
    public static final String STATE_DISABLED = "DISABLED";

    private String id;
    private String state;
    private Map<String, RevisionDTO> components;
    private Boolean disconnectedNodeAcknowledged;

    @ApiModelProperty("The id of the ProcessGroup")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return The desired state of the descendant components. Possible states are 'RUNNING' and 'STOPPED'
     */
    @ApiModelProperty(value = "The desired state of the descendant components",
        allowableValues = STATE_ENABLED + ", " + STATE_DISABLED)
    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @ApiModelProperty("Optional services to schedule. If not specified, all authorized descendant controller services will be used.")
    public Map<String, RevisionDTO> getComponents() {
        return components;
    }

    public void setComponents(Map<String, RevisionDTO> components) {
        this.components = components;
    }

    @ApiModelProperty(
            value = "Acknowledges that this node is disconnected to allow for mutable requests to proceed."
    )
    public Boolean isDisconnectedNodeAcknowledged() {
        return disconnectedNodeAcknowledged;
    }

    public void setDisconnectedNodeAcknowledged(Boolean disconnectedNodeAcknowledged) {
        this.disconnectedNodeAcknowledged = disconnectedNodeAcknowledged;
    }
}


text:
/*
 * diagonal_formula.cpp
 *
 *  Created on: Dec 4, 2013
 *      Author: Devin
 *
 *  Defines the DiagonalFormula class.
 */

#include "diagonal_formula.h"
#include <set>
#include <algorithm>
using std::set;
using std::sort;

namespace Platt {

  DiagonalFormula::DiagonalFormula(int d) :
      RestrictedTree(d-1, d-1, 2*d-2) {
    // Build a set of all distinct subsequences of d-1 composites.
    set <FactorizationSequence> FSs;
    FactorizationSequence FS;

    // Add composites to the sequence on the way down
    auto PrechildFunctor = [&] (Node<Factorization>* N) {
      if (!(N->GetData().IsPrime()))
        FS.Push(N->GetData());
    };

    // Remove composites on the way back up.
    auto PostchildFunctor = [&] (Node<Factorization>* N) {
      if (!(N->GetData().IsPrime()))
        FS.Pop();
    };

    // Add the sequence to the set
    auto LeafFunctor = [&] (Node<Factorization>* N) {
      if (!(N->GetData().IsPrime()))
              FS.Push(N->GetData());
      FSs.insert(FS);
      if (!(N->GetData().IsPrime()))
              FS.Pop();
    };

    tree.DepthFirst(&PrechildFunctor, &PostchildFunctor, &LeafFunctor);

    // Now pass over the tree for each FactorizationSequence and determine
    // its corresponding coefficient.
    for(FactorizationSequence FS : FSs) {
      vector<Node<Factorization>*> common;
      vector<Node<Factorization>*> current;
      FactorizationSequence currentFS;

      //
      auto PrechildFunctor = [&] (Node<Factorization>* N) {
        current.push_back(N);
        if (!(N->GetData()).IsPrime())
          currentFS.Push(N->GetData());
      };

      auto PostchildFunctor = [&] (Node<Factorization>* N) {
        current.pop_back();
        if (!(N->GetData()).IsPrime())
                  currentFS.Pop();
      };

      // Add the sequence to the set
      auto LeafFunctor = [&] (Node<Factorization>* N) {
        current.push_back(N);
        if (!(N->GetData()).IsPrime())
                  currentFS.Push(N->GetData());
        // Case of first branch with the FS subsequence
        if(common.size() == 0) {
          if (currentFS == FS)
            common = current;
        } else {  // common is populated
          if (currentFS == FS) {
            // Trim common down to the common lead sequence
            size_t x = common.size()-1;
            while(current[x] != common[x]) { // equality as pointers!
              common.pop_back();
              x--;
            }
          }
        }
        current.pop_back();
        if (!(N->GetData()).IsPrime())
          currentFS.Pop();
      };

      tree.DepthFirst(&PrechildFunctor, &PostchildFunctor, &LeafFunctor);

      FSvec.push_back(FS);
      // TODO: fix this comment.
      // The binomial coefficient corresponding to FS is:
      // (?????) choose
      // (?????)
      // Our values are offset by a value of d-1 because our sequence starts
      // from row d
      // If there is just one branch for the FS, we choose all d-1 composites
      // (which occur after a string of d-1 primes). Thus we have d-1 spots to
      // fill, but the offset cancels this to 0.
      // Otherwise, we have the length of the whole branch (2*d-2) minus the
      // length of the common sequence, and this again is offset by subtracting
      // 2*d-2 - (d-1) = d-1.
      if ((int)common.size() == 2*d-2)
        n_offset.push_back(0);  // num_comp == d-1
      else
        n_offset.push_back(d-1-common.size());
      // Determine the number of composites in common.
      int num_comp = 0;
      for (Node<Factorization>* N : common) {
        if (!(N->GetData()).IsPrime())
          num_comp++;
      }
      // If there is just one branch for the FS, we choose all composites
      // (which occur after a string of d-1 primes)
      if ((int)common.size() == 2*d-2)
        k.push_back(num_comp);  // num_comp == d-1
      else
        k.push_back(d-1-num_comp);
    }

  }

  string DiagonalFormula::GetFormulaString() {
    string out;
    for(size_t x = 0; x < FSvec.size(); ++x) {
      out += FSvec[x].ToString() + ": (n + " + to_string(n_offset[x])
             + ") choose " + to_string(k[x]) + "\n";
    }
    return out;
  }

  vector <Tuple> DiagonalFormula::GetFormula() {
    vector <Tuple> out;
    for(size_t x = 0; x < k.size(); ++x)
      out.push_back(Tuple(n_offset[x], k[x]));
    sort(out.begin(), out.end(), LexicographicallyLess);
    return out;
  }

}  // namespace Platt


text:
<!DOCTYPE HTML>

		<title>Events · LSE SU Machine Learning Society</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<meta name="author" content="ML@LSE">
		<meta name="description" content="LSE SU Machine Learning Society Webpage">

		<meta name="og:site_name" content="LSE SU Machine Learning Society">
		<meta name="og:title" content="Events">
		<meta name="og:url" content="https://mlatlse.github.io/events/">

		<meta name="og:image" content="https://mlatlse.github.io/images/new_logo.png">

		<meta name="generator" content="Hugo 0.56.3" />

		<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<link rel="stylesheet" href="https://mlatlse.github.io/css/main.css" />

LSE SU Machine Learning Society

Home

Events

Learn

Projects

Register (LSESU)

        Give It A Go

<time datetime="2019-07-20 20:40:05 +0800 HKT">2019-07-20</time>

        events

 Welcome to ML@LSE We look forward to seeing you in the 2019-2020 year

Facebook

GitHub

Linkedin

Email

© LSE SU Machine Learning Society 2019 |  Design: HTML5 UP


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var Subject_1 = require("../../Subject");
var Subscriber_1 = require("../../Subscriber");
var Observable_1 = require("../../Observable");
var Subscription_1 = require("../../Subscription");
var ReplaySubject_1 = require("../../ReplaySubject");
var tryCatch_1 = require("../../util/tryCatch");
var errorObject_1 = require("../../util/errorObject");
var DEFAULT_WEBSOCKET_CONFIG = {
    url: '',
    deserializer: function (e) { return JSON.parse(e.data); },
    serializer: function (value) { return JSON.stringify(value); },
};
var WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT = 'WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }';
var WebSocketSubject = (function (_super) {
    __extends(WebSocketSubject, _super);
    function WebSocketSubject(urlConfigOrSource, destination) {
        var _this = _super.call(this) || this;
        if (urlConfigOrSource instanceof Observable_1.Observable) {
            _this.destination = destination;
            _this.source = urlConfigOrSource;
        }
        else {
            var config = _this._config = __assign({}, DEFAULT_WEBSOCKET_CONFIG);
            _this._output = new Subject_1.Subject();
            if (typeof urlConfigOrSource === 'string') {
                config.url = urlConfigOrSource;
            }
            else {
                for (var key in urlConfigOrSource) {
                    if (urlConfigOrSource.hasOwnProperty(key)) {
                        config[key] = urlConfigOrSource[key];
                    }
                }
            }
            if (!config.WebSocketCtor && WebSocket) {
                config.WebSocketCtor = WebSocket;
            }
            else if (!config.WebSocketCtor) {
                throw new Error('no WebSocket constructor can be found');
            }
            _this.destination = new ReplaySubject_1.ReplaySubject();
        }
        return _this;
    }
    WebSocketSubject.prototype.lift = function (operator) {
        var sock = new WebSocketSubject(this._config, this.destination);
        sock.operator = operator;
        sock.source = this;
        return sock;
    };
    WebSocketSubject.prototype._resetState = function () {
        this._socket = null;
        if (!this.source) {
            this.destination = new ReplaySubject_1.ReplaySubject();
        }
        this._output = new Subject_1.Subject();
    };
    WebSocketSubject.prototype.multiplex = function (subMsg, unsubMsg, messageFilter) {
        var self = this;
        return new Observable_1.Observable(function (observer) {
            var result = tryCatch_1.tryCatch(subMsg)();
            if (result === errorObject_1.errorObject) {
                observer.error(errorObject_1.errorObject.e);
            }
            else {
                self.next(result);
            }
            var subscription = self.subscribe(function (x) {
                var result = tryCatch_1.tryCatch(messageFilter)(x);
                if (result === errorObject_1.errorObject) {
                    observer.error(errorObject_1.errorObject.e);
                }
                else if (result) {
                    observer.next(x);
                }
            }, function (err) { return observer.error(err); }, function () { return observer.complete(); });
            return function () {
                var result = tryCatch_1.tryCatch(unsubMsg)();
                if (result === errorObject_1.errorObject) {
                    observer.error(errorObject_1.errorObject.e);
                }
                else {
                    self.next(result);
                }
                subscription.unsubscribe();
            };
        });
    };
    WebSocketSubject.prototype._connectSocket = function () {
        var _this = this;
        var _a = this._config, WebSocketCtor = _a.WebSocketCtor, protocol = _a.protocol, url = _a.url, binaryType = _a.binaryType;
        var observer = this._output;
        var socket = null;
        try {
            socket = protocol ?
                new WebSocketCtor(url, protocol) :
                new WebSocketCtor(url);
            this._socket = socket;
            if (binaryType) {
                this._socket.binaryType = binaryType;
            }
        }
        catch (e) {
            observer.error(e);
            return;
        }
        var subscription = new Subscription_1.Subscription(function () {
            _this._socket = null;
            if (socket && socket.readyState === 1) {
                socket.close();
            }
        });
        socket.onopen = function (e) {
            var openObserver = _this._config.openObserver;
            if (openObserver) {
                openObserver.next(e);
            }
            var queue = _this.destination;
            _this.destination = Subscriber_1.Subscriber.create(function (x) {
                if (socket.readyState === 1) {
                    var serializer = _this._config.serializer;
                    var msg = tryCatch_1.tryCatch(serializer)(x);
                    if (msg === errorObject_1.errorObject) {
                        _this.destination.error(errorObject_1.errorObject.e);
                        return;
                    }
                    socket.send(msg);
                }
            }, function (e) {
                var closingObserver = _this._config.closingObserver;
                if (closingObserver) {
                    closingObserver.next(undefined);
                }
                if (e && e.code) {
                    socket.close(e.code, e.reason);
                }
                else {
                    observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT));
                }
                _this._resetState();
            }, function () {
                var closingObserver = _this._config.closingObserver;
                if (closingObserver) {
                    closingObserver.next(undefined);
                }
                socket.close();
                _this._resetState();
            });
            if (queue && queue instanceof ReplaySubject_1.ReplaySubject) {
                subscription.add(queue.subscribe(_this.destination));
            }
        };
        socket.onerror = function (e) {
            _this._resetState();
            observer.error(e);
        };
        socket.onclose = function (e) {
            _this._resetState();
            var closeObserver = _this._config.closeObserver;
            if (closeObserver) {
                closeObserver.next(e);
            }
            if (e.wasClean) {
                observer.complete();
            }
            else {
                observer.error(e);
            }
        };
        socket.onmessage = function (e) {
            var deserializer = _this._config.deserializer;
            var result = tryCatch_1.tryCatch(deserializer)(e);
            if (result === errorObject_1.errorObject) {
                observer.error(errorObject_1.errorObject.e);
            }
            else {
                observer.next(result);
            }
        };
    };
    WebSocketSubject.prototype._subscribe = function (subscriber) {
        var _this = this;
        var source = this.source;
        if (source) {
            return source.subscribe(subscriber);
        }
        if (!this._socket) {
            this._connectSocket();
        }
        this._output.subscribe(subscriber);
        subscriber.add(function () {
            var _socket = _this._socket;
            if (_this._output.observers.length === 0) {
                if (_socket && _socket.readyState === 1) {
                    _socket.close();
                }
                _this._resetState();
            }
        });
        return subscriber;
    };
    WebSocketSubject.prototype.unsubscribe = function () {
        var _a = this, source = _a.source, _socket = _a._socket;
        if (_socket && _socket.readyState === 1) {
            _socket.close();
            this._resetState();
        }
        _super.prototype.unsubscribe.call(this);
        if (!source) {
            this.destination = new ReplaySubject_1.ReplaySubject();
        }
    };
    return WebSocketSubject;
}(Subject_1.AnonymousSubject));
exports.WebSocketSubject = WebSocketSubject;
//# sourceMappingURL=WebSocketSubject.js.map


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AxisTests.cs" company="OxyPlot">
//   Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
//   Provides unit tests for the <see cref="Axis" /> class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace OxyPlot.Tests
{
    using System;
    using System.Diagnostics.CodeAnalysis;

    using NUnit.Framework;

    using OxyPlot.Axes;
    using OxyPlot.Series;

    /// <summary>
    /// Provides unit tests for the <see cref="Axis" /> class.
    /// </summary>
    [TestFixture]
    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
    // ReSharper disable InconsistentNaming
    public class AxisTests
    {
        [Test]
        public void A00_NoAxesDefined()
        {
            var plot = new PlotModel { Title = "Simple plot without axes defined" };

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(3, 13));
            ls.Points.Add(new DataPoint(10, 47));
            ls.Points.Add(new DataPoint(30, 23));
            ls.Points.Add(new DataPoint(40, 65));
            ls.Points.Add(new DataPoint(80, 10));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A00");
        }

        [Test]
        public void A01_SimpleAxes()
        {
            var plot = new PlotModel { Title = "Simple plot" };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(3, 13));
            ls.Points.Add(new DataPoint(10, 47));
            ls.Points.Add(new DataPoint(30, 23));
            ls.Points.Add(new DataPoint(40, 65));
            ls.Points.Add(new DataPoint(80, 10));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A01");
        }

        [Test]
        public void A02_ReversedAxes()
        {
            var plot = new PlotModel { Title = "Reversed axes" };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis", StartPosition = 1, EndPosition = 0 });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis", StartPosition = 1, EndPosition = 0 });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(0, 13));
            ls.Points.Add(new DataPoint(10, 47));
            ls.Points.Add(new DataPoint(30, 23));
            ls.Points.Add(new DataPoint(40, 65));
            ls.Points.Add(new DataPoint(80, 10));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A02");
        }

        [Test]
        public void A11_SmallRangeAxis()
        {
            var plot = new PlotModel { Title = "Small range axis", PlotMargins = new OxyThickness(80, 60, 50, 50) };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1e-40, 1e-38));
            ls.Points.Add(new DataPoint(1.2e-40, 1.9e-38));
            ls.Points.Add(new DataPoint(1.4e-40, 3.3e-38));
            ls.Points.Add(new DataPoint(1.6e-40, 2.5e-38));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A11");
        }

        [Test]
        public void A12_LargeRangeAxis()
        {
            var plot = new PlotModel { Title = "Large range axis", PlotMargins = new OxyThickness(80, 60, 50, 50) };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1e40, 1e38));
            ls.Points.Add(new DataPoint(1.2e40, 1.9e38));
            ls.Points.Add(new DataPoint(1.4e40, 3.3e38));
            ls.Points.Add(new DataPoint(1.6e40, 2.5e38));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A12");
        }

        [Test]
        public void A13_BadConditionedAxis()
        {
            var plot = new PlotModel { Title = "Bad conditioned axis", PlotMargins = new OxyThickness(80, 60, 50, 50) };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1.20000000001, 2400000001));
            ls.Points.Add(new DataPoint(1.20000000002, 2400000000));
            ls.Points.Add(new DataPoint(1.20000000004, 2400000004));
            ls.Points.Add(new DataPoint(1.20000000007, 2400000003));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A13");
        }

        [Test]
        public void A13B_BadConditionedAxis_SettingMinimumRange()
        {
            var plot = new PlotModel
            {
                Title = "Bad conditioned axis with MinimumRange",
                PlotMargins = new OxyThickness(80, 60, 50, 50)
            };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis", MinimumRange = 1e-3 });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis", MinimumRange = 1e8, StringFormat = "0.00E00" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1.20000000001, 2400000001));
            ls.Points.Add(new DataPoint(1.20000000002, 2400000000));
            ls.Points.Add(new DataPoint(1.20000000004, 2400000004));
            ls.Points.Add(new DataPoint(1.20000000007, 2400000003));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A13B");
        }

        [Test]
        public void A14_ConstantValue()
        {
            var plot = new PlotModel { Title = "Constant value" };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1, 2.4));
            ls.Points.Add(new DataPoint(2, 2.4));
            ls.Points.Add(new DataPoint(3, 2.4));
            ls.Points.Add(new DataPoint(4, 2.4));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A14");
        }

        [Test]
        public void A15_SinglePoint()
        {
            var plot = new PlotModel { Title = "Single point" };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1, 2.4));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A15");
        }

        [Test]
        public void A16_TwoClosePoints()
        {
            var plot = new PlotModel { Title = "Two close points" };
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "X-axis", MinimumRange = 1e-3 });
            plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1, 2.4));
            ls.Points.Add(new DataPoint(1.000000000001, 2.4));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "A16");
        }

        [Test]
        public void B01_LogarithmicAxis()
        {
            var plot = new PlotModel { Title = "Logarithmic axis" };
            plot.Axes.Add(new LogarithmicAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LogarithmicAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1.2, 3.3));
            ls.Points.Add(new DataPoint(10, 30));
            ls.Points.Add(new DataPoint(100, 20));
            ls.Points.Add(new DataPoint(1000, 400));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "B01");
        }

        [Test]
        public void B02_LogarithmicAxis()
        {
            var plot = new PlotModel { Title = "Logarithmic axis" };
            plot.Axes.Add(new LogarithmicAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LogarithmicAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1, 12));
            ls.Points.Add(new DataPoint(3, 14));
            ls.Points.Add(new DataPoint(24, 18));
            ls.Points.Add(new DataPoint(27, 19));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "B02");
        }

        [Test]
        public void B03_LogarithmicAxis()
        {
            var plot = new PlotModel { Title = "Logarithmic axis" };
            plot.Axes.Add(new LogarithmicAxis { Position = AxisPosition.Bottom, Title = "X-axis" });
            plot.Axes.Add(new LogarithmicAxis { Position = AxisPosition.Left, Title = "Y-axis" });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1e10, 1e18));
            ls.Points.Add(new DataPoint(1.2e20, 1.9e28));
            ls.Points.Add(new DataPoint(1.4e30, 3.3e30));
            ls.Points.Add(new DataPoint(1.6e40, 2.5e38));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "B03");
        }

        [Test]
        public void B04_LogarithmicAxis_Padding()
        {
            var plot = new PlotModel { Title = "Logarithmic axis with padding" };
            plot.Axes.Add(
                new LogarithmicAxis { Position = AxisPosition.Bottom, Title = "X-axis", MinimumPadding = 0.3, MaximumPadding = 0.3 });
            plot.Axes.Add(
                new LogarithmicAxis { Position = AxisPosition.Left, Title = "Y-axis", MinimumPadding = 0.3, MaximumPadding = 0.3 });

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(1, 12));
            ls.Points.Add(new DataPoint(3, 14));
            ls.Points.Add(new DataPoint(24, 18));
            ls.Points.Add(new DataPoint(27, 19));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "B04");
        }

        [Test]
        public void B05_LogarithmicAxis_SuperExponentialFormat()
        {
            var plot = new PlotModel { Title = "Logarithmic axis with SuperExponentialFormat" };
            plot.Axes.Add(
                new LogarithmicAxis
                {
                    Position = AxisPosition.Bottom,
                    Title = "X-axis",
                    Minimum = 1.8e2,
                    Maximum = 1e5,
                    UseSuperExponentialFormat = true
                });
            plot.Axes.Add(
                new LogarithmicAxis
                {
                    Position = AxisPosition.Left,
                    Title = "Y-axis",
                    Minimum = 1e18,
                    Maximum = 1e38,
                    UseSuperExponentialFormat = true
                });
            OxyAssert.AreEqual(plot, "B05");
        }

        [Test]
        public void C01_DateTimeAxis()
        {
            var plot = new PlotModel { Title = "DateTime axis", PlotMargins = new OxyThickness(100, 40, 20, 100) };
            var xaxis = new DateTimeAxis
            {
                Position = AxisPosition.Bottom,
                Title = "DateTime X",
                IntervalType = DateTimeIntervalType.Days,
                Angle = -46,
                MajorStep = 1
            };
            var yaxis = new DateTimeAxis
            {
                Position = AxisPosition.Left,
                Title = "DateTime Y",
                IntervalType = DateTimeIntervalType.Days,
                Angle = -45,
                MajorStep = 1
            };
            plot.Axes.Add(xaxis);
            plot.Axes.Add(yaxis);

            var ls = new LineSeries();
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 1), new DateTime(2011, 3, 1)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 4), new DateTime(2011, 3, 8)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 6), new DateTime(2011, 3, 12)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 10), new DateTime(2011, 3, 13)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 19), new DateTime(2011, 3, 14)));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "C01");
        }

        [Test]
        public void C02_DateTimeAxis_WithSomeUndefinedPoints()
        {
            var plot = new PlotModel { Title = "DateTime axis", PlotMargins = new OxyThickness(100, 40, 20, 100) };
            var xaxis = new DateTimeAxis
            {
                Position = AxisPosition.Bottom,
                Title = "DateTime X",
                IntervalType = DateTimeIntervalType.Days,
                Angle = -46,
                MajorStep = 1
            };
            var yaxis = new DateTimeAxis
            {
                Position = AxisPosition.Left,
                Title = "DateTime Y",
                IntervalType = DateTimeIntervalType.Days,
                Angle = -45,
                MajorStep = 1
            };
            plot.Axes.Add(xaxis);
            plot.Axes.Add(yaxis);

            var ls = new LineSeries();
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 1), new DateTime(2011, 3, 1)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(double.NaN, new DateTime(2011, 3, 8)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 6), new DateTime(2011, 3, 12)));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 10), double.NaN));
            ls.Points.Add(DateTimeAxis.CreateDataPoint(new DateTime(2011, 1, 19), new DateTime(2011, 3, 14)));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "C02");
        }

        [Test]
        public void C03_DateTimeAxis_WithAllUndefinedPoints()
        {
            var plot = new PlotModel { Title = "DateTime axis", PlotMargins = new OxyThickness(100, 40, 20, 100) };
            var xaxis = new DateTimeAxis
            {
                Position = AxisPosition.Bottom,
                Title = "DateTime X",
                IntervalType = DateTimeIntervalType.Days,
                Angle = -46,
                MajorStep = 1
            };
            var yaxis = new DateTimeAxis
            {
                Position = AxisPosition.Left,
                Title = "DateTime Y",
                IntervalType = DateTimeIntervalType.Days,
                Angle = -45,
                MajorStep = 1
            };
            plot.Axes.Add(xaxis);
            plot.Axes.Add(yaxis);

            var ls = new LineSeries();
            ls.Points.Add(new DataPoint(double.NaN, double.NaN));
            ls.Points.Add(new DataPoint(double.NaN, double.NaN));
            plot.Series.Add(ls);

            OxyAssert.AreEqual(plot, "C03");
        }

        [Test]
        public void D01_InvalidAbsoluteMaxMin()
        {
            var plot = new PlotModel { Title = "Simple plot" };
            plot.Axes.Add(new LinearAxis { AbsoluteMaximum = 0, AbsoluteMinimum = 0 });
            ((IPlotModel)plot).Update(true);
            Assert.IsNotNull(plot.GetLastUpdateException() as InvalidOperationException);
        }

        [Test]
        public void D02_InvalidMaxMin()
        {
            var plot = new PlotModel { Title = "Simple plot" };
            plot.Axes.Add(new LinearAxis { Maximum = 0, Minimum = 0 });
            ((IPlotModel)plot).Update(true);
            Assert.AreEqual(100, plot.Axes[0].ActualMaximum);
            Assert.AreEqual(0, plot.Axes[0].ActualMinimum);
        }

        [Test]
        public void D03_InvalidMaxMin()
        {
            var plot = new PlotModel { Title = "Simple plot" };
            plot.Axes.Add(new LogarithmicAxis { Maximum = 1, Minimum = 1 });
            ((IPlotModel)plot).Update(true);
            Assert.AreEqual(100, plot.Axes[0].ActualMaximum);
            Assert.AreEqual(1, plot.Axes[0].ActualMinimum);
        }

        [Test]
        public void D04_InvalidLogAxis()
        {
            var plot = new PlotModel { Title = "Simple plot" };
            plot.Axes.Add(new LogarithmicAxis { Maximum = 1, Minimum = 0 });
            ((IPlotModel)plot).Update(true);
            Assert.AreEqual(100, plot.Axes[0].ActualMaximum);
            Assert.AreEqual(1, plot.Axes[0].ActualMinimum);
        }
    }
}


text:
package Dlib.Services.Impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import Dlib.DAO.UserDAO;
import Dlib.Models.User;
import Dlib.Services.UserService;
import java.util.List;

/**
 * Default implementation of the {@link UserService} interface.  This service implements
 * operations related to User data.
 */
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;

    public User getCurrentUser() {
        final Long currentUserId = (Long) SecurityUtils.getSubject().getPrincipal();
        if( currentUserId != null ) {
            return getUser(currentUserId);
        } else {
            return null;
        }
    }

    public void createUser(String username, String email, String password) {
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword( new Sha256Hash(password).toHex() );
        userDAO.createUser( user );
    }

    public List<User> getAllUsers() {
        return userDAO.getAllUsers();
    }

    public User getUser(Long userId) {
        return userDAO.getUser(userId);
    }

    public void deleteUser(Long userId) {
        userDAO.deleteUser( userId );
    }

    public void updateUser(User user) {
        userDAO.updateUser( user );
    }

}


text:
/*
 * HTML5 Boilerplate
 *
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 *
 * Detailed information about this CSS: h5bp.com/css
 *
 * ==|== normalize ==========================================================
 */

/* =============================================================================
	 HTML5 display definitions
	 ========================================================================== */

article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; }
audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; }
audio:not([controls]) { display: none; }
[hidden] { display: none; }

/* =============================================================================
	 Base
	 ========================================================================== */

/*
 * 1. Correct text resizing oddly in IE6/7 when body font-size is set using em units
 * 2. Prevent iOS text size adjust on device orientation change, without disabling user zoom: h5bp.com/g
 */

html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }

html, button, input, select, textarea { font-family: sans-serif; color: #222; }

body { margin: 0; font-size: 1em; line-height: 1.4; }

/*
 * Remove text-shadow in selection highlight: h5bp.com/i
 * These selection declarations have to be separate
 * Also: hot pink! (or customize the background color to match your design)
 */

::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; }
::selection { background: #fe57a1; color: #fff; text-shadow: none; }

/* =============================================================================
	 Links
	 ========================================================================== */

a { color: #00e; }
a:visited { color: #551a8b; }
a:hover { color: #06e; }
a:focus { outline: thin dotted; }

/* Improve readability when focused and hovered in all browsers: h5bp.com/h */
a:hover, a:active { outline: 0; }

/* =============================================================================
	 Typography
	 ========================================================================== */

abbr[title] { border-bottom: 1px dotted; }

b, strong { font-weight: bold; }

blockquote { margin: 1em 40px; }

dfn { font-style: italic; }

hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }

ins { background: #ff9; color: #000; text-decoration: none; }

mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; }

/* Redeclare monospace font family: h5bp.com/j */
pre, code, kbd, samp { font-family: monospace, serif; _font-family: 'courier new', monospace; font-size: 1em; }

/* Improve readability of pre-formatted text in all browsers */
pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; }

q { quotes: none; }
q:before, q:after { content: ""; content: none; }

small { font-size: 85%; }

/* Position subscript and superscript content without affecting line-height: h5bp.com/k */
sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }

/* =============================================================================
	 Lists
	 ========================================================================== */

ul, ol { margin: 1em 0; padding: 0 0 0 40px; }
dd { margin: 0 0 0 40px; }
nav ul, nav ol { list-style: none; list-style-image: none; margin: 0; padding: 0; }

/* =============================================================================
	 Embedded content
	 ========================================================================== */

/*
 * 1. Improve image quality when scaled in IE7: h5bp.com/d
 * 2. Remove the gap between images and borders on image containers: h5bp.com/i/440
 */

img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; }

/*
 * Correct overflow not hidden in IE9
 */

svg:not(:root) { overflow: hidden; }

/* =============================================================================
	 Figures
	 ========================================================================== */

figure { margin: 0; }

/* =============================================================================
	 Forms
	 ========================================================================== */

form { margin: 0; }
fieldset { border: 0; margin: 0; padding: 0; }

/* Indicate that 'label' will shift focus to the associated form element */
label { cursor: pointer; }

/*
 * 1. Correct color not inheriting in IE6/7/8/9
 * 2. Correct alignment displayed oddly in IE6/7
 */

legend { border: 0; *margin-left: -7px; padding: 0; white-space: normal; }

/*
 * 1. Correct font-size not inheriting in all browsers
 * 2. Remove margins in FF3/4 S5 Chrome
 * 3. Define consistent vertical alignment display in all browsers
 */

button, input, select, textarea { font-size: 100%; margin: 0; vertical-align: baseline; *vertical-align: middle; }

/*
 * 1. Define line-height as normal to match FF3/4 (set using !important in the UA stylesheet)
 */

button, input { line-height: normal; }

/*
 * 1. Display hand cursor for clickable form elements
 * 2. Allow styling of clickable form elements in iOS
 * 3. Correct inner spacing displayed oddly in IE7 (doesn't effect IE6)
 */

button, input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; *overflow: visible; }

/*
 * Re-set default cursor for disabled elements
 */

button[disabled], input[disabled] { cursor: default; }

/*
 * Consistent box sizing and appearance
 */

input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; *width: 13px; *height: 13px; }
input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; }
input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; }

/*
 * Remove inner padding and border in FF3/4: h5bp.com/l
 */

button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; }

/*
 * 1. Remove default vertical scrollbar in IE6/7/8/9
 * 2. Allow only vertical resizing
 */

textarea { overflow: auto; vertical-align: top; resize: vertical; }

/* Colors for form validity */
input:valid, textarea:valid {  }
input:invalid, textarea:invalid { background-color: #f0dddd; }

/* =============================================================================
	 Tables
	 ========================================================================== */

table { border-collapse: collapse; border-spacing: 0; }
td { vertical-align: top; }

/* =============================================================================
	 Chrome Frame Prompt
	 ========================================================================== */

.chromeframe { margin: 0.2em 0; background: #ccc; color: black; padding: 0.2em 0; }

/* ==|== primary styles =====================================================
	 Author: Display:inline
	 ========================================================================== */

@font-face {
    font-family: 'AeroportalBold';
    src: url('Aeroportal/aeroportal_bold-webfont.eot');
    src: url('Aeroportal/aeroportal_bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('Aeroportal/aeroportal_bold-webfont.woff') format('woff'),
         url('Aeroportal/aeroportal_bold-webfont.ttf') format('truetype'),
         url('Aeroportal/aeroportal_bold-webfont.svg#AeroportalBold') format('svg');
    font-weight: normal;
    font-style: normal;

}
@font-face {
    font-family: 'AeroportalRegular';
    src: url('Aeroportal/aeroportal-webfont.eot');
    src: url('Aeroportal/aeroportal-webfont.eot?#iefix') format('embedded-opentype'),
         url('Aeroportal/aeroportal-webfont.woff') format('woff'),
         url('Aeroportal/aeroportal-webfont.ttf') format('truetype'),
         url('Aeroportal/aeroportal-webfont.svg#AeroportalRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

/* Boiler plate override */
body {
	text-align: center;
	font-size: 0.875em;
	line-height: 1.3em;
}
a, a:visited {
	text-decoration: none;
	color: #2d9ad3;
}
 a:hover {
	text-decoration: underline;
	color: #2d9ad3;
}

/* Typography */
h2 {
	font-weight: normal;
	color: #2d9ad3;
	font-size: 1.7em;
	line-height: 1.2em;
	}
	section + h2 {
		margin-top: 2em;
	}
	h2 span {
		color: #b1b1b9;
	}
	h2 small {
		font-size: 0.5em;
		background: #a8a8a8;
		color: white;
		vertical-align: middle;
		padding: 0.25em 0.5em;
		-webkit-border-radius: 4px;
		-moz-border-radius: 4px;
		border-radius: 4px;
	}
h3 {
	font-family: 'AeroportalBold';
	font-weight: normal;
	font-size: 1.5em;
	line-height: 1em;
	color: #2d9ad3;
	margin: 0 0 0.5em 0;
}
h4 {
	font-family: 'AeroportalBold';
	font-weight: normal;
	font-size: 2.5em;
	line-height: 1em;
	color: #dedee5;
	margin: 1em 0 0.5em 0;
}

/* Positioning styles */
.container {
	width: 960px;
	text-align: left;
	margin: 0 auto;
	position: relative;
	z-index: 1;
}

/* Header */
header {
	background: url(../img/header-bg.jpg) repeat-x;
	height: 810px;
	color: white;
	overflow: hidden;
	}
	header .container {
		height: 810px;
	}

	/* Nav */
	header nav {
		background: black;
		height: 2.9em;
		line-height: 2.9em;
		width: 460px;
		padding: 0 10px;
		-webkit-border-bottom-left-radius: 7px;
		-webkit-border-bottom-right-radius: 7px;
		-moz-border-radius: 0 0 7px 7px;
		border-radius: 0 0 7px 7px;
		}
		.nav-right {
			float: right;
			font-weight: bold;
		}
		header nav a,
		header nav a:visited {
			color: white;
			padding: 0 0.75em;
			-webkit-transition: color 200ms;
			-moz-transition: color 200ms;
			-ms-transition: color 200ms;
			-o-transition: color 200ms;
			transition: color 200ms;
			}
			header nav a:hover {
				color: #949494;
				text-decoration: none;
			}

	/* Logo & title */
	header hgroup {
		position: absolute;
		top: 656px;
		left: 0;
		width: 384px;
		text-align: right;
		font-family: 'AeroportalRegular';
		z-index: 10;
		}
		#logo {
			position: absolute;
			top: -82px;
			left: 100%;
			margin-left: 10px;
			width: 172px;
			height: 189px;
			background: url(../img/sprites.png);
		}
		header h1 {
			position: absolute;
			right: 0;
			bottom: 100%;
			font-size: 5.2em;
			line-height: 1em;
			margin: 0;
			padding-bottom: 2px;
    		font-weight: normal;
		}
		header h2 {
			padding: 10px 8px 0 0;
			color: #2e2e36;
			font-size: 2.5em;
			line-height: 1em;
			margin: 0;
    		font-weight: normal;
		}
		header b {
			font-weight: normal;
			font-family: 'AeroportalBold';
		}

	/* Tagline */
	.tagline {
		position: absolute;
		top: 220px;
		left: 0;
		font-size: 3.5em;
		line-height: 1em;
		font-weight: 100;
		margin: 0;
		}
		.term {
			position: relative;
		}
		.tagline > strong {
			display: block;
			padding-left: 0.5em;
			font-size: 1.5em;
			line-height: 1em;
			font-weight: bold;
		}

	/* Questions */
	#mind {
		position: absolute;
		top: 430px;
		left: 60px;
		width: 360px;
		list-style-type: none;
		margin: 0;
		padding: 0;
		}
		#mind > li {
			float: left;
			position: relative;
			width: 56px;
			height: 56px;
			margin-right: 121px;
			background: white;
			background: -webkit-gradient(linear, left top, left bottom, from(white), to(#e5e5e5));
			background: -webkit-linear-gradient(top, white, #e5e5e5);
			background: -moz-linear-gradient(top, white, #e5e5e5);
			background: -ms-linear-gradient(top, white, #e5e5e5);
			background: -o-linear-gradient(top, white, #e5e5e5);
			background: linear-gradient(top, white, #e5e5e5);
			-webkit-border-radius: 2px;
			-moz-border-radius: 2px;
			border-radius: 2px;
			-webkit-box-shadow: 0 2px 5px black;
			-moz-box-shadow: 0 2px 5px black;
			box-shadow: 0 2px 5px black;
			}
			#mind a {
				display: block;
				margin-right: -120px;
				color: #949494;
				font-size: 0.8em;
				line-height: 1.5em;
				padding: 12px 0 0 68px;
				zoom: 1;
				}
				#mind a:hover {
					text-decoration: none;
				}
				#mind strong {
					color: white;
					font-weight: bold;
					font-size: 1.7em;
				}
			#what-picto {
				display: block;
				position: absolute;
				left: 50%;
				top: 50%;
				width: 19px;
				height: 17px;
				margin: -7px 0 0 -9px;
				background: url(../img/sprites.png) -686px -35px;
			}
			#want-picto {
				display: block;
				position: absolute;
				left: 0;
				right: 0;
				top: 50%;
				font-size: 1.6em;
				line-height: 1em;
				margin-top: -0.5em;
				font-weight: bold;
				color: #2d9ad3;
				text-align: center;
			}

	/* Devices */
	#smartphone {
		position: absolute;
		width: 162px;
		height: 441px;
		background: url(../img/devices.png) -525px 0;
		z-index: 6;
		top: 328px;
		left: 880px;
	}
	#tablet {
		position: absolute;
		width: 526px;
		height: 703px;
		background: url(../img/devices.png);
		z-index: 5;
		top: 50px;
		left: 460px;
	}
	#desktop {
		position: absolute;
		width: 921px;
		height: 703px;
		background: url(../img/devices.png) -687px 0;
		z-index: 4;
		top: -20px;
		left: 640px;
	}

	/* QR-code */
	#qr-code-block {
		display: block;
		position: absolute;
		z-index: 20;
		right: 0;
		bottom: 40px;
		background: #303038;
		padding: 0.8em 1em 0.8em 4.5em;
		color: #858590;
		white-space: nowrap;
		-webkit-border-radius: 6px;
		-moz-border-radius: 6px;
		border-radius: 6px;
		}
		#qr-code-block:hover {
			text-decoration: none;
		}
		#qr-code-block h3 {
			color: white;
			margin: 0;
		}
		#qr-code {
			position: absolute;
			left: 1em;
			top: 1em;
			width: 35px;
			height: 35px;
			background: url(../img/sprites.png) no-repeat -686px 0;
			margin-right: 1em;
		}

/* Main content */
article {
	float: right;
	width: 640px;
	}

	/* Intro */
	.intro {
		font-size: 1.7em;
		line-height: 1.5em;
		color: #9797a2;
		margin-top: 0;
	}
	.intro a {
		background: #2d9ad3;
		padding: 0.25em 0.5em;
		color: white;
		-webkit-border-radius: 6px;
		-moz-border-radius: 6px;
		border-radius: 6px;
		}
		.intro a:hover {
			text-decoration: none;
		}

	/* Nav */
	article nav {
		margin: 2em 0;
		line-height: 2em;
		height: 2em;
		}
		article section + nav {
			margin-top: 3em;
		}
		article nav span,
		article nav a {
			padding: 0 1em;
			float: left;
			}
			article nav span {
				color: #2e2e36;
				font-weight: bold;
			}
			article nav a,
			article nav a:visited {
				color: #b1b1b9;
			}
			article nav span:first-child,
			article nav a:first-child {
				padding-left: 0;
			}
		article nav .nav-right,
		article nav .nav-right:visited {
			float: right;
			background: #a8a8a8;
			color: white;
			-webkit-border-radius: 4px;
			-moz-border-radius: 4px;
			border-radius: 4px;
		}

	/* List */
	.bullets {
		list-style-type: none;
		margin: 0;
		padding: 0;
		}
		.bullets > li {
			padding: 0 0 0 1.3em;
			margin-bottom: 1em;
			position: relative;
			}
			.bullets > li:before {
				display: block;
				position: absolute;
				content: '';
				top: 0.65em;
				left: 0;
				width: 9px;
				height: 9px;
				margin-top: -4px;
				background: url(../img/sprites.png) no-repeat -712px -35px;
			}

	/* Illustrations */
	#responsive,
	#plugins,
	#everything {
		position: relative;
	}
	.illustration {
		display: block;
		position: absolute;
		background: url(../img/sprites.png);
		}
		#responsive {
			padding-left: 166px;
			min-height: 150px;
			}
			#responsive .illustration {
				top: -12px;
				left: 0;
				width: 146px;
				height: 179px;
				background-position: -172px 0;
			}
		#plugins {
			padding-right: 243px;
			min-height: 150px;
			}
			#plugins .illustration {
				top: -6px;
				right: 0;
				width: 223px;
				height: 165px;
				background-position: -318px 0;
			}
		#everything {
			padding-left: 165px;
			min-height: 105px;
			}
			#everything .illustration {
				top: -6px;
				left: 0;
				width: 145px;
				height: 121px;
				background-position: -541px 0;
			}

	/* Screenshots */
	.screenshots {
		margin: 0 0 0 -32px;
		padding: 0;
		list-style-type: none;
		}
		.screenshots > li {
			float: left;
			margin: 0 0 32px 32px;
		}
		.screenshots img {
			-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
			-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
			box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
		}

	/* Version history */
	.version-history {
		margin: 0 0 2em 0;
		padding: 0;
		list-style-type: none;
		}
		.version-history > li {
			margin: 0 0 0.5em 0;
			padding: 0 0 0 4em;
			zoom: 1;
		}
		.version-new,
		.version-fixed,
		.version-upgraded {
			float: left;
			font-size: 0.8em;
			margin-left: -4.9em;
			width: 4.5em;
			color: white;
			text-align: center;
			font-weight: bold;
			text-transform: uppercase;
			-webkit-border-radius: 4px;
			-moz-border-radius: 4px;
			border-radius: 4px;
			}
			.version-new {
				background: #7dc35b;
			}
			.version-fixed {
				background: #e9a130;
			}
			.version-upgraded {
				background: #61b3de;
			}

/* Sidebar */
aside {
	margin-right: 690px;
	color: #858590;
	padding-top: 6px;
	}
	aside > p > a {
		font-weight: bold;
	}

	/* Icon blocks */
	.aside-icon-block {
		padding-left: 62px;
		position: relative;
		margin-bottom: 3em;
		}
		.aside-icon {
			position: absolute;
			left: 0;
			top: 0;
			width: 46px;
			height: 45px;
			background: url(../img/sprites.png);
			}
			#aside-technos .aside-icon {	background-position: -537px -155px;	}
			#aside-features .aside-icon {	background-position: -583px -155px;	}
			#aside-responsive .aside-icon {	background-position: -629px -155px;	}
			#aside-doc .aside-icon {		background-position: -675px -155px;	}
		.aside-icon-block p {
			margin-top: 0;
		}

	/* Bonus */
	#bonus {
		margin: 30px -1px 20px -10px;
		padding: 25px 30px 0 48px;
		height: 115px;
		background: url(../img/sprites.png) no-repeat -721px 0;
		}
		#bonus h4 {
			margin: 0 0 7px;
		}
		#bonus p {
			margin: 0;
		}

/* ==|== non-semantic helper classes ========================================
	 Please define your styles before this section.
	 ========================================================================== */

/* For image replacement */
.ir { display: block; border: 0; text-indent: -999em; overflow: hidden; background-color: transparent; background-repeat: no-repeat; text-align: left; direction: ltr; *line-height: 0; }
.ir br { display: none; }

/* Hide from both screenreaders and browsers: h5bp.com/u */
.hidden { display: none !important; visibility: hidden; }

/* Hide only visually, but have it available for screenreaders: h5bp.com/v */
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }

/* Extends the .visuallyhidden class to allow the element to be focusable when navigated to via the keyboard: h5bp.com/p */
.visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; }

/* Hide visually and from screenreaders, but maintain layout */
.invisible { visibility: hidden; }

/* Contain floats: h5bp.com/q */
.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }

/* ==|== print styles =======================================================
	 Print styles.
	 Inlined to avoid required HTTP connection: h5bp.com/r
	 ========================================================================== */

@media print {
	* { background: transparent !important; color: black !important; box-shadow:none !important; text-shadow: none !important; filter:none !important; -ms-filter: none !important; } /* Black prints faster: h5bp.com/s */
	a, a:visited { text-decoration: underline; }
	a[href]:after { content: " (" attr(href) ")"; }
	abbr[title]:after { content: " (" attr(title) ")"; }
	.ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }  /* Don't show links for images, or javascript/internal links */
	pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
	thead { display: table-header-group; } /* h5bp.com/t */
	tr, img { page-break-inside: avoid; }
	img { max-width: 100% !important; }
	@page { margin: 0.5cm; }
	p, h2, h3 { orphans: 3; widows: 3; }
	h2, h3 { page-break-after: avoid; }
}


text:
layout: post
title: "Calling pip programmatically"
date: 2013-08-22 17:45
disqus: y
categories: python
---
I was trying to find an API for [pip](http://www.pip-installer.org/) but I wasn't able to find a one. So started to look at the code and I realised that I could just emulate what the pip command was doing. It turned out to be really easy.

{% highlight python %}

import pip

pip.main(['install', 'django'])

{% endhighlight %}

This is equivalent to

{% highlight bash %}
pip install django
{% endhighlight %}

That was easy!


text:
using System;
using Metrolib.Geography;

// ReSharper disable CheckNamespace

namespace GeoVis
// ReSharper restore CheckNamespace
{
	/// <summary>
	///     Represents an axis aligned rectangle in mercator space.
	/// </summary>
	public struct MercatorRectangle : IEquatable<MercatorRectangle>
	{
		/// <summary>
		///     The greatest rectangle which can be displayed with this map.
		/// </summary>
		public static readonly MercatorRectangle Earth;

		/// <summary>
		/// </summary>
		public MercatorLocation Max;

		/// <summary>
		/// </summary>
		public MercatorLocation Min;

		static MercatorRectangle()
		{
			Earth = new MercatorRectangle
			{
				Min = MercatorLocation.Min,
				Max = MercatorLocation.Max
			};
		}

		/// <summary>
		///     Width of this rectangle.
		/// </summary>
		public double Width => Max.X - Min.X;

		/// <summary>
		///     Height of this rectangle.
		/// </summary>
		public double Height => Max.Y - Min.Y;

		/// <summary>
		///     Tests if this rectangle equals the given one.
		/// </summary>
		/// <param name="other"></param>
		/// <returns></returns>
		public bool Equals(MercatorRectangle other)
		{
			return Min.Equals(other.Min) && Max.Equals(other.Max);
		}

		/// <summary>
		///     Returns a string that represents the current object.
		/// </summary>
		/// <returns></returns>
		public override string ToString()
		{
			return string.Format("Min: {0}, Max: {1}", Min, Max);
		}

		/// <summary>
		///     Indicates whether this instance and a specified object are equal.
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public override bool Equals(object obj)
		{
			if (ReferenceEquals(objA: null, objB: obj)) return false;
			return obj is MercatorRectangle && Equals((MercatorRectangle) obj);
		}

		/// <summary>
		///     Returns the hash code for this instance.
		/// </summary>
		/// <returns></returns>
		public override int GetHashCode()
		{
			unchecked
			{
				return (Min.GetHashCode() * 397) ^ Max.GetHashCode();
			}
		}

		/// <summary>
		///     Tests the two given rectangles for equality.
		/// </summary>
		/// <param name="left"></param>
		/// <param name="right"></param>
		/// <returns></returns>
		public static bool operator ==(MercatorRectangle left, MercatorRectangle right)
		{
			return left.Equals(right);
		}

		/// <summary>
		///     Tests the two given rectangles for inequality.
		/// </summary>
		/// <param name="left"></param>
		/// <param name="right"></param>
		/// <returns></returns>
		public static bool operator !=(MercatorRectangle left, MercatorRectangle right)
		{
			return !left.Equals(right);
		}

		/// <summary>
		///     Creates a new rectangle from the given values.
		/// </summary>
		/// <param name="minX"></param>
		/// <param name="maxY"></param>
		/// <param name="maxX"></param>
		/// <param name="minY"></param>
		/// <returns></returns>
		public static MercatorRectangle FromMinMax(double minX, double maxY, double maxX, double minY)
		{
			return new MercatorRectangle
			{
				Min = new MercatorLocation(minX, minY),
				Max = new MercatorLocation(maxX, maxY)
			};
		}
	}
}


text:
'use strict';

const config     = require('config');
const path       = require('path');
const express    = require('express');
const fs         = require('fs');
const favicon    = require('serve-favicon');
const RouteUtils = require('../utils/route_utils');
const api        = require('../api');

const enforceSSL = RouteUtils.enforceSSL({ port: config.server.ssl.port });

function serveBundledView(view, page, bundleMappingsPath) {
  return function(req, res, next) {
    fs.readFileAsync(bundleMappingsPath)
    .then(JSON.parse)
    .then(function(mappings) {
      res.render(view, {
        settings : config.app[page],
        scripts  : {
          commons : mappings.commons.js,
          app     : mappings[page].js
        }
      });
    })
    .catch(next);
  };
}

module.exports = function(app) {

  if (config.app.favicon) {
    app.use(favicon(path.join(__dirname, config.app.favicon)));
  } else {
    app.use('favicon.ico', function(req, res) {
      res.status(200);
      res.type('image/x-icon');
    });
  }

  // Secured content
  app.use(config.app.dashboard.base, enforceSSL);

  // Serve assets
  app.use('/', express.static(config.app.assets.path, {
    etag   : true,
    maxage : config.app.assets.maxAge,
    index  : false
  }));

  app.use('/dashboard', serveBundledView('index', 'dashboard', config.app.assets.mappings));
  app.use('/web',       serveBundledView('index', 'web',       config.app.assets.mappings));

  // URL rewrite for non-HTML5 browsers
  // Just send the index.html for other files to support HTML5Mode
  // app.all(config.app.dashboard.base + '*', function(req, res, next) {
  //   res.sendFile(config.app.dashboard.index, { root: path.join(__dirname, config.app.dashboard.root) });
  // });

  // app.all(config.app.web.base + '*', function(req, res, next) {
  //   res.sendFile(config.app.web.index, { root: path.join(__dirname, config.app.web.root) });
  // });

  // API
  app.use(config.app.api.base, api());

};


text:
//------------------------------------------------------------------------------
//  ntransformnode_main.cc
//  (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "scene/ntransformnode.h"
#include "scene/nsceneserver.h"
#include "gfx2/ngfxserver2.h"
#include "scene/nanimator.h"
#include <Data/BinaryReader.h>

nNebulaClass(nTransformNode, "nscenenode");

bool nTransformNode::LoadDataBlock(nFourCC FourCC, Data::CBinaryReader& DataReader)
{
	switch (FourCC)
	{
		case 'WVCL': // LCVW
		{
			SetLockViewer(DataReader.Read<bool>());
			OK;
		}
		case 'LCSS': // SSCL
		{
			SetScale(DataReader.Read<vector3>());
			OK;
		}
		case 'TORS': // SROT
		{
			SetQuat(DataReader.Read<quaternion>());
			OK;
		}
		case 'SOPS': // SPOS
		{
			SetPosition(DataReader.Read<vector3>());
			OK;
		}
		case 'TVPR': // RPVT
		{
			SetRotatePivot(DataReader.Read<vector3>());
			OK;
		}
		case 'TVPS': // SPVT
		{
			SetScalePivot(DataReader.Read<vector3>());
			OK;
		}
		default: return nSceneNode::LoadDataBlock(FourCC, DataReader);
	}
}
//---------------------------------------------------------------------

//------------------------------------------------------------------------------
/**
    Attach to the scene server.
*/
void
nTransformNode::Attach(nSceneServer* sceneServer, nRenderContext* renderContext)
{
    n_assert(sceneServer);
    if (this->CheckFlags(Active))
    {
        sceneServer->BeginGroup(this, renderContext);
        nSceneNode::Attach(sceneServer, renderContext);
        sceneServer->EndGroup();
    }
}

//------------------------------------------------------------------------------
/**
    Indicate to scene server that we provide transformation.
*/
bool
nTransformNode::HasTransform() const
{
    return true;
}

//------------------------------------------------------------------------------
/**
    Compute the resulting modelview matrix and set it in the scene
    server as current modelview matrix.
*/
bool
nTransformNode::RenderTransform(nSceneServer* sceneServer,
                                nRenderContext* renderContext,
                                const matrix44& parentMatrix)
{
    n_assert(sceneServer);
    n_assert(renderContext);

    this->InvokeAnimators(nAnimator::Transform, renderContext);
    if (this->GetLockViewer())
    {
        // handle lock to viewer
        const matrix44& viewMatrix = nGfxServer2::Instance()->GetTransform(nGfxServer2::InvView);
        matrix44 m = this->tform.getmatrix();
        m = m * parentMatrix;
        m.M41 = viewMatrix.M41;
        m.M42 = viewMatrix.M42;
        m.M43 = viewMatrix.M43;
        sceneServer->SetModelTransform(m);
    }
    else
    {
        // default case
        sceneServer->SetModelTransform(this->tform.getmatrix() * parentMatrix);
    }
    return true;
}