text:
#include <new>

#include "../include/zmq.h"

#include "pipe.hpp"
#include "likely.hpp"

zmq::reader_t::reader_t (object_t *parent_, pipe_t *pipe_,
      uint64_t lwm_) :
    object_t (parent_),
    active (true),
    pipe (pipe_),
    writer (NULL),
    lwm (lwm_),
    msgs_read (0),
    sink (NULL),
    terminating (false)
{
    //  Note that writer is not set here. Writer will inform reader about its
    //  address once it is created (via set_writer method).
}

void zmq::reader_t::set_writer (writer_t *writer_)
{
    zmq_assert (!writer);
    writer = writer_;
}

zmq::reader_t::~reader_t ()
{
    //  Pipe as such is owned and deallocated by reader object.
    //  The point is that reader processes the last step of terminal
    //  handshaking (term_ack).
    zmq_assert (pipe);

    //  First delete all the unread messages in the pipe. We have to do it by
    //  hand because zmq_msg_t is a POD, not a class, so there's no associated
    //  destructor.
    zmq_msg_t msg;
    while (pipe->read (&msg))
       zmq_msg_close (&msg);

    delete pipe;
}

void zmq::reader_t::set_event_sink (i_reader_events *sink_)
{
    zmq_assert (!sink);
    sink = sink_;
}

bool zmq::reader_t::is_delimiter (zmq_msg_t &msg_)
{
    unsigned char *offset = 0;

    return msg_.content == (void*) (offset + ZMQ_DELIMITER);
}

bool zmq::reader_t::check_read ()
{
    if (!active)
        return false;

    //  Check if there's an item in the pipe.
    if (!pipe->check_read ()) {
        active = false;
        return false;
    }

    //  If the next item in the pipe is message delimiter,
    //  initiate its termination.
    if (pipe->probe (is_delimiter)) {
        zmq_msg_t msg;
        bool ok = pipe->read (&msg);
        zmq_assert (ok);
        if (sink)
            sink->delimited (this);
        terminate ();
        return false;
    }

    return true;
}

bool zmq::reader_t::read (zmq_msg_t *msg_)
{
    if (!active)
        return false;

    if (!pipe->read (msg_)) {
        active = false;
        return false;
    }

    //  If delimiter was read, start termination process of the pipe.
    unsigned char *offset = 0;
    if (msg_->content == (void*) (offset + ZMQ_DELIMITER)) {
        if (sink)
            sink->delimited (this);
        terminate ();
        return false;
    }

    if (!(msg_->flags & ZMQ_MSG_MORE))
        msgs_read++;

    if (lwm > 0 && msgs_read % lwm == 0)
        send_activate_writer (writer, msgs_read);

    return true;
}

void zmq::reader_t::terminate ()
{
    //  If termination was already started by the peer, do nothing.
    if (terminating)
        return;

    active = false;
    terminating = true;
    send_pipe_term (writer);
}

void zmq::reader_t::process_activate_reader ()
{
    //  Forward the event to the sink (either socket or session).
    active = true;
    sink->activated (this);
}

void zmq::reader_t::process_pipe_term_ack ()
{
    //  At this point writer may already be deallocated.
    //  For safety's sake drop the reference to it.
    writer = NULL;

    //  Notify owner about the termination.
    zmq_assert (sink);
    sink->terminated (this);

    //  Deallocate resources.
    delete this;
}

zmq::writer_t::writer_t (object_t *parent_, pipe_t *pipe_, reader_t *reader_,
      uint64_t hwm_, int64_t swap_size_) :
    object_t (parent_),
    active (true),
    pipe (pipe_),
    reader (reader_),
    hwm (hwm_),
    msgs_read (0),
    msgs_written (0),
    swap (NULL),
    sink (NULL),
    swapping (false),
    pending_delimiter (false),
    terminating (false)
{
    //  Inform reader about the writer.
    reader->set_writer (this);

    //  Open the swap file, if required.
    if (swap_size_ > 0) {
        swap = new (std::nothrow) swap_t (swap_size_);
        alloc_assert (swap);
        int rc = swap->init ();
        zmq_assert (rc == 0);
    }
}

zmq::writer_t::~writer_t ()
{
    if (swap)
       delete swap;
}

void zmq::writer_t::set_event_sink (i_writer_events *sink_)
{
    zmq_assert (!sink);
    sink = sink_;
}

bool zmq::writer_t::check_write (zmq_msg_t *msg_)
{
    //  We've already checked and there's no space free for the new message.
    //  There's no point in checking once again.
    if (unlikely (!active))
        return false;

    if (unlikely (swapping)) {
        if (unlikely (!swap->fits (msg_))) {
            active = false;
            return false;
        }
    }
    else {
        if (unlikely (pipe_full ())) {
            if (swap)
                swapping = true;
            else {
                active = false;
                return false;
            }
        }
    }

    return true;
}

bool zmq::writer_t::write (zmq_msg_t *msg_)
{
    if (unlikely (!check_write (msg_)))
        return false;

    if (unlikely (swapping)) {
        bool stored = swap->store (msg_);
        zmq_assert (stored);
        if (!(msg_->flags & ZMQ_MSG_MORE))
            swap->commit ();
        return true;
    }

    pipe->write (*msg_, msg_->flags & ZMQ_MSG_MORE);
    if (!(msg_->flags & ZMQ_MSG_MORE))
        msgs_written++;

    return true;
}

void zmq::writer_t::rollback ()
{
    //  Remove incomplete message from the swap.
    if (unlikely (swapping)) {
        swap->rollback ();
        return;
    }

    //  Remove incomplete message from the pipe.
    zmq_msg_t msg;
    while (pipe->unwrite (&msg)) {
        zmq_assert (msg.flags & ZMQ_MSG_MORE);
        zmq_msg_close (&msg);
    }
}

void zmq::writer_t::flush ()
{
    //  In the swapping mode, flushing is automatically handled by swap object.
    if (!swapping && !pipe->flush ())
        send_activate_reader (reader);
}

void zmq::writer_t::terminate ()
{
    //  Prevent double termination.
    if (terminating)
        return;
    terminating = true;

    //  Mark the pipe as not available for writing.
    active = false;

    //  Rollback any unfinished messages.
    rollback ();

    if (swapping) {
        pending_delimiter = true;
        return;
    }

    //  Push delimiter into the pipe. Trick the compiler to belive that
    //  the tag is a valid pointer. Note that watermarks are not checked
    //  thus the delimiter can be written even though the pipe is full.
    zmq_msg_t msg;
    const unsigned char *offset = 0;
    msg.content = (void*) (offset + ZMQ_DELIMITER);
    msg.flags = 0;
    pipe->write (msg, false);
    flush ();
}

void zmq::writer_t::process_activate_writer (uint64_t msgs_read_)
{
    //  Store the reader's message sequence number.
    msgs_read = msgs_read_;

    //  If we are in the swapping mode, we have some messages in the swap.
    //  Given that pipe is now ready for writing we can move part of the
    //  swap into the pipe.
    if (swapping) {
        zmq_msg_t msg;
        while (!pipe_full () && !swap->empty ()) {
            swap->fetch(&msg);
            pipe->write (msg, msg.flags & ZMQ_MSG_MORE);
            if (!(msg.flags & ZMQ_MSG_MORE))
                msgs_written++;
        }
        if (!pipe->flush ())
            send_activate_reader (reader);

        //  There are no more messages in the swap. We can switch into
        //  standard in-memory mode.
        if (swap->empty ()) {
            swapping = false;

            //  Push delimiter into the pipe. Trick the compiler to belive that
            //  the tag is a valid pointer. Note that watermarks are not checked
            //  thus the delimiter can be written even though the pipe is full.
            if (pending_delimiter) {
                zmq_msg_t msg;
                const unsigned char *offset = 0;
                msg.content = (void*) (offset + ZMQ_DELIMITER);
                msg.flags = 0;
                pipe->write (msg, false);
                flush ();
                return;
            }
        }
    }

    //  If the writer was non-active before, let's make it active
    //  (available for writing messages to).
    if (!active && !terminating) {
        active = true;
        zmq_assert (sink);
        sink->activated (this);
    }
}

void zmq::writer_t::process_pipe_term ()
{
    send_pipe_term_ack (reader);

    //  The above command allows reader to deallocate itself and the pipe.
    //  For safety's sake we'll drop the pointers here.
    reader = NULL;
    pipe = NULL;

    //  Notify owner about the termination.
    zmq_assert (sink);
    sink->terminated (this);

    //  Deallocate the resources.
    delete this;
}

bool zmq::writer_t::pipe_full ()
{
    return hwm > 0 && msgs_written - msgs_read == hwm;
}

void zmq::create_pipe (object_t *reader_parent_, object_t *writer_parent_,
    uint64_t hwm_, int64_t swap_size_, reader_t **reader_, writer_t **writer_)
{
    //  First compute the low water mark. Following point should be taken
    //  into consideration:
    //
    //  1. LWM has to be less than HWM.
    //  2. LWM cannot be set to very low value (such as zero) as after filling
    //     the queue it would start to refill only after all the messages are
    //     read from it and thus unnecessarily hold the progress back.
    //  3. LWM cannot be set to very high value (such as HWM-1) as it would
    //     result in lock-step filling of the queue - if a single message is
    //     read from a full queue, writer thread is resumed to write exactly one
    //     message to the queue and go back to sleep immediately. This would
    //     result in low performance.
    //
    //  Given the 3. it would be good to keep HWM and LWM as far apart as
    //  possible to reduce the thread switching overhead to almost zero,
    //  say HWM-LWM should be max_wm_delta.
    //
    //  That done, we still we have to account for the cases where
    //  HWM < max_wm_delta thus driving LWM to negative numbers.
    //  Let's make LWM 1/2 of HWM in such cases.
    uint64_t lwm = (hwm_ > max_wm_delta * 2) ?
        hwm_ - max_wm_delta : (hwm_ + 1) / 2;

    //  Create all three objects pipe consists of: the pipe per se, reader and
    //  writer. The pipe will be handled by reader and writer, its never passed
    //  to the user. Reader and writer are returned to the user.
    pipe_t *pipe = new (std::nothrow) pipe_t ();
    alloc_assert (pipe);
    *reader_ = new (std::nothrow) reader_t (reader_parent_, pipe, lwm);
    alloc_assert (*reader_);
    *writer_ = new (std::nothrow) writer_t (writer_parent_, pipe, *reader_,
        hwm_, swap_size_);
    alloc_assert (*writer_);
}


text:
layout: post
title: ! 'Java aktuell: der iJUG Newsletter'
date: 2010-07-14 16:32:43.000000000 +02:00
categories: article
tags:
- Newsletter
- iJUG
status: publish
type: post
published: true
meta:
  _edit_last: '3'
  _wp_old_slug: ''
author: uwe
---

Hier nun wieder der aktuelle Newsletter der iJUG. Ein paar Highlights aus den Themen:

DOAG Konferenz

Java Forum Stuttgart

Eclipse Helios

NetBeans 3.9

Link zur HTML-Version.

redpajama_set_name: RedPajamaGithub


text:
package dev.wonderland.gameDev;

import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import dev.wonderland.gameDev.display.Display;
import dev.wonderland.gameDev.gfx.Assets;
import dev.wonderland.gameDev.gfx.GameCamera;
import dev.wonderland.gameDev.input.KeyManager;
import dev.wonderland.gameDev.states.GameState;
import dev.wonderland.gameDev.states.State;

public class Game implements Runnable {

	private Display display;
	private int width, height;
	public String title;

	private boolean running = false;
	private Thread thread;

	private BufferStrategy bs;
	private Graphics g;

	//States
	private State gameState;

	//Input
	private KeyManager keyManager;

	//Camera
	private GameCamera gameCamera;

	//Handler
	private Handler handler;

	public Game(String title, int width, int height){
		this.width = width;
		this.height = height;
		this.title = title;
		keyManager = new KeyManager();
	}

	private void init(){
		display = new Display(title, width, height);
		display.getFrame().addKeyListener(keyManager);
		Assets.init();

		gameCamera = new GameCamera(this, 0, 0);
		handler = new Handler(this);

		gameState = new GameState(handler);
		State.setState(gameState);
	}

	private void tick(){
		keyManager.tick();

		if(State.getState() != null)
			State.getState().tick();
	}

	private void render(){
		bs = display.getCanvas().getBufferStrategy();
		if(bs == null){
			display.getCanvas().createBufferStrategy(3);
			return;
		}
		g = bs.getDrawGraphics();
		//Clear Screen
		g.clearRect(0, 0, width, height);
		//Draw Here!

		if(State.getState() != null)
			State.getState().render(g);

		//End Drawing!
		bs.show();
		g.dispose();
	}

	public void run(){

		init();

		int fps = 60;
		double timePerTick = 1000000000 / fps;
		double delta = 0;
		long now;
		long lastTime = System.nanoTime();
		long timer = 0;
		while(running){
			now = System.nanoTime();
			delta += (now - lastTime) / timePerTick;
			timer += now - lastTime;
			lastTime = now;

			if(delta >= 1){
				tick();
				delta--;
			}

			if(timer >= 1000000000){
				timer = 0;
			}

			render();
		}
		stop();
	}

	public KeyManager getKeyManager(){
		return keyManager;
	}

	public GameCamera getGameCamera(){
		return gameCamera;
	}

	public int getWidth(){
		return width;
	}

	public int getHeight(){
		return height;
	}

	public synchronized void start(){
		if(running)
			return;
		running = true;
		thread = new Thread(this);
		thread.start();
	}

	public synchronized void stop(){
		if(!running)
			return;
		running = false;
		try {
			thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


text:
CPack External Generator
------------------------

CPack provides many generators to create packages for a variety of platforms
and packaging systems. The intention is for CMake/CPack to be a complete
end-to-end solution for building and packaging a software project. However, it
may not always be possible to use CPack for the entire packaging process, due
to either technical limitations or policies that require the use of certain
tools. For this reason, CPack provides the "External" generator, which allows
external packaging software to take advantage of some of the functionality
provided by CPack, such as component installation and the dependency graph.

Integration with External Packaging Tools
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The CPack External generator generates a ``.json`` file containing the
CPack internal metadata, which gives external software information
on how to package the software. External packaging software may itself
invoke CPack, consume the generated metadata,
install and package files as required.

Alternatively CPack can invoke an external packaging software
through an optional custom CMake script in
:variable:`CPACK_EXTERNAL_PACKAGE_SCRIPT` instead.

Staging of installation files may also optionally be
taken care of by the generator when enabled through the
:variable:`CPACK_EXTERNAL_ENABLE_STAGING` variable.

JSON Format
^^^^^^^^^^^

The JSON metadata file contains a list of CPack components and component groups,
the various options passed to :command:`cpack_add_component` and
:command:`cpack_add_component_group`, the dependencies between the components
and component groups, and various other options passed to CPack.

The JSON's root object will always provide two fields:
``formatVersionMajor`` and ``formatVersionMinor``, which are always integers
that describe the output format of the generator. Backwards-compatible changes
to the output format (for example, adding a new field that didn't exist before)
cause the minor version to be incremented, and backwards-incompatible changes
(for example, deleting a field or changing its meaning) cause the major version
to be incremented and the minor version reset to 0. The format version is
always of the format ``major.minor``. In other words, it always has exactly two
parts, separated by a period.

You can request one or more specific versions of the output format as described
below with :variable:`CPACK_EXTERNAL_REQUESTED_VERSIONS`. The output format will
have a major version that exactly matches the requested major version, and a
minor version that is greater than or equal to the requested minor version. If
no version is requested with :variable:`CPACK_EXTERNAL_REQUESTED_VERSIONS`, the
latest known major version is used by default. Currently, the only supported
format is 1.0, which is described below.

Version 1.0
***********

In addition to the standard format fields, format version 1.0 provides the
following fields in the root:

``components``
  The ``components`` field is an object with component names as the keys and
  objects describing the components as the values. The component objects have
  the following fields:

  ``name``
    The name of the component. This is always the same as the key in the
    ``components`` object.

  ``displayName``
    The value of the ``DISPLAY_NAME`` field passed to
    :command:`cpack_add_component`.

  ``description``
    The value of the ``DESCRIPTION`` field passed to
    :command:`cpack_add_component`.

  ``isHidden``
    True if ``HIDDEN`` was passed to :command:`cpack_add_component`, false if
    it was not.

  ``isRequired``
    True if ``REQUIRED`` was passed to :command:`cpack_add_component`, false if
    it was not.

  ``isDisabledByDefault``
    True if ``DISABLED`` was passed to :command:`cpack_add_component`, false if
    it was not.

  ``group``
    Only present if ``GROUP`` was passed to :command:`cpack_add_component`. If
    so, this field is a string value containing the component's group.

  ``dependencies``
    An array of components the component depends on. This contains the values
    in the ``DEPENDS`` argument passed to :command:`cpack_add_component`. If no
    ``DEPENDS`` argument was passed, this is an empty list.

  ``installationTypes``
    An array of installation types the component is part of. This contains the
    values in the ``INSTALL_TYPES`` argument passed to
    :command:`cpack_add_component`. If no ``INSTALL_TYPES`` argument was
    passed, this is an empty list.

  ``isDownloaded``
    True if ``DOWNLOADED`` was passed to :command:`cpack_add_component`, false
    if it was not.

  ``archiveFile``
    The name of the archive file passed with the ``ARCHIVE_FILE`` argument to
    :command:`cpack_add_component`. If no ``ARCHIVE_FILE`` argument was passed,
    this is an empty string.

``componentGroups``
  The ``componentGroups`` field is an object with component group names as the
  keys and objects describing the component groups as the values. The component
  group objects have the following fields:

  ``name``
    The name of the component group. This is always the same as the key in the
    ``componentGroups`` object.

  ``displayName``
    The value of the ``DISPLAY_NAME`` field passed to
    :command:`cpack_add_component_group`.

  ``description``
    The value of the ``DESCRIPTION`` field passed to
    :command:`cpack_add_component_group`.

  ``parentGroup``
    Only present if ``PARENT_GROUP`` was passed to
    :command:`cpack_add_component_group`. If so, this field is a string value
    containing the component group's parent group.

  ``isExpandedByDefault``
    True if ``EXPANDED`` was passed to :command:`cpack_add_component_group`,
    false if it was not.

  ``isBold``
    True if ``BOLD_TITLE`` was passed to :command:`cpack_add_component_group`,
    false if it was not.

  ``components``
    An array of names of components that are direct members of the group
    (components that have this group as their ``GROUP``). Components of
    subgroups are not included.

  ``subgroups``
    An array of names of component groups that are subgroups of the group
    (groups that have this group as their ``PARENT_GROUP``).

``installationTypes``
  The ``installationTypes`` field is an object with installation type names as
  the keys and objects describing the installation types as the values. The
  installation type objects have the following fields:

  ``name``
    The name of the installation type. This is always the same as the key in
    the ``installationTypes`` object.

  ``displayName``
    The value of the ``DISPLAY_NAME`` field passed to
    :command:`cpack_add_install_type`.

  ``index``
    The integer index of the installation type in the list.

``projects``
  The ``projects`` field is an array of objects describing CMake projects which
  comprise the CPack project. The values in this field are derived from
  :variable:`CPACK_INSTALL_CMAKE_PROJECTS`. In most cases, this will be only a
  single project. The project objects have the following fields:

  ``projectName``
    The project name passed to :variable:`CPACK_INSTALL_CMAKE_PROJECTS`.

  ``component``
    The name of the component or component set which comprises the project.

  ``directory``
    The build directory of the CMake project. This is the directory which
    contains the ``cmake_install.cmake`` script.

  ``subDirectory``
    The subdirectory to install the project into inside the CPack package.

``packageName``
  The package name given in :variable:`CPACK_PACKAGE_NAME`. Only present if
  this option is set.

``packageVersion``
  The package version given in :variable:`CPACK_PACKAGE_VERSION`. Only present
  if this option is set.

``packageDescriptionFile``
  The package description file given in
  :variable:`CPACK_PACKAGE_DESCRIPTION_FILE`. Only present if this option is
  set.

``packageDescriptionSummary``
  The package description summary given in
  :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`. Only present if this option is
  set.

``buildConfig``
  The build configuration given to CPack with the ``-C`` option. Only present
  if this option is set.

``defaultDirectoryPermissions``
  The default directory permissions given in
  :variable:`CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS`. Only present if this
  option is set.

``setDestdir``
  True if :variable:`CPACK_SET_DESTDIR` is true, false if it is not.

``packagingInstallPrefix``
  The install prefix given in :variable:`CPACK_PACKAGING_INSTALL_PREFIX`. Only
  present if :variable:`CPACK_SET_DESTDIR` is true.

``stripFiles``
  True if :variable:`CPACK_STRIP_FILES` is true, false if it is not.

``warnOnAbsoluteInstallDestination``
  True if :variable:`CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION` is true, false
  if it is not.

``errorOnAbsoluteInstallDestination``
  True if :variable:`CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION` is true,
  false if it is not.

Variables specific to CPack External generator
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. variable:: CPACK_EXTERNAL_REQUESTED_VERSIONS

  This variable is used to request a specific version of the CPack External
  generator. It is a list of ``major.minor`` values, separated by semicolons.

  If this variable is set to a non-empty value, the CPack External generator
  will iterate through each item in the list to search for a version that it
  knows how to generate. Requested versions should be listed in order of
  descending preference by the client software, as the first matching version
  in the list will be generated.

  The generator knows how to generate the version if it has a versioned
  generator whose major version exactly matches the requested major version,
  and whose minor version is greater than or equal to the requested minor
  version. For example, if ``CPACK_EXTERNAL_REQUESTED_VERSIONS`` contains 1.0, and
  the CPack External generator knows how to generate 1.1, it will generate 1.1.
  If the generator doesn't know how to generate a version in the list, it skips
  the version and looks at the next one. If it doesn't know how to generate any
  of the requested versions, an error is thrown.

  If this variable is not set, or is empty, the CPack External generator will
  generate the highest major and minor version that it knows how to generate.

  If an invalid version is encountered in ``CPACK_EXTERNAL_REQUESTED_VERSIONS`` (one
  that doesn't match ``major.minor``, where ``major`` and ``minor`` are
  integers), it is ignored.

.. variable:: CPACK_EXTERNAL_ENABLE_STAGING

  This variable can be set to true to enable optional installation
  into a temporary staging area which can then be picked up
  and packaged by an external packaging tool.
  The top level directory used by CPack for the current packaging
  task is contained in ``CPACK_TOPLEVEL_DIRECTORY``.
  It is automatically cleaned up on each run before packaging is initiated
  and can be used for custom temporary files required by
  the external packaging tool.
  It also contains the staging area ``CPACK_TEMPORARY_DIRECTORY``
  into which CPack performs the installation when staging is enabled.

.. variable:: CPACK_EXTERNAL_PACKAGE_SCRIPT

  This variable can optionally specify the full path to
  a CMake script file to be run as part of the CPack invocation.
  It is invoked after (optional) staging took place and may
  run an external packaging tool. The script has access to
  the variables defined by the CPack config file.


text:
<?php

namespace App\Controllers\Front\Account;

use App\Controllers\Controller;

class Logout extends Controller {

    public function index() {
        if (Customer::isLogged()) {

            $customer_id = Customer::getId();

            Customer::logout();
            Cart::clear();

            unset(Session::p()->data['wishlist']);
            unset(Session::p()->data['shipping_address_id']);
            unset(Session::p()->data['shipping_country_id']);
            unset(Session::p()->data['shipping_zone_id']);
            unset(Session::p()->data['shipping_postcode']);
            unset(Session::p()->data['shipping_method']);
            unset(Session::p()->data['shipping_methods']);
            unset(Session::p()->data['payment_address_id']);
            unset(Session::p()->data['payment_country_id']);
            unset(Session::p()->data['payment_zone_id']);
            unset(Session::p()->data['payment_method']);
            unset(Session::p()->data['payment_methods']);
            unset(Session::p()->data['comment']);
            unset(Session::p()->data['order_id']);
            unset(Session::p()->data['coupon']);
            unset(Session::p()->data['reward']);
            unset(Session::p()->data['gift_card']);
            unset(Session::p()->data['gift_cards']);

            Theme::trigger('front_customer_logout', array('customer_id' => $customer_id));
        }

        $data = Theme::language('account/logout');

        Theme::setTitle(Lang::get('lang_heading_title'));

        if (Customer::isLogged()):
            Breadcrumb::add('lang_text_account', 'account/dashboard', null, true, 'SSL');
        endif;

        Breadcrumb::add('lang_text_logout', 'account/logout', null, true, 'SSL');

        if (Theme::getstyle() == 'content'):
            $route = 'content/home';
        else:
            $route = 'shop/home';
        endif;

        $data['continue']     = Url::link($route);
        $data['text_message'] = Lang::get('lang_text_message');

        $data = Theme::listen(__CLASS__, __FUNCTION__, $data);

        $data = Theme::renderControllers($data);

        Response::setOutput(View::make('common/success', $data));
    }
}


text:
from pants.subsystem.subsystem import Subsystem
from pants.testutil.option.fakes import create_options_for_optionables

def global_subsystem_instance(subsystem_type, options=None):
    """Returns the global instance of a subsystem, for use in tests.

    :API: public

    :param type subsystem_type: The subclass of :class:`pants.subsystem.subsystem.Subsystem`
                                to create.
    :param options: dict of scope -> (dict of option name -> value).
                    The scopes may be that of the global instance of the subsystem (i.e.,
                    subsystem_type.options_scope) and/or the scopes of instances of the
                    subsystems it transitively depends on.
    """
    init_subsystem(subsystem_type, options)
    return subsystem_type.global_instance()

def init_subsystems(subsystem_types, options=None):
    """Initialize subsystems for use in tests.

    Does not create an instance.  This function is for setting up subsystems that the code
    under test creates.

    Note that there is some redundancy between this function and BaseTest.context(for_subsystems=...).
    TODO: Fix that.

    :API: public

    :param list subsystem_types: The subclasses of :class:`pants.subsystem.subsystem.Subsystem`
                                 to create.
    :param options: dict of scope -> (dict of option name -> value).
                    The scopes may be those of the global instances of the subsystems (i.e.,
                    subsystem_type.options_scope) and/or the scopes of instances of the
                    subsystems they transitively depend on.
    """
    optionables = set()
    for s in subsystem_types:
        if not Subsystem.is_subsystem_type(s):
            raise TypeError(f"{s} is not a subclass of `Subsystem`")
        for si in s.known_scope_infos():
            optionables.add(si.optionable_cls)
    if options:
        allowed_scopes = {o.options_scope for o in optionables}
        for scope in options.keys():
            if scope != "" and scope not in allowed_scopes:
                raise ValueError(
                    "`{}` is not the scope of any of these subsystems: {}".format(
                        scope, optionables
                    )
                )
    # Don't trample existing subsystem options, in case a test has set up some
    # other subsystems in some other way.
    updated_options = dict(Subsystem._options.items()) if Subsystem._options else {}
    if options:
        updated_options.update(options)
    Subsystem.set_options(create_options_for_optionables(optionables, options=updated_options))

def init_subsystem(subsystem_type, options=None):
    """Singular form of :func:`pants_test.subsystem.subsystem_util.init_subsystems`

    :API: public

    :param subsystem_type: The subclass of :class:`pants.subsystem.subsystem.Subsystem`
                                 to create.
    :param options: dict of scope -> (dict of option name -> value).
                    The scopes may be those of the global instance of the subsystem (i.e.,
                    subsystem_type.options_scope) and/or the scopes of instance of the
                    subsystem it transitively depends on.
    """
    init_subsystems([subsystem_type], options)


text:
<ion-header-bar class="bar-balanced">

My Weather App

</ion-header-bar>

<ion-pane>
  <ion-content>

    	<form class="item item-input-inset" ng-submit="home.doSearch()">

		    <input ng-model="home.search" type="search" placeholder="Search">

		  <button class="button button-balanced">
		    Search
		  </button>
		</form>

{{home.city}}, {{home.state}}

{{home.temp}}°F

				{{home.summary}}

		      Search History

		    <select ng-model="selected" ng-options="key for (key, value) in home.searchHistory">

		    </select>

	        {{key}}

    		Search History

  </ion-content>
</ion-pane>


text:
package org.elasticsearch.xpack.watcher.input.search;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.xpack.watcher.input.InputFactory;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;

import java.io.IOException;

public class SearchInputFactory extends InputFactory<SearchInput, SearchInput.Result, ExecutableSearchInput> {

    private final Client client;
    private final TimeValue defaultTimeout;
    private final WatcherSearchTemplateService searchTemplateService;

    public SearchInputFactory(Settings settings, Client client, NamedXContentRegistry xContentRegistry,
                              ScriptService scriptService) {
        this.client = client;
        this.defaultTimeout = settings.getAsTime("xpack.watcher.input.search.default_timeout", TimeValue.timeValueMinutes(1));
        this.searchTemplateService = new WatcherSearchTemplateService(scriptService, xContentRegistry);
    }

    @Override
    public String type() {
        return SearchInput.TYPE;
    }

    @Override
    public SearchInput parseInput(String watchId, XContentParser parser) throws IOException {
        return SearchInput.parse(watchId, parser);
    }

    @Override
    public ExecutableSearchInput createExecutable(SearchInput input) {
        return new ExecutableSearchInput(input, client, searchTemplateService, defaultTimeout);
    }
}


text:
using System;
using System.Xml;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEditor;
using System.Reflection;
using UnityEditorInternal;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class InjectionBlackListGenerator : EditorWindow
{
    public static string blackListFilePath = CustomSettings.injectionFilesPath + "InjectionBlackList.txt";
    public static Action onBlackListGenerated;

    static string pathsInfoSavedPath;
    static HashSet<string> specifiedDropType = new HashSet<string>
    {
    };
    const string nestRegex = @"     (?<=
                                        (?<!/{2,}.*)                #Ignore Comment
                                    )
                                    (
                                        (?<=class\s+)               #Capture class name
                                        (\b(\w+)\b)
                                        |
                                        (?<=struct\s+)              #Capture struct name
                                        (\b(\w+)\b)
                                        |
                                        (?<=namespace\s+)           #Capture namespace name
                                        ((\b(\w+)\b\.?){1,})
                                    )";/// match class or struct
    const string namespaceRegex = @"(?<=
                                        (?<=
                                            (?<!/{2,}.*)            #Ignore Comment
                                        )
                                        namespace\s+
                                    )";/// match namespace Name
    List<string> paths;
    ReorderableList pathUIList;
    Vector2 scrollPosition = Vector2.zero;
    HashSet<string> blackList = new HashSet<string>();
    Dictionary<string, System.Action<HashSet<string>, string>> assetExtentions = new Dictionary<string, System.Action<HashSet<string>, string>>
    {
        { "*.cs", SearchTypeInCSFile },
        { "*.dll", SearchTypeInAssembly },
    };

#if ENABLE_LUA_INJECTION
    [MenuItem("Lua/Generate LuaInjection BlackList")]
#endif
    public static void Open()
    {
        GetWindow<InjectionBlackListGenerator>("LuaInjection", true);
    }

    void OnListHeaderGUI(Rect rect)
    {
        EditorGUI.LabelField(rect, "Scripts Path");
    }

    void OnListElementGUI(Rect rect, int index, bool isactive, bool isfocused)
    {
        const float GAP = 5;

        string info = paths[index];
        rect.y++;

        Rect r = rect;
        r.width = 16;
        r.height = 18;
        r.xMin = r.xMax + GAP;
        r.xMax = rect.xMax - 50 - GAP;
        GUI.enabled = false;
        info = GUI.TextField(r, info);
        GUI.enabled = true;

        r.xMin = r.xMax + GAP;
        r.width = 50;
        if (GUI.Button(r, "Select"))
        {
            var path = SelectFolder();
            if (path != null)
            {
                paths[index] = path;
            }
        }
    }

    string SelectFolder()
    {
        string dataPath = Application.dataPath;
        string selectedPath = EditorUtility.OpenFolderPanel("Path", dataPath, "");
        if (!string.IsNullOrEmpty(selectedPath))
        {
            return GetRelativePath(selectedPath);
        }
        return null;
    }

    string GetRelativePath(string absolutePath)
    {
        if (absolutePath.StartsWith(Application.dataPath))
        {
            return "Assets/" + absolutePath.Substring(Application.dataPath.Length + 1);
        }
        else
        {
            ShowNotification(new GUIContent("不能在Assets目录之外!"));
        }
        return null;
    }

    void AddNewPath()
    {
        string path = SelectFolder();
        if (!string.IsNullOrEmpty(path))
        {
            paths.Add(path);
        }
    }

    void InitFilterListDrawer()
    {
        if (pathUIList != null)
        {
            return;
        }

        pathUIList = new ReorderableList(paths, typeof(string));
        pathUIList.drawElementCallback = OnListElementGUI;
        pathUIList.drawHeaderCallback = OnListHeaderGUI;
        pathUIList.draggable = true;
        pathUIList.elementHeight = 22;
        pathUIList.onAddCallback = (list) => AddNewPath();
    }

    void OnGUI()
    {
        InitPathsInfo();
        InitFilterListDrawer();

        bool execGenerate = false;
        GUILayout.BeginHorizontal(EditorStyles.toolbar);
        {
            if (GUILayout.Button("Add", EditorStyles.toolbarButton))
            {
                AddNewPath();
            }
            if (GUILayout.Button("Save", EditorStyles.toolbarButton))
            {
                SavePathsInfo();
            }
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Generate", EditorStyles.toolbarButton))
            {
                execGenerate = true;
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginVertical();
        {
            scrollPosition = GUILayout.BeginScrollView(scrollPosition);
            {
                pathUIList.DoLayoutList();
            }
            GUILayout.EndScrollView();
        }
        GUILayout.EndVertical();

        if (execGenerate)
        {
            Generate();
            Close();
        }
    }

    void Generate()
    {
        if (paths.Count == 0)
        {
            EditorUtility.DisplayDialog("提示", "没有选中任何可跳过的路径", "确定");
            return;
        }
        blackList.Clear();

        foreach (var path in paths)
        {
            foreach (var extention in assetExtentions)
            {
                var files = from fileName in Directory.GetFiles(path, extention.Key, SearchOption.AllDirectories)
                            let validFullFileName = fileName.Replace("\\", "/")
                            let bEditorScriptFile = validFullFileName.Contains("/Editor/")
                            //let bToluaGeneratedFile = validFullFileName.Contains("/GenerateWrapFiles/")
                            where !bEditorScriptFile /*&& !bToluaGeneratedFile*/
                            select validFullFileName;

                int index = 0;
                foreach (var fileFullPath in files)
                {
                    EditorUtility.DisplayProgressBar("Searching", fileFullPath, (float)index / files.Count());
                    extention.Value(blackList, fileFullPath);
                    ++index;
                }
                EditorUtility.ClearProgressBar();
            }
        }

        blackList.UnionWith(specifiedDropType);
        SaveBlackList();
        SavePathsInfo();

        if (onBlackListGenerated != null)
        {
            onBlackListGenerated();
        }
        onBlackListGenerated = null;
        Debug.Log("BlackList Generated!!!");
    }

    static void SearchTypeInCSFile(HashSet<string> typeSet, string fileFullPath)
    {
        var fileContent = File.ReadAllText(fileFullPath);
        if (string.IsNullOrEmpty(fileContent))
        {
            return;
        }

        int nestCount = 0;
        int lastTypeMatchedIndex = 0;
        Stack<int> nestIndexStack = new Stack<int>();
        Stack<string> nestStack = new Stack<string>();

        var matchResult = Regex.Match(fileContent, nestRegex, RegexOptions.IgnorePatternWhitespace);
        while (matchResult.Success)
        {
            string typeName = matchResult.Value;
            if (string.IsNullOrEmpty(typeName))
            {
                matchResult = matchResult.NextMatch();
                continue;
            }

            lastTypeMatchedIndex = nestIndexStack.Count > 0 ? nestIndexStack.Peek() : 0;
            string matchSubString = fileContent.Substring(lastTypeMatchedIndex, matchResult.Index - lastTypeMatchedIndex);
            var beginBraceMatchResult = Regex.Matches(matchSubString, "(?<!/{2,}.*){");
            var endBraceMatchResult = Regex.Matches(matchSubString, "(?<!/{2,}.*)}");
            int compareTag = beginBraceMatchResult.Count - endBraceMatchResult.Count;
            bool bNamespaceMatched = Regex.IsMatch(matchSubString, namespaceRegex, RegexOptions.IgnorePatternWhitespace);
            nestIndexStack.Push(matchResult.Index);

            if (compareTag == 0)
            {
                nestStack.Clear();
                nestCount = 0;
            }
            else if (compareTag >= nestCount)
            {
                if (compareTag == nestCount)
                {
                    nestStack.Pop();
                }
                if (compareTag > nestCount)
                {
                    nestCount++;
                }
                nestIndexStack.Pop();
            }
            else if (compareTag < nestCount && compareTag > 0)
            {
                int searchedStackCount = nestStack.Count - compareTag;
                for (int i = 0; i < searchedStackCount; ++i)
                {
                    nestStack.Pop();
                }
                nestCount = nestStack.Count;
                if (nestCount > 0)
                {
                    nestIndexStack.Pop();
                }
            }

            string prefix = "";
            foreach (var name in nestStack)
            {
                prefix = name + prefix;
            }
            string typeFullName = prefix + typeName;
            if (!typeSet.Contains(typeFullName) && !bNamespaceMatched)
            {
                typeSet.Add(typeFullName);
            }

            string nestTag = (bNamespaceMatched ? "." : "+");
            nestStack.Push(typeName + nestTag);
            matchResult = matchResult.NextMatch();
        }
    }

    static void SearchTypeInAssembly(HashSet<string> typeSet, string assemblyPath)
    {
        Assembly assembly = null;
        try
        {
            assembly = Assembly.LoadFile(assemblyPath);
        }
        catch { }

        if (assembly == null)
        {
            return;
        }

        foreach (Type t in assembly.GetTypes())
        {
            bool bNotPrimitiveType = t.IsClass || (t.IsValueType && !t.IsPrimitive && !t.IsEnum);
            bool bCustomType = bNotPrimitiveType && !t.FullName.Contains("<");
            if (bCustomType && !typeSet.Contains(t.FullName) && !t.ContainsGenericParameters)
            {
                typeSet.Add(t.FullName);
            }
        }
    }

    void InitPathsInfo()
    {
        if (pathsInfoSavedPath == null)
        {
            pathsInfoSavedPath = CustomSettings.injectionFilesPath + "LuaInjectionSkipPaths.txt";
        }
        if (paths != null)
        {
            return;
        }

        if (File.Exists(pathsInfoSavedPath))
        {
            paths = new List<string>(File.ReadAllLines(pathsInfoSavedPath));
        }
        else
        {
            paths = new List<string>();
            string toluaPath = GetRelativePath(CustomSettings.injectionFilesPath.Substring(0, CustomSettings.injectionFilesPath.Length - "Injection/".Length));
            paths.Add(toluaPath + "Core/");
            paths.Add(toluaPath + "Injection/");
            paths.Add(toluaPath + "Misc/");
            paths.Add(toluaPath + "Injection/");
            paths.Add(toluaPath + "Misc/");
            paths.Add(Application.dataPath + "/Plugins/");
            paths.Add(CustomSettings.toluaBaseType);
            paths.Add(GetRelativePath(CustomSettings.saveDir));
        }
    }

    void SavePathsInfo()
    {
        File.WriteAllLines(pathsInfoSavedPath, paths.ToArray());
        AssetDatabase.Refresh();
    }

    void SaveBlackList()
    {
        try
        {
            if (File.Exists(blackListFilePath))
            {
                File.Delete(blackListFilePath);
            }
            File.WriteAllLines(blackListFilePath, blackList.ToArray());
        }
        catch (Exception e)
        {
            Debug.LogError(e.ToString());
        }

        AssetDatabase.Refresh();
    }
}


text:
<?php

class ColumnFactoryTest extends DatatablesTestCase {

    public function setUp()
    {
        parent::setUp();

        $this->app['request']->replace($this->testData);
    }

    public function testCreateBuildsNewColumnIndexedByName()
    {
        $input = new Genius\Datatables\Columns\Input\OneNineInput($this->app['request']);

        $factory = new Genius\Datatables\Columns\Factory($input, $this->app['validator']);

        $factory->create("id", 0);

        $this->assertInstanceOf("Genius\Datatables\Columns\Column", $this->getProperty($factory, "columns")[0]);

        return $factory;
    }

    /**
     * @depends testCreateBuildsNewColumnIndexedByName
     */
    public function testGetColumnFromFactoryReturnsWithDataSet($factory)
	{
		$column = $factory->getColumn(0);

		$this->assertInstanceOf("Genius\Datatables\Columns\Column", $column);

		return $column;
	}

	/**
	 * @depends testGetColumnFromFactoryReturnsWithDataSet
	 */
    public function testColumnHasDataSetByFactory(Genius\Datatables\Columns\Column $column)
    {
        $this->assertEquals($column->fields[0], 'id');
        $this->assertEquals($column->mDataProp, 0);
        $this->assertFalse($column->bSearchable);
        $this->assertFalse($column->bSortable);
        $this->assertFalse($column->bRegex);
        $this->assertEquals($column->sSearch, "");
        $this->assertTrue($column->sort);
        $this->assertEquals($column->sort_dir, "asc");
    }

	public function testColumnHasSearchSetFromGlobal()
	{
		$testData = array_merge($this->testData, array(
			"sSearch" => "test",
			"bSearchable_0" => true
		));

		$this->app['request']->replace($testData);

		$input = new Genius\Datatables\Columns\Input\OneNineInput($this->app['request']);

        $factory = new Genius\Datatables\Columns\Factory($input, $this->app['validator']);

        $factory->create("id", 0);

		$this->assertEquals("test", $factory->getColumn(0)->sSearch);
	}

	public function testColumnHasSearchSetLocallyAndIsNotOverridenByGlobal()
	{
		$testData = array_merge($this->testData, array(
			"sSearch" => "test",
			"sSearch_0" => "col0",
			"bSearchable_0" => true
		));

		$this->app['request']->replace($testData);

		$input = new Genius\Datatables\Columns\Input\OneNineInput($this->app['request']);

        $factory = new Genius\Datatables\Columns\Factory($input, $this->app['validator']);

        $factory->create("id", 0);

		$this->assertEquals("col0", $factory->getColumn(0)->sSearch);
	}
}


text:
itk_fetch_module(SphinxExamples
  "This module builds the examples found at http://itk.org/ITKExamples/"
  GIT_REPOSITORY http://itk.org/ITKExamples.git
  # 2015-07-09
  GIT_TAG 2bc08a52aa0437da776cc777157f25b7b525b46f
  )


text:
package org.foxbpm.engine.impl.diagramview.svg.factory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.foxbpm.engine.exception.FoxBPMException;
import org.foxbpm.engine.impl.diagramview.factory.AbstractFlowElementVOFactory;
import org.foxbpm.engine.impl.diagramview.svg.SVGTemplateContainer;
import org.foxbpm.engine.impl.diagramview.svg.SVGTemplateNameConstant;
import org.foxbpm.engine.impl.diagramview.svg.SVGUtils;
import org.foxbpm.engine.impl.diagramview.svg.vo.GVO;
import org.foxbpm.engine.impl.diagramview.svg.vo.SvgVO;
import org.foxbpm.engine.impl.diagramview.vo.VONode;
import org.foxbpm.kernel.process.KernelBaseElement;

/**
 * FLOW单个节点SVG工厂类
 *
 * @author MAENLIANG
 * @date 2014-06-10
 *
 */
public abstract class AbstractFlowElementSVGFactory extends AbstractFlowElementVOFactory {
	/**
	 * static relation
	 */
	private final static Map<String, Class<?>> svgFactoryMap = initSvgFactoryMap();
	/**
	 *
	 * @param kernelFlowElement
	 * @param svgTemplateFileName
	 */
	public AbstractFlowElementSVGFactory(KernelBaseElement kernelBaseElement, String svgTemplateFileName) {
		super(kernelBaseElement, svgTemplateFileName);
	}

	/**
	 *
	 * initSvgBuildMap(static relation)
	 *
	 * @return Map<String,Class<?>>
	 * @exception
	 * @since 1.0.0
	 */
	private static Map<String, Class<?>> initSvgFactoryMap() {
		Map<String, Class<?>> tempSvgFactoryMap = new HashMap<String, Class<?>>();
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_STARTEVENT_TIMER, EventSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_STARTEVENT_NONE, EventSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_CATCHEVENT_TIMER, EventSVGFactory.class);

		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_ENDEVENT_NONE, EventSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_ENDEVENT_TERMINATE, EventSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_ACTIVITY_SUBPROCESS, SubProcessSVGFactory.class);

		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_ACTIVITY_SUBPROCESS_COLLAPSED, SubProcessSVGFactory.class);

		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_ACTIVITY_TASK, TaskSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_CONNECTOR_ASSOCIATION, AssociationSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_CONNECTOR_SEQUENCEFLOW, ConnectorSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_ACTIVITY_CALLACTIVITY, CallActivitySVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_GATEWAY_EXCLUSIVE, GatewaySVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_GATEWAY_INCLUSIVE, GatewaySVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_GATEWAY_PARALLEL, GatewaySVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_GROUP, GroupSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_TEXTANNOTATION, TextAnnotationSVGFactory.class);
		tempSvgFactoryMap.put(SVGTemplateNameConstant.TEMPLATE_LANESET, LanesetSVGFactory.class);

		return tempSvgFactoryMap;
	}
	/**
	 * 创建具体的工厂类,目前支持三种实现
	 *
	 * @param kernelFlowElement
	 * @param svgTemplateFileName
	 * @return
	 */
	public static AbstractFlowElementSVGFactory createSVGFactory(
	    KernelBaseElement kernelBaseElement, String svgTemplateFileName) {
		try {
			return (AbstractFlowElementSVGFactory) svgFactoryMap.get(svgTemplateFileName).getConstructor(KernelBaseElement.class, String.class).newInstance(kernelBaseElement, svgTemplateFileName);
		} catch (Exception e) {
			throw new FoxBPMException("createSVGFactory exception ", e);
		}

	}

	/**
	 * 将所有的元素对象转化成String字符串
	 *
	 * @param voNodeList
	 *            所有的节点集合
	 * @return SVG字符串
	 */

	public String convertNodeListToString(Map<String, Object> processDefinitionPorperties,
	    List<VONode> voNodeList) {
		VONode svgContainer = this.getDefaultSVGContainerFromFactory(processDefinitionPorperties);
		Iterator<VONode> voIter = voNodeList.iterator();
		SvgVO svgVo = null;
		GVO clone = null;
		List<GVO> getgVoList = null;
		while (voIter.hasNext()) {
			svgVo = (SvgVO) voIter.next();
			clone = SVGUtils.cloneGVO(svgVo.getgVo());
			getgVoList = ((SvgVO) svgContainer).getgVo().getgVoList();
			getgVoList.add(clone);
		}
		return SVGUtils.createSVGString(svgContainer);
	}

	/**
	 * 创建SVG模板容器对象
	 *
	 * @return
	 */
	public static VONode createSVGTemplateContainerVO(
	    Map<String, Object> processDefinitionProperties) {
		VONode svgTemplateContainer = SVGTemplateContainer.getContainerInstance().getCloneTemplateByName(SVGTemplateNameConstant.SVG_TEMPLATE);
		return svgTemplateContainer;
	}

	/**
	 * 加载SVG模版
	 *
	 * @param templateName
	 *            模版名称
	 * @return SVG模版
	 */
	protected VONode loadSVGVO(String templateName) {
		try {
			return SVGTemplateContainer.getContainerInstance().getCloneTemplateByName(templateName);
		} catch (Exception e) {
			throw new FoxBPMException("template svg file load exception", e);
		}
	}

	/**
	 * 获取模版容器对象
	 */
	private VONode getDefaultSVGContainerFromFactory(Map<String, Object> processDefinitionPorperties) {
		SvgVO svgTemplateContainer = (SvgVO) AbstractFlowElementSVGFactory.createSVGTemplateContainerVO(processDefinitionPorperties);
		Float svgMinX = (Float) processDefinitionPorperties.get(CANVAS_MINX);
		Float svgMinY = (Float) processDefinitionPorperties.get(CANVAS_MINY);
		Float svgMaxX = (Float) processDefinitionPorperties.get(CANVAS_MAXX);
		Float svgMaxY = (Float) processDefinitionPorperties.get(CANVAS_MAXY);
		svgTemplateContainer.setWidth(svgMaxX);
		svgTemplateContainer.setHeight(svgMaxY);
		svgTemplateContainer.setMinHeight(String.valueOf(svgMinY));
		svgTemplateContainer.setMinWidth(String.valueOf(svgMinX));
		// 初始化VOList
		svgTemplateContainer.getgVo().setgVoList(new ArrayList<GVO>());
		return svgTemplateContainer;
	}
}


text:
ddg() {
  if [ ${#} -gt 1 ]; then
    open "https://duckduckgo.com/?q=${1}"
  elif [ ${#} -gt 2 ]; then
    open "https://duckduckgo.com/?q=${1}\!${2}"
  else
    printf "Invalid input!\n"
  fi;
}

# Use Chrome from shell
chrome() {
  # Prevent shell from foregrounding `chrome`
  if ! pgrep "Chrome" >/dev/null 2>&1; then
    open -a "Google Chrome" >/dev/null 2>&1 && \
    osascript -e 'tell app "Google Chrome" to close front window'
  fi;
  # Open Chrome binary with arguments, then switch to created window
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ${@} 2>/dev/null \
  && open -a "Google Chrome" >/dev/null 2>&1
}

# Kill all the tabs in Chrome to free up memory
# `grep [C]hrome` explained: tinyurl.com/c7uq9x
ctabkill() {
  ps ux | grep '[C]hrome Helper --type=renderer' | grep -v extension-process |\
  tr -s ' ' | cut -d ' ' -f2 | xargs kill
}

# Open all Safari tabs in Chrome
tabsaco() {
  open -a "Google Chrome"
  osascript \
  -e 'tell application "Chrome" to activate' \
  -e 'set list_Tabs to {}' \
  -e 'tell application "Safari"' \
    -e 'set the_Tabs to (tabs of every window)' \
    -e 'repeat with the_Tab in the_Tabs' \
      -e 'set the_Items to (every item of the_Tab)' \
      -e 'repeat with the_Item in the_Items' \
        -e 'copy URL of the_Item to end of list_Tabs' \
      -e 'end repeat' \
    -e 'end repeat' \
  -e 'end tell' \
  -e 'tell application "Google Chrome"' \
    -e 'repeat with list_Tab in list_Tabs' \
      -e 'set myTab to make new tab at end of tabs of window 1' \
      -e 'set URL of myTab to list_Tab' \
    -e 'end repeat' \
  -e 'end tell' \
  -e 'tell application "System Events" to set visible of process "Safari" to false'
}

# Open all Chrome tabs in Safari
tabcosa() {
  open -a "Safari"
  osascript \
  -e 'set list_Tabs to {}' \
  -e 'tell application "Google Chrome"' \
    -e 'set the_Tabs to (tabs of every window)' \
    -e 'repeat with the_Tab in the_Tabs' \
      -e 'set the_Items to (every item of the_Tab)' \
      -e 'repeat with the_Item in the_Items' \
        -e 'copy URL of the_Item to end of list_Tabs' \
      -e 'end repeat' \
    -e 'end repeat' \
  -e 'end tell' \
  -e 'tell application "Safari"' \
    -e 'repeat with list_Tab in list_Tabs' \
      -e 'set myTab to make new tab at end of tabs of window 1' \
      -e 'set URL of myTab to list_Tab' \
    -e 'end repeat' \
  -e 'end tell' \
  -e 'tell application "System Events" to set visible of process "Google Chrome" to false'
}


text:
package no.noen.server.eos;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import no.noen.eos.DayData;
import org.komsa.db.PoolManager;
import org.komsa.log.LogWriter;
import org.komsa.server.entity.EntityServiceImpl;

/**
 * Class for handling import to database.
 */
public class BatchImport {
    /** Constructor. */
    private BatchImport() {
    }

    /**
     * Save data batch.
     */
    public static void save(DataBatch batch) {
        java.util.Map<String,DayData> dayMap = new java.util.HashMap<String,DayData>();

        // Get existing data in period
        try {
            MeterFactory fac = new MeterFactory();
            long meterId = batch.getMeterId();
            java.util.List<DayData> dayList =
                fac.getPeriodData(meterId, batch.getMinDate(), batch.getMaxDate());
            java.text.DateFormat df = new SimpleDateFormat("yyyyMMdd");
            for (int i = 0; i < dayList.size(); i++) {
                DayData data = dayList.get(i);
                dayMap.put(df.format(data.getDate()), data);
            }
        } catch (Exception ex) {
            LogWriter.elog(ex, "BatchImport.save");
        }

        // Check for changes
        java.util.List<DayData> changedData = new java.util.ArrayList<DayData>();
        for (Iterator<String> it = batch.getDayIterator(); it.hasNext(); ) {
            String key = it.next();
            DayData data = batch.getEntry(key);
            DayData oldData = dayMap.get(key);
            if (oldData == null) {
                // New entry
                changedData.add(data);
            } else {
                // Old entry, update
                for (int hour = 1; hour < 25; hour++) {
                    boolean hasData = data.hasHourData(hour);
                    if (hasData)
                        oldData.setData(hour, data.getRawData(hour));
                }
                if (oldData.isModified())
                    changedData.add(oldData);
            }
        }

        // Finally save changes
        if (changedData.size() > 0)
            saveElements(changedData);

        MeterManager.stampCount(batch.getMeter());
    }

    /**
     * Save data elements.
     */
    private static void saveElements(java.util.List<DayData> dataList) {
        Connection conn = null;
        try {
            conn = PoolManager.getInstance().getConnection("eos");
            if (conn == null)
                throw new SQLException("No database connection available.");
            EntityServiceImpl es = new EntityServiceImpl();
            for (int i = 0; i < dataList.size(); i++) {
                DayData data = dataList.get(i);
                es.save(data, conn);
            }
        } catch (Exception ex) {
            LogWriter.elog(ex, "BatchImport.saveElements");
        } finally {
            if (conn != null)
                PoolManager.getInstance().freeConnection("eos", conn);
            conn = null;
        }
    }

}


text:
'use strict';

module.exports = function (options) {
    var name = options.hash.name || '';

    var strObject = {
        string: '',
        toHTML: function () {
            return this.string;
        }
    };
    if (name) {
        var newAttrs = [];
        if (options.hash.className !== undefined) {
            newAttrs.push('class="' + options.hash.className + '"');
        }

        for (var i in options.hash) {
            if (i !== 'name' && i !== 'className' && Object.prototype.hasOwnProperty.call(options.hash, i)) {
                newAttrs.push(i + '="' + options.hash[i] + '"');
            }
        }

        if (newAttrs.length) {
            newAttrs.unshift('');
        }

        newAttrs = newAttrs.join(' ');

        strObject.string = '<svg' + newAttrs + '><use xlink:href="#' + name + '"></use></svg>';
    }

    return strObject;
};


text:
package xxx.screwdriver.forsakenscissors.objects;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;

import xxx.screwdriver.forsakenscissors.Game;
import xxx.screwdriver.forsakenscissors.GameObject;

public class Ladder extends GameObject {

	private static int LADDER_WIDTH = 42;
	private static int LADDER_HEIGHT = 42;

	public Ladder(float x, float y) throws SlickException {
		super(x, y, LADDER_WIDTH, LADDER_HEIGHT);
	}

	public void update(GameContainer container, float delta) {
		super.update(container, delta);
		if (this.checkCollision(Game.getInstance().getPlayer())) {
			Game.getInstance().getPlayer().setNearLadder(true);
		}
	}
}


text:
KAMISHIBAI runs WPF applications on Generic Host.

Generic Host is the most important architecture in .NET, and many modern libraries are provided on the premise of Generic Host.

By supporting Generic Host, KAMISHIBAI supports modern libraries.

The code to host the simplest application is as follows

```cs
using GettingStarted;
using Kamishibai;
using Microsoft.Extensions.Hosting;

// Create a builder by specifying the application and main window.
var builder = KamishibaiApplication<App, MainWindow>.CreateBuilder();

// Register presentation(View and ViewModel).
builder.Services.AddPresentation<MainWindow, MainViewModel>();
builder.Services.AddPresentation<FirstPage, FirstViewModel>();

// Build and run the application.
var app = builder.Build();
await app.RunAsync();
```

It can be described in the same way as ASP.NET Core 6.0.

For example, if you want to load environment-specific configuration files, you can do so as follows

```cs
var builder = KamishibaiApplication<App, MainWindow>.CreateBuilder();

builder.Configuration
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", true, false);
```

For detailed usage, please refer to the documentation of each library.

[<< NuGet Package Structure and Overview](03-overview.md) | [Menu](01-table-of-contents.md) | [Navigation Details >>](05-navigation.md)


text:
package org.apache.camel.converter;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.util.StopWatch;

/**
 * @version
 */
public class PropertyEditorTypeConverterIssueTest extends ContextTestSupport {

    public void testPropertyEditorTypeConverter() throws Exception {
        // test that converters a custom object (MyBean) to a String which causes
        // PropertyEditorTypeConverter to be used. And this test times how fast
        // this is. As we want to optimize PropertyEditorTypeConverter to be faster
        MyBean bean = new MyBean();
        bean.setBar("Hello");

        StopWatch watch = new StopWatch();
        for (int i = 0; i < 500; i++) {
            assertNotNull(context.getTypeConverter().convertTo(String.class, bean));
        }
        log.info("Time taken: " + watch.stop());
    }
}


text:
<?php

namespace Vipa\AdminBundle\Tests\Controller;

use Vipa\CoreBundle\Tests\BaseTestSetup as BaseTestCase;

class AdminMailTemplateControllerTest extends BaseTestCase
{
    public function testIndex()
    {
        $this->logIn();
        $client = $this->client;
        $client->request('GET', '/admin/mail-template/');

        $this->assertStatusCode(200, $client);
    }

    public function testShow()
    {
        $this->logIn();
        $client = $this->client;
        $client->request('GET', '/admin/mail-template/1/show');

        $this->assertStatusCode(200, $client);
    }

    public function testEdit()
    {
        $this->logIn();
        $client = $this->client;
        $client->request('GET', '/admin/mail-template/1/edit');

        $this->assertStatusCode(200, $client);
    }
}


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

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>WeakHashtableTest xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />

1
17
18
19  package org.apache.commons.logging.impl;
20
21  import java.lang.ref.*;
22  import junit.framework.*;
23  import java.util.*;
24
25  public class WeakHashtableTest extends TestCase {
26
27
28      /** Maximum number of iterations before our test fails */
29      private static final int MAX_GC_ITERATIONS = 50;
30
31      private WeakHashtable weakHashtable;
32      private Long keyOne;
33      private Long keyTwo;
34      private Long keyThree;
35      private Long valueOne;
36      private Long valueTwo;
37      private Long valueThree;
38
39      public WeakHashtableTest(String testName) {
40          super(testName);
41      }
42
43
44      protected void setUp() throws Exception {
45          super.setUp();
46          weakHashtable = new WeakHashtable();
47
48          keyOne = new Long(1);
49          keyTwo = new Long(2);
50          keyThree = new Long(3);
51          valueOne = new Long(100);
52          valueTwo = new Long(200);
53          valueThree = new Long(300);
54
55          weakHashtable.put(keyOne, valueOne);
56          weakHashtable.put(keyTwo, valueTwo);
57          weakHashtable.put(keyThree, valueThree);
58      }
59
60      /** Tests public boolean contains(Object value) */
61      public void testContains() throws Exception {
62          assertFalse(weakHashtable.contains(new Long(1)));
63          assertFalse(weakHashtable.contains(new Long(2)));
64          assertFalse(weakHashtable.contains(new Long(3)));
65          assertTrue(weakHashtable.contains(new Long(100)));
66          assertTrue(weakHashtable.contains(new Long(200)));
67          assertTrue(weakHashtable.contains(new Long(300)));
68          assertFalse(weakHashtable.contains(new Long(400)));
69      }
70
71      /** Tests public boolean containsKey(Object key) */
72      public void testContainsKey() throws Exception {
73          assertTrue(weakHashtable.containsKey(new Long(1)));
74          assertTrue(weakHashtable.containsKey(new Long(2)));
75          assertTrue(weakHashtable.containsKey(new Long(3)));
76          assertFalse(weakHashtable.containsKey(new Long(100)));
77          assertFalse(weakHashtable.containsKey(new Long(200)));
78          assertFalse(weakHashtable.containsKey(new Long(300)));
79          assertFalse(weakHashtable.containsKey(new Long(400)));
80      }
81
82      /** Tests public boolean containsValue(Object value) */
83      public void testContainsValue() throws Exception {
84          assertFalse(weakHashtable.containsValue(new Long(1)));
85          assertFalse(weakHashtable.containsValue(new Long(2)));
86          assertFalse(weakHashtable.containsValue(new Long(3)));
87          assertTrue(weakHashtable.containsValue(new Long(100)));
88          assertTrue(weakHashtable.containsValue(new Long(200)));
89          assertTrue(weakHashtable.containsValue(new Long(300)));
90          assertFalse(weakHashtable.containsValue(new Long(400)));
91      }
92
93      /** Tests public Enumeration elements() */
94      public void testElements() throws Exception {
95          ArrayList elements = new ArrayList();
96          for (Enumeration e = weakHashtable.elements(); e.hasMoreElements();) {
97              elements.add(e.nextElement());
98          }
99          assertEquals(3, elements.size());
100         assertTrue(elements.contains(valueOne));
101         assertTrue(elements.contains(valueTwo));
102         assertTrue(elements.contains(valueThree));
103     }
104
105     /** Tests public Set entrySet() */
106     public void testEntrySet() throws Exception {
107         Set entrySet = weakHashtable.entrySet();
108         for (Iterator it = entrySet.iterator(); it.hasNext();) {
109             Map.Entry entry = (Map.Entry) it.next();
110             Object key = entry.getKey();
111             if (keyOne.equals(key)) {
112                 assertEquals(valueOne, entry.getValue());
113             } else if (keyTwo.equals(key)) {
114                 assertEquals(valueTwo, entry.getValue());
115             } else if (keyThree.equals(key)) {
116                 assertEquals(valueThree, entry.getValue());
117             } else {
118                 fail("Unexpected key");
119             }
120         }
121     }
122
123     /** Tests public Object get(Object�key) */
124     public void testGet() throws Exception {
125         assertEquals(valueOne, weakHashtable.get(keyOne));
126         assertEquals(valueTwo, weakHashtable.get(keyTwo));
127         assertEquals(valueThree, weakHashtable.get(keyThree));
128         assertNull(weakHashtable.get(new Long(50)));
129     }
130
131     /** Tests public Enumeration keys() */
132     public void testKeys() throws Exception {
133         ArrayList keys = new ArrayList();
134         for (Enumeration e = weakHashtable.keys(); e.hasMoreElements();) {
135             keys.add(e.nextElement());
136         }
137         assertEquals(3, keys.size());
138         assertTrue(keys.contains(keyOne));
139         assertTrue(keys.contains(keyTwo));
140         assertTrue(keys.contains(keyThree));
141     }
142
143     /** Tests public Set keySet() */
144     public void testKeySet() throws Exception {
145         Set keySet = weakHashtable.keySet();
146         assertEquals(3, keySet.size());
147         assertTrue(keySet.contains(keyOne));
148         assertTrue(keySet.contains(keyTwo));
149         assertTrue(keySet.contains(keyThree));
150     }
151
152     /** Tests public Object put(Object key, Object value) */
153     public void testPut() throws Exception {
154         Long anotherKey = new Long(2004);
155         weakHashtable.put(anotherKey, new Long(1066));
156
157         assertEquals(new Long(1066), weakHashtable.get(anotherKey));
158
159         // Test compliance with the hashtable API re nulls
160         Exception caught = null;
161         try {
162             weakHashtable.put(null, new Object());
163         }
164         catch (Exception e) {
165             caught = e;
166         }
167         assertNotNull("did not throw an exception adding a null key", caught);
168         caught = null;
169         try {
170             weakHashtable.put(new Object(), null);
171         }
172         catch (Exception e) {
173             caught = e;
174         }
175         assertNotNull("did not throw an exception adding a null value", caught);
176     }
177
178     /** Tests public void putAll(Map t) */
179     public void testPutAll() throws Exception {
180         Map newValues = new HashMap();
181         Long newKey = new Long(1066);
182         Long newValue = new Long(1415);
183         newValues.put(newKey, newValue);
184         Long anotherNewKey = new Long(1645);
185         Long anotherNewValue = new Long(1815);
186         newValues.put(anotherNewKey, anotherNewValue);
187         weakHashtable.putAll(newValues);
188
189         assertEquals(5, weakHashtable.size());
190         assertEquals(newValue, weakHashtable.get(newKey));
191         assertEquals(anotherNewValue, weakHashtable.get(anotherNewKey));
192     }
193
194     /** Tests public Object remove(Object�key) */
195     public void testRemove() throws Exception {
196         weakHashtable.remove(keyOne);
197         assertEquals(2, weakHashtable.size());
198         assertNull(weakHashtable.get(keyOne));
199     }
200
201     /** Tests public Collection values() */
202     public void testValues() throws Exception {
203         Collection values = weakHashtable.values();
204         assertEquals(3, values.size());
205         assertTrue(values.contains(valueOne));
206         assertTrue(values.contains(valueTwo));
207         assertTrue(values.contains(valueThree));
208     }
209
210     public void testRelease() throws Exception {
211         assertNotNull(weakHashtable.get(new Long(1)));
212         ReferenceQueue testQueue = new ReferenceQueue();
213         WeakReference weakKeyOne = new WeakReference(keyOne, testQueue);
214
215         // lose our references
216         keyOne = null;
217         keyTwo = null;
218         keyThree = null;
219         valueOne = null;
220         valueTwo = null;
221         valueThree = null;
222
223         int iterations = 0;
224         int bytz = 2;
225         while(true) {
226             System.gc();
227             if(iterations++ > MAX_GC_ITERATIONS){
228                 fail("Max iterations reached before resource released.");
229             }
230
231             if(weakHashtable.get(new Long(1)) == null) {
232                 break;
233
234             } else {
235                 // create garbage:
236                 byte[] b =  new byte[bytz];
237                 bytz = bytz * 2;
238             }
239         }
240
241         // some JVMs seem to take a little time to put references on
242         // the reference queue once the reference has been collected
243         // need to think about whether this is enough to justify
244         // stepping through the collection each time...
245         while(testQueue.poll() == null) {}
246
247         // Test that the released objects are not taking space in the table
248         assertEquals("underlying table not emptied", 0, weakHashtable.size());
249     }
250 }

This page was automatically generated by Maven


text:
layout: remote_event
categories:
  - events
links:
title: "Nick Lucius, Chicago's Chief Data Officer"
description: "Nick Lucius serves as the City of Chicago's Chief Data Officer. Working in the Office of Mayor Lori Lightfoot, Nick oversees data strategy and policy citywide. He will talk about how the city uses data and technology to flatten the curve of COVID infections, with a focus on racial justice."
speakers:
 - "Nick Lucius, Chief Data Officer, Office of the Mayor, City of Chicago"
image: /images/events/401-nick-lucius.jpg
image_credit:
date: 2020-06-09T19:00:00-05:00
event_id: 401
youtube_id: K7wFnbeBtl0
agenda:
sponsor: Chi Hack Night Community
asl_provided: false
tags:
 - covid-19
 - govtech
 - 'open data'
published: true

---

[Chi Hack Nights are now remote!](/blog/2020/03/16/chi-hack-night-going-remote.html) Now from the comfort of your self-quarantine location!

Tune into our livestream at 7pm CST every Tuesday: **[youtube.com/chihacknight/live](https://youtube.com/chihacknight/live)**

---

Nick Lucius serves as the City of Chicago's Chief Data Officer. Working in the Office of Mayor Lori Lightfoot, Nick oversees data strategy and policy citywide. Recently, Nick worked as a data scientist at the former Department of Innovation and Technology. Prior to working in data, Nick was an attorney and worked in a variety of public interest settings, including environmental code enforcement, health and human services, and transportation safety.

Since his appointment earlier this year, Nick has managed many data and tech projects in coordination with Chicago's [COVID-19 response](https://www.chicago.gov/city/en/sites/covid-19/home.html). He will talk about how the city [uses data](https://www.chicago.gov/city/en/sites/covid-19/home/latest-data.html) and technology to flatten the curve of COVID infections, with a focus on racial justice.

---

**ASL** This event will {% unless page.asl_provided %} not {% endunless %}have an American Sign Language interpreter.


text:
package proto

//go:generate capnp compile -I $GOPATH -ogo match.capnp
//go:generate capnp compile -I $GOPATH -ogo progressupdate.capnp
//go:generate capnp compile -I $GOPATH -ogo sourcebackend.capnp


text:
using Glove
using Test
using LinearAlgebra

# Anything <: AbstractFloat, just here for easy use
S = Float32

# Test from python Glove implementation.
# https://github.com/maciejkula/glove-python/tree/master/glove/tests
corpus1 = split(read("data/corpus_test1.txt", String))
table = LookupTable(corpus1)
@test table.word2id == Dict("a" => 1, "naive" => 2, "fox" => 3)
@test table.id2word == Dict(1 => "a", 2 => "naive",  3 => "fox")
@test length(table) == 3
@test table["fox"] == 3
@test table[1] == "a"

# create the co-occurence matrix and table in 1 pass on the corpus.
codict = weightedsums(S, table, corpus1)
@test codict[(1,1)] == 0.0
@test codict[(1,2)] == 1.0
@test codict[(1,3)] == 0.5

@test codict[(2,1)] == 1.0
@test codict[(2,2)] == 0.0
@test codict[(2,3)] == 1.0

@test codict[(3,1)] == 0.5
@test codict[(3,2)] == 1.0
@test codict[(3,3)] == 0.0

corpus2 = split(read("data/corpus_test2.txt", String))
table = LookupTable(corpus2)
codict = weightedsums(S, table, corpus2)

cokeys = collect(keys(codict))
covals = collect(values(codict))

n = length(codict)
covec = CooccurenceVector{S}(undef, n)

@inbounds for i=1:n
  covec[i] = (cokeys[i][1], cokeys[i][2], covals[i])
end

vocabsize = length(table)
vecsize = 10

model = Model(S, vocabsize, vecsize)

@test typeof(model) == Glove.Model{S}
@test eltype(model.W_main) == S
@test typeof(covec) == CooccurenceVector{S}
@test eltype(covec) == Tuple{Int, Int, S}

# The corpus is very, very small.
# So even with a large amount of iterations
# this test may fail.
adagrad!(S, model, covec, 500)

# make sure everything is still the same type
@test eltype(model.W_main) == S

# similar words
function similar_words(
  M::Matrix{T},
  table::LookupTable,
  word::S;
  n::Int=10) where {T, S<:Token}

    c_id = table[word]

    dists = vec(M[:, c_id]' * M) / norm(M[:, c_id]) / norm(M, 1)

    sorted_ids = sortperm(dists, rev=true)[1:n+1]
    sim_words = Token[]

    for id = sorted_ids
        if c_id == id
            continue
        end
        word = table[id]
        push!(sim_words, word)
    end
    sim_words
end

# paper recommends adding the main and context matrices.
M = model.W_main + model.W_ctx
top_words = similar_words(M, table, "trees", n=10)[1:3]
@test in("graph", top_words)
top_words = similar_words(M, table, "graph", n=10)[1:3]
@test in("trees", top_words)


text:
define([
    'settings/js/widgets/path-widget',
    'test/test-utils',
    'jasmine-jquery'
], function(PathWidget, utils) {

    describe('Path widget', function() {
        beforeEach(function() {
            this.widget = new PathWidget({
                configItem: 'thingThatNeedsAPath',
                description: 'Choose a path',
                strings: {
                    label: 'Path:'
                },
                title: 'Path To Thing'
            });

            this.widget.render();
            this.widget.updateConfig({path: '/opt/thing'});
            this.$path = this.widget.$('input[name="path"]');
        });

        utils.testSuperProperties.call(this, {configItem: 'thingThatNeedsAPath', title: 'Path To Thing', description: 'Choose a path'});

        it('should display the correct config', function() {
            expect(this.$path).toHaveValue('/opt/thing');
        });

        it('should return the correct config', function() {
            this.$path.val('C:\\things');
            expect(this.widget.getConfig()).toEqual({path: 'C:\\things'});
        });

        it('should fail client side validation on blank path', function() {
            var $controlGroup = this.$path.closest('.control-group');
            this.$path.val('');
            var isValid = this.widget.validateInputs();

            expect(isValid).toBeFalsy();
            expect($controlGroup).toHaveClass('error');

            this.$path.val('/opt').trigger('change');

            expect($controlGroup).not.toHaveClass('error');
        });
    });

});


text:
require "securerandom"

module RedTokenAuth
  module Validations
    extend ActiveSupport::Concern

    included do
      include ActiveModel::SecurePassword

      validates :email,
        format: RedTokenAuth.configuration.email_regex,
        if: Proc.new { |resource| resource.email.present? || resource.provider == "email" }
      validates :password,
        length: { in: RedTokenAuth.configuration.password_length },
        confirmation: true,
        if: Proc.new { |resource| resource.password.present? }
    end
  end
end


text:
import { Serif } from "@artsy/palette"
import { ArtistBio_bio } from "v2/__generated__/ArtistBio_bio.graphql"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import styled from "styled-components"

export interface ArtistBioProps {
  bio: ArtistBio_bio
  onReadMoreClicked?: () => void
  maxChars?: number
}

export class ArtistBio extends React.Component<ArtistBioProps> {
  render() {
    const { bio } = this.props
    return (
      <Serif size="3">
        <BioSpan
          dangerouslySetInnerHTML={{
            __html: bio.biographyBlurb.text,
          }}
        />
      </Serif>
    )
  }
}

export const ArtistBioFragmentContainer = createFragmentContainer(ArtistBio, {
  bio: graphql`
    fragment ArtistBio_bio on Artist {
      biographyBlurb: biographyBlurb(format: HTML, partnerBio: true) {
        text
      }
    }
  `,
})

/*
  Using dangerouslySetInnerHTML in our span adds an inline <p>.
  Here we make sure the inline <p> is formatted properly.
*/
const BioSpan = styled.span`
  > * {
    margin-block-start: 0;
    margin-block-end: 0;
    padding-bottom: 1em;
  }
  > *:last-child {
    display: inline;
  }
`


text:
<link rel="import" href="./subdir/subbehavior.html">

<script>
  /**
   * A simple behavior description.
   * @polymerBehavior
   */
  MyNamespace.SimpleBehavior = {
    behaviors: [MyNamespace.SubBehavior],
    properties: {
      /** A property provided by SimpleBehavior. */
      inheritPlease: {
        type: Number,
        value: 10,
        notify: true
      }
    }
  };
</script>


text:
package org.clinical3PO.hadoop.reducers;

import java.io.IOException;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PatientUniqueCountReducer extends Reducer<Text, Text, Text, NullWritable> {

	private static final Logger logger = LoggerFactory.getLogger(PatientUniqueCountReducer.class);

	@Override
	public void reduce(Text key, Iterable<Text> values, Context context)
			throws IOException, InterruptedException {

		if(key != null) {
			context.write(key, NullWritable.get());
		}
	}
}


text:
.class public final Lcom/payu/android/sdk/internal/gg;
.super Ljava/lang/Object;

# instance fields
.field public a:Landroid/content/Context;

.field public b:Lcom/payu/android/sdk/internal/fq;

.field public c:Lcom/payu/android/sdk/internal/v;

# direct methods
.method public constructor <init>(Landroid/content/Context;Lcom/payu/android/sdk/internal/fq;Lcom/payu/android/sdk/internal/v;)V
    .locals 0

    .line 44
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 45
    iput-object p1, p0, Lcom/payu/android/sdk/internal/gg;->a:Landroid/content/Context;

    .line 46
    iput-object p2, p0, Lcom/payu/android/sdk/internal/gg;->b:Lcom/payu/android/sdk/internal/fq;

    .line 47
    iput-object p3, p0, Lcom/payu/android/sdk/internal/gg;->c:Lcom/payu/android/sdk/internal/v;

    .line 48
    return-void
.end method

.method public static a(Lcom/payu/android/sdk/internal/wf;)Lcom/payu/android/sdk/internal/vx;
    .locals 5

    .line 64
    move-object v4, p0

    new-instance v0, Lcom/payu/android/sdk/internal/vx;

    invoke-direct {v0, v4}, Lcom/payu/android/sdk/internal/vx;-><init>(Lcom/payu/android/sdk/internal/wf;)V

    .line 65
    move-object p0, v0

    move-object v4, v0

    const-wide/16 v0, 0x1f4

    const-wide/16 v2, 0x0

    cmp-long v0, v0, v2

    if-gez v0, :cond_0

    new-instance v0, Ljava/lang/IllegalArgumentException;

    const-string v1, "Delay must be positive value."

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    :cond_0
    const-wide/16 v0, 0x1f4

    const-wide/32 v2, 0x7fffffff

    cmp-long v0, v0, v2

    if-lez v0, :cond_1

    new-instance v0, Ljava/lang/IllegalArgumentException;

    const-string v1, "Delay value too large. Max: 2147483647"

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    :cond_1
    iget v0, v4, Lcom/payu/android/sdk/internal/vx;->d:I

    int-to-long v0, v0

    const-wide/16 v2, 0x1f4

    cmp-long v0, v0, v2

    if-eqz v0, :cond_2

    const/16 v0, 0x1f4

    iput v0, v4, Lcom/payu/android/sdk/internal/vx;->d:I

    invoke-virtual {v4}, Lcom/payu/android/sdk/internal/vx;->a()V

    .line 66
    :cond_2
    move-object v4, p0

    iget v0, p0, Lcom/payu/android/sdk/internal/vx;->e:I

    if-eqz v0, :cond_3

    const/4 v0, 0x0

    iput v0, v4, Lcom/payu/android/sdk/internal/vx;->e:I

    invoke-virtual {v4}, Lcom/payu/android/sdk/internal/vx;->a()V

    .line 67
    :cond_3
    return-object p0
.end method


text:
<?php

namespace ZendSearchTest\Lucene;

use ZendSearch\Lucene\Document;

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage UnitTests
 * @group      Zend_Search_Lucene
 */
class FieldTest extends \PHPUnit_Framework_TestCase
{
    public function testBinary()
    {
        $field = Document\Field::Binary('field', 'value');

        $this->assertEquals($field->boost, 1);
        $this->assertEquals($field->encoding, '');
        $this->assertEquals($field->isBinary,    true);
        $this->assertEquals($field->isIndexed,   false);
        $this->assertEquals($field->isStored,    true);
        $this->assertEquals($field->isTokenized, false);

        $this->assertEquals($field->name, 'field');
        $this->assertEquals($field->value, 'value');
    }

    public function testKeyword()
    {
        $field = Document\Field::Keyword('field', 'value');

        $this->assertEquals($field->boost, 1);
        $this->assertEquals($field->encoding, 'UTF-8');
        $this->assertEquals($field->isBinary,    false);
        $this->assertEquals($field->isIndexed,   true);
        $this->assertEquals($field->isStored,    true);
        $this->assertEquals($field->isTokenized, false);

        $this->assertEquals($field->name, 'field');
        $this->assertEquals($field->value, 'value');
    }

    public function testText()
    {
        $field = Document\Field::Text('field', 'value');

        $this->assertEquals($field->boost, 1);
        $this->assertEquals($field->encoding, 'UTF-8');
        $this->assertEquals($field->isBinary,    false);
        $this->assertEquals($field->isIndexed,   true);
        $this->assertEquals($field->isStored,    true);
        $this->assertEquals($field->isTokenized, true);

        $this->assertEquals($field->name, 'field');
        $this->assertEquals($field->value, 'value');
    }

    public function testUnIndexed()
    {
        $field = Document\Field::UnIndexed('field', 'value');

        $this->assertEquals($field->boost, 1);
        $this->assertEquals($field->encoding, 'UTF-8');
        $this->assertEquals($field->isBinary,    false);
        $this->assertEquals($field->isIndexed,   false);
        $this->assertEquals($field->isStored,    true);
        $this->assertEquals($field->isTokenized, false);

        $this->assertEquals($field->name, 'field');
        $this->assertEquals($field->value, 'value');
    }

    public function testUnStored()
    {
        $field = Document\Field::UnStored('field', 'value');

        $this->assertEquals($field->boost, 1);
        $this->assertEquals($field->encoding, 'UTF-8');
        $this->assertEquals($field->isBinary,    false);
        $this->assertEquals($field->isIndexed,   true);
        $this->assertEquals($field->isStored,    false);
        $this->assertEquals($field->isTokenized, true);

        $this->assertEquals($field->name, 'field');
        $this->assertEquals($field->value, 'value');
    }

    public function testEncoding()
    {
        // forcing filter to UTF-8
        $utf8text = iconv('UTF-8', 'UTF-8', 'Words with umlauts: åãü...');

        $iso8859_1 = iconv('UTF-8', 'ISO-8859-1', $utf8text);
        $field = Document\Field::Text('field', $iso8859_1, 'ISO-8859-1');

        $this->assertEquals($field->encoding, 'ISO-8859-1');

        $this->assertEquals($field->name, 'field');
        $this->assertEquals($field->value, $iso8859_1);
        $this->assertEquals($field->getUtf8Value(), $utf8text);
    }
}


text:
>Given a version number MAJOR.MINOR.PATCH, increment the:
>
 >1. MAJOR version when you make incompatible API changes,
 >2. MINOR version when you add functionality in a backwards-compatible manner,
 >3. PATCH version when you make backwards-compatible bug fixes
>
>Specification
>
 >4. Major version zero (0.y.z) is for initial development. Anything may change at any time. The public API should not be considered stable.

### [Git Flow][git flow] branching model.

Two main branches with an infinite lifetime:

- `master` (reserved for deployment)
- `develop`

Both branches are [Protected](https://help.github.com/articles/about-protected-branches/)

`master` requires a [Pull Request Review](https://help.github.com/articles/about-pull-request-reviews/)

`develop` is submitted to **Continuous Integration**. Making it somewhat stable to be considered as a *nightly build*.

Since **status checks** require another branch (you can't commit directly to develop), project development is done through **support branches**.

**Support Branches naming conventions:**

- format `tag/project/description`
- tags `feature`, `hot-fix` and `release` are reserved by [Git Flow][git flow]
- project is optional and id's the affected [project](#projects)
- description `addt-<technology-name>` when adding a new technology for easier pin-pointing

### Projects

qip is a monorepo with multiple services:

- **webapi**

    web server that exposes the qip api

- **webclient**

    web app, called client to better differentiate from webapi (otherwise only one letter off)

## In Practice

### Features

1. Create a new **feature-branch**, branching from `develop`

   `git checkout -b feature/x develop`

2. Work on feature. **Commit often!**

    Follow [The Seven rules of a great Git commit message](https://chris.beams.io/posts/git-commit/#seven-rules)

    [Strive for atomic commits](https://www.freshconsulting.com/atomic-commits/).
    Smaller commits have more precise diffs and a clear sequence, thus are easier to understand.

    `git commit -m "Descriptive change message"`

3. "Merge"

   1. Create a **Pull Request**

    **or**

   1. Push features to remote

        `git push -u origin feature/x`

   2. Change back to develop

        `git checkout develop`

   3. Merge changes

        `git merge --no-ff feature/x`

        Optionally delete local branch

        `git branch -d feature/x`

   4. Push merge to remote

        `git push origin develop`

        This could give an error if mandatory **status checks** are still pending or failed

### Releases

Follow a similar pattern to features with small changes

1. naming convention is `release/version`

2. Bumps version across configuration files

3. Should only do last touch commits (e.g., bugfixes, deployment configurations...)

4. Also merges with `master` branch, tagging it

## Code Conventions

Linters and static analysis tools will be incorporated into the **Continuous Integration** pipeline to enforce code conventions

### TODOs

`TODO(user): do something`

Where user should be an id of the author (e.g., github username)

You can be more suggestive about the context using the following words:

- `FIXME`
- `HACK`
- `BUG`

[git flow]: http://nvie.com/posts/a-successful-git-branching-model/


text:
package com.intuso.housemate.client.api.bridge.v1_0.driver;

import com.google.common.base.Function;
import com.intuso.housemate.client.v1_0.api.driver.ConditionDriver;

/**
 * Created by tomc on 05/11/15.
 */
public class ConditionDriverMapper {

    private final Function<com.intuso.housemate.client.api.internal.driver.ConditionDriver, ConditionDriver> toV1_0Function = new Function<com.intuso.housemate.client.api.internal.driver.ConditionDriver, ConditionDriver>() {
        @Override
        public ConditionDriver apply(com.intuso.housemate.client.api.internal.driver.ConditionDriver conditionDriver) {
            return map(conditionDriver);
        }
    };

    private final Function<ConditionDriver, com.intuso.housemate.client.api.internal.driver.ConditionDriver> fromV1_0Function = new Function<ConditionDriver, com.intuso.housemate.client.api.internal.driver.ConditionDriver>() {
        @Override
        public com.intuso.housemate.client.api.internal.driver.ConditionDriver apply(ConditionDriver conditionDriver) {
            return map(conditionDriver);
        }
    };

    public Function<com.intuso.housemate.client.api.internal.driver.ConditionDriver, ConditionDriver> getToV1_0Function() {
        return toV1_0Function;
    }

    public Function<ConditionDriver, com.intuso.housemate.client.api.internal.driver.ConditionDriver> getFromV1_0Function() {
        return fromV1_0Function;
    }

    public <FROM extends com.intuso.housemate.client.api.internal.driver.ConditionDriver, TO extends ConditionDriver>
        TO map(FROM conditionDriver) {
        if(conditionDriver == null)
            return null;
        else if(conditionDriver instanceof ConditionDriverBridge)
            return (TO) ((ConditionDriverBridge) conditionDriver).getConditionDriver();
        return (TO) new ConditionDriverBridgeReverse(conditionDriver);
    }

    public <FROM extends ConditionDriver, TO extends com.intuso.housemate.client.api.internal.driver.ConditionDriver>
        TO map(FROM conditionDriver) {
        if(conditionDriver == null)
            return null;
        else if(conditionDriver instanceof ConditionDriverBridgeReverse)
            return (TO) ((ConditionDriverBridgeReverse) conditionDriver).getConditionDriver();
        return (TO) new ConditionDriverBridge(conditionDriver);
    }
}