text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="KinematicCollision2D" inherits="Reference" version="3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		Collision data for [KinematicBody2D] collisions.
	</brief_description>
	<description>
		Contains collision data for [KinematicBody2D] collisions. When a [KinematicBody2D] is moved using [method KinematicBody2D.move_and_collide], it stops if it detects a collision with another body. If a collision is detected, a KinematicCollision2D object is returned.
		This object contains information about the collision, including the colliding object, the remaining motion, and the collision position. This information can be used to calculate a collision response.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="get_angle" qualifiers="const">
			<return type="float" />
			<argument index="0" name="up_direction" type="Vector2" default="Vector2( 0, -1 )" />
			<description>
				The collision angle according to [code]up_direction[/code], which is [code]Vector2.UP[/code] by default. This value is always positive.
			</description>
		</method>
	</methods>
	<members>
		<member name="collider" type="Object" setter="" getter="get_collider">
			The colliding body.
		</member>
		<member name="collider_id" type="int" setter="" getter="get_collider_id" default="0">
			The colliding body's unique instance ID. See [method Object.get_instance_id].
		</member>
		<member name="collider_metadata" type="Variant" setter="" getter="get_collider_metadata">
			The colliding body's metadata. See [Object].
		</member>
		<member name="collider_rid" type="RID" setter="" getter="get_collider_rid">
			The colliding body's [RID] used by the [Physics2DServer].
		</member>
		<member name="collider_shape" type="Object" setter="" getter="get_collider_shape">
			The colliding body's shape.
		</member>
		<member name="collider_shape_index" type="int" setter="" getter="get_collider_shape_index" default="0">
			The colliding shape's index. See [CollisionObject2D].
		</member>
		<member name="collider_velocity" type="Vector2" setter="" getter="get_collider_velocity" default="Vector2( 0, 0 )">
			The colliding object's velocity.
		</member>
		<member name="local_shape" type="Object" setter="" getter="get_local_shape">
			The moving object's colliding shape.
		</member>
		<member name="normal" type="Vector2" setter="" getter="get_normal" default="Vector2( 0, 0 )">
			The colliding body's shape's normal at the point of collision.
		</member>
		<member name="position" type="Vector2" setter="" getter="get_position" default="Vector2( 0, 0 )">
			The point of collision, in global coordinates.
		</member>
		<member name="remainder" type="Vector2" setter="" getter="get_remainder" default="Vector2( 0, 0 )">
			The moving object's remaining movement vector.
		</member>
		<member name="travel" type="Vector2" setter="" getter="get_travel" default="Vector2( 0, 0 )">
			The distance the moving object traveled before collision.
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
package com.haxademic.core.draw.filters.pshader;

import com.haxademic.core.draw.filters.pshader.shared.BaseFragmentShader;

import processing.core.PApplet;

public class RadialFlareFilter
extends BaseFragmentShader {

	public static RadialFlareFilter instance;

	public RadialFlareFilter(PApplet p) {
		super(p, "haxademic/shaders/filters/radial-flare.glsl");
		setRadialLength(0.95f);
		setImageBrightness(9f);
		setFlareBrightness(9f);
		setIters(100f);
	}

	public static RadialFlareFilter instance(PApplet p) {
		if(instance != null) return instance;
		instance = new RadialFlareFilter(p);
		return instance;
	}

	public void setRadialLength(float radialLength) {
		shader.set("radialLength", radialLength);
	}

	public void setImageBrightness(float imageBrightness) {
		shader.set("imageBrightness", imageBrightness);
	}

	public void setFlareBrightness(float flareBrightness) {
		shader.set("flareBrightness", flareBrightness);
	}

	public void setIters(float iters) {
		shader.set("iters", iters);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CampaignChain\CoreBundle\Wizard\Install\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class AdminStepType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('user', 'text', array(
                'data' => 'admin',
            ))
            ->add('first_name', 'text')
            ->add('last_name', 'text')
            ->add('password', 'repeated', array(
                'required'        => false,
                'type'            => 'password',
                'first_name'      => 'password',
                'second_name'     => 'password_again',
                'invalid_message' => 'The password fields must match.',
            ))
            ->add('timezone', 'timezone')
            ->add('email', 'email');
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'campaignchain_core_install_step_admin';
    }
}


text: package club.zhcs.titans.utils;


text:
#include <algorithm>
#include <utility>

#include "drawtypes/iconset.hpp"
#include "drawtypes/label.hpp"
#include "modules/xworkspaces.hpp"
#include "utils/factory.hpp"
#include "utils/math.hpp"
#include "x11/atoms.hpp"
#include "x11/connection.hpp"

#include "modules/meta/base.inl"

POLYBAR_NS

namespace {
  inline bool operator==(const position& a, const position& b) {
    return a.x + a.y == b.x + b.y;
  }
}

namespace modules {
  template class module<xworkspaces_module>;

  /**
   * Construct module
   */
  xworkspaces_module::xworkspaces_module(const bar_settings& bar, string name_)
      : static_module<xworkspaces_module>(bar, move(name_)), m_connection(connection::make()) {
    // Load config values
    m_pinworkspaces = m_conf.get(name(), "pin-workspaces", m_pinworkspaces);
    m_click = m_conf.get(name(), "enable-click", m_click);
    m_scroll = m_conf.get(name(), "enable-scroll", m_scroll);

    // Initialize ewmh atoms
    if ((m_ewmh = ewmh_util::initialize()) == nullptr) {
      throw module_error("Failed to initialize ewmh atoms");
    }

    // Check if the WM supports _NET_CURRENT_DESKTOP
    if (!ewmh_util::supports(m_ewmh->_NET_CURRENT_DESKTOP)) {
      throw module_error("The WM does not support _NET_CURRENT_DESKTOP, aborting...");
    }

    // Check if the WM supports _NET_DESKTOP_VIEWPORT
    if (!(m_monitorsupport = ewmh_util::supports(m_ewmh->_NET_DESKTOP_VIEWPORT)) && m_pinworkspaces) {
      throw module_error("The WM does not support _NET_DESKTOP_VIEWPORT (required when `pin-workspaces = true`)");
    }

    // Add formats and elements
    m_formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, {TAG_LABEL_STATE, TAG_LABEL_MONITOR});

    if (m_formatter->has(TAG_LABEL_MONITOR)) {
      m_monitorlabel = load_optional_label(m_conf, name(), "label-monitor", DEFAULT_LABEL_MONITOR);
    }

    if (m_formatter->has(TAG_LABEL_STATE)) {
      // clang-format off
      m_labels.insert(make_pair(
          desktop_state::ACTIVE, load_optional_label(m_conf, name(), "label-active", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::OCCUPIED, load_optional_label(m_conf, name(), "label-occupied", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::URGENT, load_optional_label(m_conf, name(), "label-urgent", DEFAULT_LABEL_STATE)));
      m_labels.insert(make_pair(
          desktop_state::EMPTY, load_optional_label(m_conf, name(), "label-empty", DEFAULT_LABEL_STATE)));
      // clang-format on
    }

    m_icons = factory_util::shared<iconset>();
    m_icons->add(DEFAULT_ICON, factory_util::shared<label>(m_conf.get(name(), DEFAULT_ICON, ""s)));

    for (const auto& workspace : m_conf.get_list<string>(name(), "icon", {})) {
      auto vec = string_util::split(workspace, ';');
      if (vec.size() == 2) {
        m_icons->add(vec[0], factory_util::shared<label>(vec[1]));
      }
    }

    // Get list of monitors
    m_monitors = randr_util::get_monitors(m_connection, m_connection.root(), false);

    // Get desktop details
    m_desktop_names = get_desktop_names();
    m_current_desktop = ewmh_util::get_current_desktop();
    m_current_desktop_name = m_desktop_names[m_current_desktop];

    rebuild_desktops();
    rebuild_desktop_states();

    // Get _NET_CLIENT_LIST
    rebuild_clientlist();
  }

  /**
   * Handler for XCB_PROPERTY_NOTIFY events
   */
  void xworkspaces_module::handle(const evt::property_notify& evt) {
    if (evt->atom == m_ewmh->_NET_CLIENT_LIST) {
      rebuild_clientlist();
    } else if (evt->atom == m_ewmh->_NET_DESKTOP_NAMES || evt->atom == m_ewmh->_NET_NUMBER_OF_DESKTOPS) {
      m_desktop_names = get_desktop_names();
      rebuild_desktops();
      rebuild_desktop_states();
    } else if (evt->atom == m_ewmh->_NET_CURRENT_DESKTOP) {
      m_current_desktop = ewmh_util::get_current_desktop();
      m_current_desktop_name = m_desktop_names[m_current_desktop];
      rebuild_desktop_states();
    } else if (evt->atom == WM_HINTS) {
      if (icccm_util::get_wm_urgency(m_connection, evt->window)) {
        set_desktop_urgent(evt->window);
      }
    } else {
      return;
    }

    if (m_timer.allow(evt->time)) {
      broadcast();
    }
  }

  /**
   * Rebuild the list of managed clients
   */
  void xworkspaces_module::rebuild_clientlist() {
    vector<xcb_window_t> clients = ewmh_util::get_client_list();
    vector<xcb_window_t> diff;
    std::sort(clients.begin(), clients.end());
    std::sort(m_clientlist.begin(), m_clientlist.end());

    if (m_clientlist.size() > clients.size()) {
      std::set_difference(
          m_clientlist.begin(), m_clientlist.end(), clients.begin(), clients.end(), back_inserter(diff));
      for (auto&& win : diff) {
        // untrack window
        m_clientlist.erase(std::remove(m_clientlist.begin(), m_clientlist.end(), win), m_clientlist.end());
      }
    } else {
      std::set_difference(
          clients.begin(), clients.end(), m_clientlist.begin(), m_clientlist.end(), back_inserter(diff));
      for (auto&& win : diff) {
        // listen for wm_hint (urgency) changes
        m_connection.ensure_event_mask(win, XCB_EVENT_MASK_PROPERTY_CHANGE);
        // track window
        m_clientlist.emplace_back(win);
      }
    }
  }

  /**
   * Rebuild the desktop tree
   */
  void xworkspaces_module::rebuild_desktops() {
    m_viewports.clear();

    auto bounds = [&] {
      if (m_monitorsupport) {
        return ewmh_util::get_desktop_viewports();
      } else {
        vector<position> b;
        std::fill_n(std::back_inserter(b), m_desktop_names.size(), position{m_bar.monitor->x, m_bar.monitor->y});
        return b;
      }
    }();

    bounds.erase(std::unique(bounds.begin(), bounds.end(), [](auto& a, auto& b) { return a == b; }), bounds.end());

    unsigned int step;
    if (bounds.size() > 0) {
      step = m_desktop_names.size() / bounds.size();
    } else {
      step = 1;
    }
    unsigned int offset = 0;
    for (unsigned int i = 0; i < bounds.size(); i++) {
      if (!m_pinworkspaces || m_bar.monitor->match(bounds[i])) {
        auto viewport = make_unique<struct viewport>();
        viewport->state = viewport_state::UNFOCUSED;
        viewport->pos = bounds[i];

        for (auto&& m : m_monitors) {
          if (m->match(viewport->pos)) {
            viewport->name = m->name;
            viewport->state = viewport_state::FOCUSED;
          }
        }

        viewport->label = [&] {
          label_t label;
          if (m_monitorlabel) {
            label = m_monitorlabel->clone();
            label->reset_tokens();
            label->replace_token("%name%", viewport->name);
          }
          return label;
        }();

        for (unsigned int index = offset; index < offset + step; index++) {
          viewport->desktops.emplace_back(make_unique<struct desktop>(index, offset, desktop_state::EMPTY, label_t{}));
        }

        m_viewports.emplace_back(move(viewport));
      }
      offset += step;
    }
  }

  /**
   * Update active state of current desktops
   */
  void xworkspaces_module::rebuild_desktop_states() {
    for (auto&& v : m_viewports) {
      for (auto&& d : v->desktops) {
        if (m_desktop_names[d->index] == m_current_desktop_name) {
          d->state = desktop_state::ACTIVE;
        } else {
          d->state = desktop_state::EMPTY;
        }

        d->label = m_labels.at(d->state)->clone();
        d->label->reset_tokens();
        d->label->replace_token("%index%", to_string(d->index - d->offset + 1));
        d->label->replace_token("%name%", m_desktop_names[d->index]);
        d->label->replace_token("%icon%", m_icons->get(m_desktop_names[d->index], DEFAULT_ICON)->get());
      }
    }
  }

  vector<string> xworkspaces_module::get_desktop_names(){
    vector<string> names = ewmh_util::get_desktop_names();
    unsigned int desktops_number = ewmh_util::get_number_of_desktops();
    if(desktops_number == names.size()) {
      return names;
    }
    else if(desktops_number < names.size()) {
      names.erase(names.begin()+desktops_number, names.end());
      return names;
    }
    for (unsigned int i = names.size(); i < desktops_number + 1; i++) {
      names.insert(names.end(), to_string(i));
    }
    return names;
  }

  /**
   * Find window and set corresponding desktop to urgent
   */
  void xworkspaces_module::set_desktop_urgent(xcb_window_t window) {
    auto desk = ewmh_util::get_desktop_from_window(window);
    if(desk == m_current_desktop)
      // ignore if current desktop is urgent
      return;
    for (auto&& v : m_viewports) {
      for (auto&& d : v->desktops) {
        if (d->index == desk && d->state != desktop_state::URGENT) {
          d->state = desktop_state::URGENT;

          d->label = m_labels.at(d->state)->clone();
          d->label->reset_tokens();
          d->label->replace_token("%index%", to_string(d->index - d->offset + 1));
          d->label->replace_token("%name%", m_desktop_names[d->index]);
          d->label->replace_token("%icon%", m_icons->get(m_desktop_names[d->index], DEFAULT_ICON)->get());
          return;
        }
      }
    }

  }

  /**
   * Fetch and parse data
   */
  void xworkspaces_module::update() {}

  /**
   * Generate module output
   */
  string xworkspaces_module::get_output() {
    // Get the module output early so that
    // the format prefix/suffix also gets wrapped
    // with the cmd handlers
    string output;
    for (m_index = 0; m_index < m_viewports.size(); m_index++) {
      if (m_index > 0) {
        m_builder->space(m_formatter->get(DEFAULT_FORMAT)->spacing);
      }
      output += module::get_output();
    }

    if (m_scroll) {
      m_builder->cmd(mousebtn::SCROLL_DOWN, string{EVENT_PREFIX} + string{EVENT_SCROLL_DOWN});
      m_builder->cmd(mousebtn::SCROLL_UP, string{EVENT_PREFIX} + string{EVENT_SCROLL_UP});
    }

    m_builder->append(output);

    m_builder->cmd_close();
    m_builder->cmd_close();

    return m_builder->flush();
  }

  /**
   * Output content as defined in the config
   */
  bool xworkspaces_module::build(builder* builder, const string& tag) const {
    if (tag == TAG_LABEL_MONITOR) {
      if (m_viewports[m_index]->state != viewport_state::NONE) {
        builder->node(m_viewports[m_index]->label);
        return true;
      } else {
        return false;
      }
    } else if (tag == TAG_LABEL_STATE) {
      unsigned int added_states = 0;
      for (auto&& desktop : m_viewports[m_index]->desktops) {
        if (desktop->label.get()) {
          if (m_click && desktop->state != desktop_state::ACTIVE) {
            builder->cmd(mousebtn::LEFT, string{EVENT_PREFIX} + string{EVENT_CLICK} + to_string(desktop->index));
            builder->node(desktop->label);
            builder->cmd_close();
          } else {
            builder->node(desktop->label);
          }
          added_states++;
        }
      }
      return added_states > 0;
    } else {
      return false;
    }
  }

  /**
   * Handle user input event
   */
  bool xworkspaces_module::input(string&& cmd) {
    size_t len{strlen(EVENT_PREFIX)};
    if (cmd.compare(0, len, EVENT_PREFIX) != 0) {
      return false;
    }
    cmd.erase(0, len);

    vector<unsigned int> indexes;
    for (auto&& viewport : m_viewports) {
      for (auto&& desktop : viewport->desktops) {
        indexes.emplace_back(desktop->index);
      }
    }

    std::sort(indexes.begin(), indexes.end());

    unsigned int new_desktop{0};
    unsigned int current_desktop{ewmh_util::get_current_desktop()};

    if ((len = strlen(EVENT_CLICK)) && cmd.compare(0, len, EVENT_CLICK) == 0) {
      new_desktop = std::strtoul(cmd.substr(len).c_str(), nullptr, 10);
    } else if ((len = strlen(EVENT_SCROLL_UP)) && cmd.compare(0, len, EVENT_SCROLL_UP) == 0) {
      new_desktop = math_util::min<unsigned int>(indexes.back(), current_desktop + 1);
      new_desktop = new_desktop == current_desktop ? indexes.front() : new_desktop;
    } else if ((len = strlen(EVENT_SCROLL_DOWN)) && cmd.compare(0, len, EVENT_SCROLL_DOWN) == 0) {
      new_desktop = math_util::max<unsigned int>(indexes.front(), current_desktop - 1);
      new_desktop = new_desktop == current_desktop ? indexes.back() : new_desktop;
    }

    if (new_desktop != current_desktop) {
      m_log.info("%s: Requesting change to desktop #%u", name(), new_desktop);
      ewmh_util::change_current_desktop(new_desktop);
    } else {
      m_log.info("%s: Ignoring change to current desktop", name());
    }

    return true;
  }
}

POLYBAR_NS_END


text:
'use strict';

var fs = require('fs');
var path = require('path');

module.exports = function(grunt) {
  var coverageWriteStream;

  grunt.task.registerTask('finalize-coverage-stream', function() {
    if (!coverageWriteStream) {
      return;
    }
    var done = this.async();
    coverageWriteStream.once('close', done);
    coverageWriteStream.end();
    coverageWriteStream = null;
  });

  function consoleLoggerMiddleware(req, res, next) {
    if (!(req.method === 'POST' && req._parsedUrl.pathname.replace(/\//g, '') === 'console' && Array.isArray(req.body))) {
      return next();
    }
    res.write('<!doctype html><meta charset=utf-8>');
    res.end('Got it, thanks!');

    req.body.forEach(function(log) {
      if (log.message.indexOf('not ok ') === 0) {
        log.type = 'error';
      } else if (log.message.indexOf('ok ') === 0) {
        log.type = 'ok';
      } else if (log.message.indexOf('COVER') === 0) {
        log.type = 'coverage';
      } else if (log.message.indexOf('DONE\t') === 0) {
        log.type = 'coverage done';
      }

      if (log.type === 'error') {
        grunt.log.error(log.message);
      } else if (log.type === 'ok') {
        grunt.log.ok(log.message);
      } else if (log.type === 'log') {
        grunt.log.writeln(log.message);
      } else if (log.type === 'coverage') {
        if (!coverageWriteStream) {
          coverageWriteStream = fs.createWriteStream(path.join(__dirname, '/../../coverage.log'));
        }
        coverageWriteStream.write(log.message + '\n');
      } else if (log.type === 'coverage done') {
        grunt.task.run('finalize-coverage-stream');
      } else if (log.type === 'perf') {
        grunt.event.emit('perf results', log.message);
      } else {
        grunt.verbose.writeln(log);
      }
    });
  }

  function testResultLoggerMiddleware(req, res, next) {
    if (!(req.method === 'POST' && req._parsedUrl.pathname.indexOf('/reportTestResults') === 0)) {
      return next();
    }
    res.write('<!doctype html><meta charset=utf-8>');
    res.end('Got it, thanks!');

    var logType = 'writeln';
    var message = req.body;

    if (req.body.type && req.body.message) {
      if (req.body.type === 'error') {
        logType = 'error';
      } else if (req.body.message.indexOf('ok') === 0) {
        logType = 'ok';
      } else if (req.body.message.indexOf('not ok') === 0) {
        logType = 'error';
      }
      message = req.body.message;
    }
    if (typeof message !== 'string') {
      message = JSON.stringify(message, null, 2);
    }
    grunt.log[logType]('[%s][%s]', req.headers['user-agent'], Date.now(), message);
  }

  return {
    server: {
      options: {
        base: '.',
        hostname: '*',
        port: 9999,
        middleware: function(connect, options) {

          connect.logger.token('user-agent', function(req, res) {
            return req.headers['user-agent'];
          });
          connect.logger.token('timestamp', function(req, res) {
            return Date.now();
          });

          return [
            connect.json(),
            consoleLoggerMiddleware,
            testResultLoggerMiddleware,

            connect.logger({format:'[:user-agent][:timestamp] :method :url', stream:grunt.verbose}),
            connect.static(options.base),
            connect.directory(options.base),
          ];
        },
      },
    },
  };
};


text:
package com.example.jingbin.cloudreader.view.viewbigimage;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.viewpager.widget.ViewPager;

/**
 * Hacky fix for Issue #4 and
 * http://code.google.com/p/android/issues/detail?id=18990
 *
 * ScaleGestureDetector seems to mess up the touch events, which means that
 * ViewGroups which make use of onInterceptTouchEvent throw a lot of
 * IllegalArgumentException: pointerIndex out of range.
 *
 * There's not much I can do in my code for now, but we can mask the result by
 * just catching the problem and ignoring it.
 *
 * @author Chris Banes
 */
public class HackyViewPager extends ViewPager {

//	public HackyViewPager(Context context) {
//		super(context);
//	}

	public HackyViewPager(Context context, AttributeSet attributeSet){
		super(context, attributeSet);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		try {
			return super.onInterceptTouchEvent(ev);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return false;
		}
	}

}


text:
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      t.datetime :remember_created_at

      t.datetime :last_sign_in_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
  end
end


text:
package org.kairosdb.core.http;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Scopes;
import com.google.inject.servlet.GuiceFilter;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.eclipse.jetty.servlets.QoSFilter;
import org.kairosdb.core.http.exceptionmapper.InvalidServerTypeExceptionMapper;
import org.kairosdb.core.KairosRootConfig;
import org.kairosdb.core.http.rest.AdminResource;
import org.kairosdb.core.http.rest.FeaturesResource;
import org.kairosdb.core.http.rest.MetadataResource;
import org.kairosdb.core.http.rest.MetricsResource;

public class WebServletModule extends JerseyServletModule
{
	public static final String QOS_URL = "kairosdb.qos.url";
	public static final String QOS_PREFIX = "kairosdb.qos.";

	private String qosURL = null;
	private ImmutableMap<String, String> qosParams;

	public WebServletModule(KairosRootConfig props)
	{
		if (props.hasPath(QOS_URL) && !(props.getString(QOS_URL,"")).trim().equals(""))
		{
			qosURL =  props.getString(QOS_URL);
			ImmutableMap.Builder<String, String> qosBuilder = new ImmutableMap.Builder<>();
			for (String key : props)
			{
				if (key.startsWith(QOS_PREFIX) && !key.contentEquals(QOS_URL))
				{
					String qosKey = key.substring(QOS_PREFIX.length());
					String qosValue = props.getString(key);
					qosBuilder.put(qosKey, qosValue);
				}
			}
			this.qosParams = qosBuilder.build();
		}
	}

	public String getQosUrl()
	{
		return qosURL;
	}

	public ImmutableMap<String, String> getQosParams()
	{
		return qosParams;
	}

	@Override
	protected void configureServlets()
	{
		binder().requireExplicitBindings();
		bind(GuiceFilter.class);

		//Bind web server
		bind(WebServer.class);

		//Bind resource classes here
		bind(MetricsResource.class).in(Scopes.SINGLETON);
		bind(MetadataResource.class).in(Scopes.SINGLETON);
		bind(FeaturesResource.class).in(Scopes.SINGLETON);
		bind(AdminResource.class).in(Scopes.SINGLETON);

		bind(GuiceContainer.class);

		bind(LoggingFilter.class).in(Scopes.SINGLETON);
		filter("/*").through(LoggingFilter.class);

		if (qosURL != null)
		{
			bind(QoSFilter.class).in(Scopes.SINGLETON);
			filter(qosURL).through(QoSFilter.class, qosParams);
		}

		// hook Jackson into Jersey as the POJO <-> JSON mapper
		bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);
		serve("/*").with(GuiceContainer.class);

		//
		bind(InvalidServerTypeExceptionMapper.class).in(Scopes.SINGLETON);
	}
}


text:
package com.annimon.hotarufx.visual.objects;

import com.annimon.hotarufx.exceptions.HotaruRuntimeException;
import com.annimon.hotarufx.visual.PropertyBindings;
import com.annimon.hotarufx.visual.PropertyTimeline;
import com.annimon.hotarufx.visual.PropertyTimelineHolder;
import com.annimon.hotarufx.visual.TimeLine;
import com.annimon.hotarufx.visual.visitors.NodeVisitor;
import java.util.EnumSet;
import java.util.function.Supplier;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.WritableValue;
import javafx.scene.Node;
import javafx.scene.effect.BlendMode;
import javafx.util.StringConverter;
import static com.annimon.hotarufx.visual.PropertyType.*;

public abstract class ObjectNode {

    private final Node node;
    private PropertyTimelineHolder<Boolean> visible;
    private PropertyTimelineHolder<Number> opacity;
    private PropertyTimelineHolder<Node> clip;
    private PropertyTimelineHolder<String> style;
    private PropertyTimelineHolder<Number> rotate;
    private PropertyTimelineHolder<Number> translateX, translateY, translateZ;
    private PropertyTimelineHolder<Number> scaleX, scaleY, scaleZ;
    private PropertyTimelineHolder<Number> layoutX, layoutY;
    private PropertyTimelineHolder<String> blendMode;
    private boolean isRenderable;

    public ObjectNode(Node node) {
        this.node = node;
        visible = PropertyTimelineHolder.empty();
        opacity = PropertyTimelineHolder.empty();
        clip = PropertyTimelineHolder.empty();
        style = PropertyTimelineHolder.empty();
        rotate = PropertyTimelineHolder.empty();
        translateX = PropertyTimelineHolder.empty();
        translateY = PropertyTimelineHolder.empty();
        translateZ = PropertyTimelineHolder.empty();
        scaleX = PropertyTimelineHolder.empty();
        scaleY = PropertyTimelineHolder.empty();
        scaleZ = PropertyTimelineHolder.empty();
        layoutX = PropertyTimelineHolder.empty();
        layoutY = PropertyTimelineHolder.empty();
        blendMode = PropertyTimelineHolder.empty();
        isRenderable = true;
    }

    public Node getFxNode() {
        return node;
    }

    public boolean isRenderable() {
        return isRenderable;
    }

    public void setRenderable(boolean renderable) {
        isRenderable = renderable;
    }

    public PropertyTimeline<Boolean> visibleProperty() {
        return visible.setIfEmptyThenGet(node::visibleProperty);
    }

    public PropertyTimeline<Number> opacityProperty() {
        return opacity.setIfEmptyThenGet(node::opacityProperty);
    }

    public PropertyTimeline<Node> clipProperty() {
        return clip.setIfEmptyThenGet(node::clipProperty);
    }

    public PropertyTimeline<String> styleProperty() {
        return style.setIfEmptyThenGet(node::styleProperty);
    }

    public PropertyTimeline<Number> rotateProperty() {
        return rotate.setIfEmptyThenGet(node::rotateProperty);
    }

    public PropertyTimeline<Number> translateXProperty() {
        return translateX.setIfEmptyThenGet(node::translateXProperty);
    }

    public PropertyTimeline<Number> translateYProperty() {
        return translateY.setIfEmptyThenGet(node::translateYProperty);
    }

    public PropertyTimeline<Number> translateZProperty() {
        return translateZ.setIfEmptyThenGet(node::translateZProperty);
    }

    public PropertyTimeline<Number> scaleXProperty() {
        return scaleX.setIfEmptyThenGet(node::scaleXProperty);
    }

    public PropertyTimeline<Number> scaleYProperty() {
        return scaleY.setIfEmptyThenGet(node::scaleYProperty);
    }

    public PropertyTimeline<Number> scaleZProperty() {
        return scaleZ.setIfEmptyThenGet(node::scaleZProperty);
    }

    public PropertyTimeline<Number> layoutXProperty() {
        return layoutX.setIfEmptyThenGet(node::layoutXProperty);
    }

    public PropertyTimeline<Number> layoutYProperty() {
        return layoutY.setIfEmptyThenGet(node::layoutYProperty);
    }

    public PropertyTimeline<String> blendModeProperty() {
        return blendMode.setIfEmptyThenGet(enumToString(BlendMode.class, node.blendModeProperty()));
    }

    public void buildTimeline(TimeLine timeline) {
        visible.applyIfPresent(timeline);
        opacity.applyIfPresent(timeline);
        clip.applyIfPresent(timeline);
        style.applyIfPresent(timeline);
        rotate.applyIfPresent(timeline);
        translateX.applyIfPresent(timeline);
        translateY.applyIfPresent(timeline);
        translateZ.applyIfPresent(timeline);
        scaleX.applyIfPresent(timeline);
        scaleY.applyIfPresent(timeline);
        scaleZ.applyIfPresent(timeline);
        layoutX.applyIfPresent(timeline);
        layoutY.applyIfPresent(timeline);
        blendMode.applyIfPresent(timeline);
    }

    public final PropertyBindings propertyBindings() {
        return propertyBindings(new PropertyBindings());
    }

    protected PropertyBindings propertyBindings(PropertyBindings bindings) {
        return bindings
                .add("visible", BOOLEAN, this::visibleProperty)
                .add("opacity", NUMBER, this::opacityProperty)
                .add("clip", CLIP_NODE, this::clipProperty)
                .add("css", STRING, this::styleProperty)
                .add("style", STRING, this::styleProperty)
                .add("rotate", NUMBER, this::rotateProperty)
                .add("translateX", NUMBER, this::translateXProperty)
                .add("translateY", NUMBER, this::translateYProperty)
                .add("translateZ", NUMBER, this::translateZProperty)
                .add("scaleX", NUMBER, this::scaleXProperty)
                .add("scaleY", NUMBER, this::scaleYProperty)
                .add("scaleZ", NUMBER, this::scaleZProperty)
                .add("layoutX", NUMBER, this::layoutXProperty)
                .add("layoutY", NUMBER, this::layoutYProperty)
                .add("blendMode", STRING, this::blendModeProperty);
    }

    protected <T extends Enum<T>> Supplier<WritableValue<String>> enumToString(Class<T> enumClass, ObjectProperty<T> property) {
        return () -> {
            final var stringProperty = new SimpleStringProperty();
            stringProperty.bindBidirectional(property, new StringConverter<T>() {
                @Override
                public String toString(T object) {
                    if (object == null) {
                        return "null";
                    }
                    return object.name();
                }

                @Override
                public T fromString(String string) {
                    if ("null".equals(string)) {
                        return null;
                    }
                    try {
                        return Enum.valueOf(enumClass, string);
                    } catch (IllegalArgumentException e) {
                        try {
                            final var number = (int) Double.parseDouble(string);
                            return enumClass.cast(EnumSet.allOf(enumClass).toArray()[number]);
                        } catch (Exception ex) {
                            throw new HotaruRuntimeException("No constant " + string
                                    + " for type " + enumClass.getSimpleName());
                        }
                    }
                }
            });
            return stringProperty;
        };
    }

    public abstract <R, T> R accept(NodeVisitor<R, T> visitor, T input);
}


text:
/*
 * This program finds the element which occurs odd times in an array. All
 * other numbers occur even times in the array
 */

import java.io.*;
import java.util.*;

public class element_which_occurs_odd_times_in_array
{
    /*
     * This function finds the element which occurs odd times in a array based
     * on the logic that XOR operation of an element with itself results in
     * zero and xor of a number with zero gives us the number itself. So if we
     * XOR all the numbers in the array together, then we will get the number
     * which occurs odd number of times in the array. The time complexity of
     * this function is O(n).
     */
    public static int element_odd_times (int []array)
    {
        int result = 0; /* Set result to zero */
        int i;

        /*
         * Take the XOR of all array elements in 'result'.
         */
        for (i = 0; i < array.length; ++i) {
            result ^= array[i];
        }

        /*
         * Return the result
         */
        return result;
    }

    public static void main (String[] args)
    {
        /*
         * Test 1: Test with one occurrence of the odd occurring
         *         number
         */
        int[] array1 = {12,3,4,4,3,1,1};
        assert 12 == element_odd_times(array1);

        /*
         * Test 2: Test with more than one occurrence of the odd
         *         occurring number
         */
        int[] array2 = {12,12,12,3,4,4,3,1,1};
        assert 12 == element_odd_times(array2);

        /*
         * Test 3: Test with more than one occurrence of the odd
         *         occurring number in an array of negative numbers
         */
        int[] array3 = {-12,-12,-12,-3,-4,-4,-3,-1,-1};
        assert -12 == element_odd_times(array3);

        /*
         * Test 4: Test with only one number in the array
         */
        int[] array4 = {12};
        assert 12 == element_odd_times(array4);
    }
}


text:
package org.sat4j.minisat.constraints.card;

import java.io.Serializable;

import org.sat4j.minisat.constraints.cnf.Lits;
import org.sat4j.minisat.constraints.cnf.UnitClauses;
import org.sat4j.minisat.core.Constr;
import org.sat4j.minisat.core.ILits;
import org.sat4j.minisat.core.Undoable;
import org.sat4j.minisat.core.UnitPropagationListener;
import org.sat4j.specs.ContradictionException;
import org.sat4j.specs.IVecInt;

public class MinWatchCard implements Constr, Undoable, Serializable {

	private static final long serialVersionUID = 1L;

	public static final boolean ATLEAST = true;

	public static final boolean ATMOST = false;

	/**
	 * degree of the cardinality constraint
	 */
	protected int degree;

	/**
	 * literals involved in the constraint
	 */
	private final int[] lits;

	/**
	 * contains the sign of the constraint : ATLEAT or ATMOST
	 */
	private boolean moreThan;

	/**
	 * contains the sum of the coefficients of the watched literals
	 */
	protected int watchCumul;

	/**
	 * Vocabulary of the constraint
	 */
	private final ILits voc;

	/**
	 * Constructs and normalizes a cardinality constraint. used by
	 * minWatchCardNew in the non-normalized case.
	 *
	 * @param voc
	 *            vocabulary used by the constraint
	 * @param ps
	 *            literals involved in the constraint
	 * @param moreThan
	 *            should be ATLEAST or ATMOST;
	 * @param degree
	 *            degree of the constraint
	 */
	public MinWatchCard(ILits voc, IVecInt ps, boolean moreThan, int degree) {
		// On met en place les valeurs
		this.voc = voc;
		this.degree = degree;
		this.moreThan = moreThan;

		// On simplifie ps
		int[] index = new int[voc.nVars() * 2 + 2];
		// Fresh array should have all elements set to 0

		// On repertorie les litt?raux utiles
		for (int i = 0; i < ps.size(); i++) {
			int p = ps.get(i);
			if (index[p ^ 1] == 0) {
				index[p]++;
			} else {
				index[p ^ 1]--;
			}
		}
		// On supprime les litt?raux inutiles
		int ind = 0;
		while (ind < ps.size()) {
			if (index[ps.get(ind)] > 0) {
				index[ps.get(ind)]--;
				ind++;
			} else {
				// ??
				if ((ps.get(ind) & 1) != 0)
					this.degree--;
				ps.delete(ind);
			}
		}

		// On copie les litt?raux de la contrainte
		lits = new int[ps.size()];
		ps.moveTo(lits);

		// On normalise la contrainte au sens de Barth
		normalize();

	}

	/**
	 * Constructs and normalizes a cardinality constraint. used by
	 * MinWatchCardPB.normalizedMinWatchCardNew() in the normalized case.

	 * Should not be used if parameters are not already
	 * normalized

	 * This constraint is always an ATLEAST constraint.
	 *
	 * @param voc
	 *            vocabulary used by the constraint
	 * @param ps
	 *            literals involved in the constraint
	 * @param degree
	 *            degree of the constraint
	 */
	protected MinWatchCard(ILits voc, IVecInt ps, int degree) {
		// On met en place les valeurs
		this.voc = voc;
		this.degree = degree;
		this.moreThan = ATLEAST;

		// On copie les litt?raux de la contrainte
		lits = new int[ps.size()];
		ps.moveTo(lits);

	}

	/**
	 * computes the reason for a literal
	 *
	 * @param p
	 *            falsified literal (or Lit.UNDEFINED)
	 * @param outReason
	 *            the reason to be computed. Vector of literals.
	 * @see Constr#calcReason(int p, IVecInt outReason)
	 */
	public void calcReason(int p, IVecInt outReason) {
		for (int i = 0; i < lits.length; i++) {
			if (voc.isFalsified(lits[i])) {
				outReason.push(lits[i] ^ 1);
			}
		}
	}

	/**
	 * Returns the activity of the constraint
	 *
	 * @return activity value of the constraint
	 * @see Constr#getActivity()
	 */
	public double getActivity() {
		// TODO getActivity
		return 0;
	}

	/**
	 * Increments activity of the constraint
	 *
	 * @param claInc
	 *            value to be added to the activity of the constraint
	 * @see Constr#incActivity(double claInc)
	 */
	public void incActivity(double claInc) {
		// TODO incActivity
	}

	/**
	 * Returns wether the constraint is learnt or not.
	 *
	 * @return false : a MinWatchCard cannot be learnt.
	 * @see Constr#learnt()
	 */
	public boolean learnt() {
		return false;
	}

	/**
	 * Simplifies the constraint w.r.t. the assignments of the literals
	 *
	 * @param voc
	 *            vocabulary used
	 * @param ps
	 *            literals involved
	 * @return value to be added to the degree. This value is less than or equal
	 *         to 0.
	 */
	protected static int linearisation(ILits voc, IVecInt ps) {
		// Stockage de l'influence des modifications
		int modif = 0;

		for (int i = 0; i < ps.size();) {
			// on verifie si le litteral est affecte
			if (voc.isUnassigned(ps.get(i))) {
				i++;
			} else {
				// Si le litteral est satisfait,
				// ?a revient ? baisser le degr?
				if (voc.isSatisfied(ps.get(i))) {
					modif--;
				}
				// dans tous les cas, s'il est assign?,
				// on enleve le ieme litteral
				ps.set(i, ps.last());
				ps.pop();
			}
		}

		// DLB: inutile?
		// ps.shrinkTo(nbElement);
		assert modif <= 0;

		return modif;
	}

	/**
	 * Returns if the constraint is the reason for a unit propagation.
	 *
	 * @return true
	 * @see Constr#locked()
	 */
	public boolean locked() {
		// TODO locked
		return true;
	}

	/**
	 * Constructs a cardinality constraint with a minimal set of watched
	 * literals Permet la cr?ation de contrainte de cardinalit? ? observation
	 * minimale
	 *
	 * @param s
	 *            tool for propagation
	 * @param voc
	 *            vocalulary used by the constraint
	 * @param ps
	 *            literals involved in the constraint
	 * @param moreThan
	 *            sign of the constraint. Should be ATLEAST or ATMOST.
	 * @param degree
	 *            degree of the constraint
	 * @return a new cardinality constraint, null if it is a tautology
	 * @throws ContradictionException
	 */
	public static Constr minWatchCardNew(UnitPropagationListener s, ILits voc,
			IVecInt ps, boolean moreThan, int degree)
			throws ContradictionException {

		int mydegree = degree + linearisation(voc, ps);

		if (ps.size() < mydegree) {
			throw new ContradictionException();
		} else if (ps.size() == mydegree) {
			for (int i = 0; i < ps.size(); i++)
				if (!s.enqueue(ps.get(i))) {
					throw new ContradictionException();
				}
			return new UnitClauses(ps);
		}

		// La contrainte est maintenant cr??e
		MinWatchCard retour = new MinWatchCard(voc, ps, moreThan, mydegree);

		if (retour.degree <= 0)
			return null;

		retour.computeWatches();

		retour.computePropagation(s);

		return retour;
	}

	/**
	 * normalize the constraint (cf. P.Barth normalization)
	 */
	public final void normalize() {
		// Gestion du signe
		if (!moreThan) {
			// On multiplie le degr? par -1
			this.degree = 0 - this.degree;
			// On r?vise chaque litt?ral
			for (int indLit = 0; indLit < lits.length; indLit++) {
				lits[indLit] = lits[indLit] ^ 1;
				this.degree++;
			}
			this.moreThan = true;
		}
	}

	/**
	 * propagates the value of a falsified literal
	 *
	 * @param s
	 *            tool for literal propagation
	 * @param p
	 *            falsified literal
	 * @return false if an inconistency is detected, else true
	 */
	public boolean propagate(UnitPropagationListener s, int p) {

		// Si la contrainte est responsable de propagation unitaire
		if (watchCumul == degree) {
			voc.watch(p, this);
			return false;
		}

		// Recherche du litt?ral falsifi?
		int indFalsified = 0;
		while ((lits[indFalsified] ^ 1) != p)
			indFalsified++;
		assert watchCumul > degree;

		// Recherche du litt?ral swap
		int indSwap = degree + 1;
		while (indSwap < lits.length && voc.isFalsified(lits[indSwap]))
			indSwap++;

		// Mise ? jour de la contrainte
		if (indSwap == lits.length) {
			// Si aucun litt?ral n'a ?t? trouv?
			voc.watch(p, this);
			// La limite est atteinte
			watchCumul--;
			assert watchCumul == degree;
			voc.undos(p).push(this);

			// On met en queue les litt?raux impliqu?s
			for (int i = 0; i <= degree; i++)
				if ((p != (lits[i] ^ 1)) && !s.enqueue(lits[i], this))
					return false;

			return true;
		}
		// Si un litt?ral a ?t? trouv? on les ?change
		int tmpInt = lits[indSwap];
		lits[indSwap] = lits[indFalsified];
		lits[indFalsified] = tmpInt;

		// On observe le nouveau litt?ral
		voc.watch(tmpInt ^ 1, this);

		return true;
	}

	/**
	 * Removes a constraint from the solver
	 *
	 * @since 2.1
	 */
	public void remove(UnitPropagationListener upl) {
		for (int i = 0; i < Math.min(degree + 1, lits.length); i++) {
			voc.watches(lits[i] ^ 1).remove(this);
		}
	}

	/**
	 * Rescales the activity value of the constraint
	 *
	 * @param d
	 *            rescale factor
	 */
	public void rescaleBy(double d) {
		// TODO rescaleBy
	}

	/**
	 * simplifies the constraint
	 *
	 * @return true if the constraint is satisfied, else false
	 */
	public boolean simplify() {
		// Calcul de la valeur actuelle
		for (int i = 0, count = 0; i < lits.length; i++)
			if (voc.isSatisfied(lits[i]) && (++count == degree))
				return true;

		return false;
	}

	/**
	 * Returns a string representation of the constraint.
	 *
	 * @return representation of the constraint.
	 */
	@Override
	public String toString() {
		StringBuffer stb = new StringBuffer();
		stb.append("Card (" + lits.length + ") : ");
		if (lits.length > 0) {
			// if (voc.isUnassigned(lits[0])) {
			stb.append(Lits.toString(this.lits[0]));
			stb.append("[");
			stb.append(voc.valueToString(lits[0]));
			stb.append("@");
			stb.append(voc.getLevel(lits[0]));
			stb.append("]");
			stb.append(" "); //$NON-NLS-1$
			// }
			for (int i = 1; i < lits.length; i++) {
				// if (voc.isUnassigned(lits[i])) {
				stb.append(" + "); //$NON-NLS-1$
				stb.append(Lits.toString(this.lits[i]));
				stb.append("[");
				stb.append(voc.valueToString(lits[i]));
				stb.append("@");
				stb.append(voc.getLevel(lits[i]));
				stb.append("]");
				stb.append(" "); //$NON-NLS-1$
				// }
			}
			stb.append(">= "); //$NON-NLS-1$
			stb.append(this.degree);
		}
		return stb.toString();
	}

	/**
	 * Updates information on the constraint in case of a backtrack
	 *
	 * @param p
	 *            unassigned literal
	 */
	public void undo(int p) {
		// Le litt?ral observ? et falsifi? devient non assign?
		watchCumul++;
	}

	public void setLearnt() {
		throw new UnsupportedOperationException();
	}

	public void register() {
		throw new UnsupportedOperationException();
	}

	public int size() {
		return lits.length;
	}

	public int get(int i) {
		return lits[i];
	}

	public void assertConstraint(UnitPropagationListener s) {
		throw new UnsupportedOperationException();
	}

	protected void computeWatches() {
		int indSwap = lits.length;
		int tmpInt;
		for (int i = 0; i <= degree && i < indSwap; i++) {
			while (voc.isFalsified(lits[i]) && --indSwap > i) {
				tmpInt = lits[i];
				lits[i] = lits[indSwap];
				lits[indSwap] = tmpInt;
			}

			// Si le litteral est observable
			if (!voc.isFalsified(lits[i])) {
				watchCumul++;
				voc.watch(lits[i] ^ 1, this);
			}
		}
		if (learnt()) {
			// chercher tous les litteraux a regarder
			// par ordre de niveau decroissant
			int free = 1;
			while ((watchCumul <= degree) && (free > 0)) {
				free = 0;
				// regarder le litteral falsifie au plus bas niveau
				int maxlevel = -1, maxi = -1;
				for (int i = watchCumul; i < lits.length; i++) {
					if (voc.isFalsified(lits[i])) {
						free++;
						int level = voc.getLevel(lits[i]);
						if (level > maxlevel) {
							maxi = i;
							maxlevel = level;
						}
					}
				}
				if (free > 0) {
					assert maxi >= 0;
					voc.watch(lits[maxi] ^ 1, this);
					tmpInt = lits[maxi];
					lits[maxi] = lits[watchCumul];
					lits[watchCumul] = tmpInt;
					watchCumul++;
					free--;
					assert free >= 0;
				}
			}
			assert lits.length == 1 || watchCumul > 1;
		}

	}

	protected MinWatchCard computePropagation(UnitPropagationListener s)
			throws ContradictionException {

		// Si on a des litteraux impliques
		if (watchCumul == degree) {
			for (int i = 0; i < lits.length; i++)
				if (!s.enqueue(lits[i])) {
					throw new ContradictionException();
				}
			return null;
		}

		// Si on n'observe pas suffisamment
		if (watchCumul < degree) {
			throw new ContradictionException();
		}
		return this;
	}

	public int[] getLits() {
		int[] tmp = new int[size()];
		System.arraycopy(lits, 0, tmp, 0, size());
		return tmp;
	}

	public ILits getVocabulary() {
		return voc;
	}

	@Override
	public boolean equals(Object card) {
		if (card == null) {
			return false;
		}
		try {
			MinWatchCard mcard = (MinWatchCard) card;
			if (mcard.degree != degree)
				return false;
			if (lits.length != mcard.lits.length)
				return false;
			boolean ok;
			for (int lit : lits) {
				ok = false;
				for (int lit2 : mcard.lits)
					if (lit == lit2) {
						ok = true;
						break;
					}
				if (!ok)
					return false;
			}
			return true;
		} catch (ClassCastException e) {
			return false;
		}
	}

	@Override
	public int hashCode() {
		long sum = 0;
		for (int p : lits) {
			sum += p;
		}
		sum += degree;
		return (int) sum / (lits.length + 1);
	}

	/**
	 * @since 2.1
	 */
	public void forwardActivity(double claInc) {
		// do nothing
	}

	public boolean canBePropagatedMultipleTimes() {
		return true;
	}
}


text:
Migrate Addons

Source Version

                <select class="selectbox" name="blVerSrc" ng-model="$parent.blVerSrc" ng-options="key for key in blVerList">
                </select>

Target Version

                <select class="selectbox" name="blVerTgt" ng-model="$parent.blVerTgt" ng-options="key for key in blVerList | filter: key='!'+blVerSrc">
                </select>

                    Migrate

                    {{blamTranslate('Close');}}


text:
using System;

namespace CoCSharp.Data.Csv
{
    /// <summary>
    ///
    /// </summary>
    public class CsvSerializerSettings
    {
        /// <summary>
        ///
        /// </summary>
        public CsvSerializerSettings()
        {
            /*  Should state the way to serialize or deserialize .csv files.
             */
            throw new NotImplementedException();
        }
    }
}


text:
from django import forms
from django.conf import settings
from django.db.models import Sum
from django.db.models import Q
from django_mako_plus.controller import view_function, RedirectException
from django.http import HttpResponse, HttpResponseRedirect, Http404
from homepage import models as hmod
from lib.filters import *
from lib import get_fake_request, prepare_fake_meta
from lib.mailer import send_html_mail
from lib.ckeditor import ckEditorWidget
from forum import models as fmod
from . import templater, prepare_params
import re

@view_function
def process_request(request):
  '''Main thread view'''
  # check user permissions and prepare the params
  params = prepare_params(request)

  # get the thread the user is after
  try:
    thread = fmod.Thread.objects.get(pk=request.urlparams[0])
  except (fmod.Thread.DoesNotExist, ValueError, TypeError):
    raise RedirectException('/forum/')

  # handle the form
  comment_form = CommentForm(request)
  if request.method == 'POST':
    comment_form = CommentForm(request, request.POST, request.FILES)
    if comment_form.is_valid():
      # create the comment, and add any files
      comment = fmod.Comment(user=request.user, thread=thread)
      comment.comment = comment_form.cleaned_data['comment']
      comment.save()
      if comment_form.cleaned_data['file1']:
        cf = hmod.UploadedFile()
        cf.filename = comment_form.cleaned_data['file1'].name
        cf.contenttype = comment_form.cleaned_data['file1'].content_type
        cf.size = comment_form.cleaned_data['file1'].size
        cf.filebytes = comment_form.cleaned_data['file1'].read()
        cf.save()
        comment.files.add(cf)

      # send the emails
      send_comment_email_immediate(request, comment)

      # forward to the comment so we don't get a double post on reload
      return HttpResponseRedirect('/forum/thread/%s#comment_%s' % (thread.pk, comment.pk))  # redirect so the user doesn't accidentally post again by hitting refresh

  # render the template
  params['comment_form'] = comment_form
  params['thread'] = thread
  params['comments'] = thread.comments.order_by('created')
  return templater.render_to_response(request, 'thread.html', params)

class CommentForm(forms.Form):
  '''Form to post new comment'''
  comment = forms.CharField()  # recreated in __init__ below
  file1 = forms.FileField(label="Attach a File:", required=False)

  def __init__(self, request, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['comment'] = forms.CharField(label="", max_length=4000, required=True, widget=ckEditorWidget(request, toolbar='be_small', attrs={ 'style': 'height: 250px;' }))

  def clean_file1(self):
    if self.cleaned_data['file1']:
      if self.cleaned_data['file1'].size > fmod.MAX_COMMENT_FILE_SIZE:
        raise forms.ValidationError('The attached file is above the limit of %.1f KB.' % (fmod.MAX_COMMENT_FILE_SIZE / 1024))
    return self.cleaned_data['file1']

#####################################################
###   Ajax endpoint to vote on a comment

@view_function
def vote(request):
  # check user permissions and prepare the params
  params = prepare_params(request)

  # handle vote button
  comment = fmod.Comment.objects.get(id=request.REQUEST.get('id'))

  # create/modify the vote ticket
  vt, created = fmod.VoteTicket.objects.get_or_create(user=request.user, comment=comment)
  vt.points = 1 if request.REQUEST.get('vote') == 'up' else 0
  vt.save()

  # recalculate the total votes on the item by doing a sum query
  comment.vote = fmod.VoteTicket.objects.filter(comment=comment).aggregate(Sum('points'))['points__sum']
  comment.save()

  # return the comment vote
  return HttpResponse(comment.vote)

###################################################
###   Downloads/views an attachment to a comment

@view_function
def attachment(request):
  # check user permissions and prepare the params
  params = prepare_params(request)

  # get the cf
  try:
    cf = hmod.UploadedFile.objects.get(id=request.urlparams[0])
  except (ValueError, hmod.UploadedFile.DoesNotExist):
    raise Http404

  # return the response
  return cf.get_response(attachment=request.urlparams[1] != 'inline')

#############################################
###   Sends notifications for new comments

# parses the message id created in the method below
RE_MESSAGE_ID = re.compile('c(\d+)_([^@]+)@island.byu.edu')

def send_comment_email_immediate(request, comment):
  '''Sends email out for a given comment'''
  thread = comment.thread

  # create the unique message id, and add headers
  headers = {}
  headers['Message-ID'] = '<c%i_%s@island.byu.edu>' % (comment.id, thread.get_hash().hexdigest())  # if we change this, we need to change the regex above
  headers['Reply-To'] = '%s@island.byu.edu' % thread.topic.key
  headers['List-Id'] = '<%s.island.byu.edu>' % thread.topic.key
  headers['List-Help'] = '<https://island.byu.edu/forum/index/help/>'
  headers['List-Post'] = headers['Reply-To']
  subject = thread.title

  # reference it to the first comment in the thread.  Some email clients use References, some use In-Reply-To
  first_comment = fmod.Comment.objects.filter(thread=thread).order_by('created')[0]
  if first_comment != comment:
    subject = 'Re: %s' % subject
    headers['References'] = '<c%i_%s@island.byu.edu>' % (first_comment.id, thread.get_hash().hexdigest())
    headers['In-Reply-To'] = headers['References']

  # I'm doing this with SQL because I don't know how to make Django do it with the either-or situation
  # It's also more explicit this way so we know exactly who will be getting emails
  # Here's who gets emails here:
  #   1. Users with a TopicNotification record for the thread.topic set to 'immediate'.
  #   2. Users without a Topic Notification record for the thread.topic - i.e. NOT EXISTS.
  #
  params_list = []
  for user in hmod.SiteUser.objects.raw("""
    SELECT u.*
    FROM homepage_siteuser AS u
    WHERE EXISTS (
        SELECT *
        FROM forum_topicnotification AS tn
        WHERE tn.user_id=u.id
          AND tn.topic_id=%s
          AND tn.notification='immediate'
    ) OR NOT EXISTS (
        SELECT notification
        FROM forum_topicnotification AS tn2
        WHERE tn2.user_id=u.id
          AND tn2.topic_id=%s
    )
  """, (thread.topic.id, thread.topic.id)):
    # if we don't have an email for this user, skip it
    if not user.email:
      continue

    # create a unique unsubscribe hash for this thread and user - this prevents hackers from unsubscribing people without the link
    m = thread.get_hash()
    m.update((user.email or 'defaultemail').encode('utf8'))  # add some user info to it

    # add parameters for this email
    params_list.append({
      'to_name': user.get_full_name(),
      'to_email': user.email,
      'to_id': user.id,
      'subject': subject,
      'comment': comment.comment,
      'comment_name': comment.user.get_full_name(),
      'comment_email': comment.user.email,
      'topic_title': thread.topic.title,
      'topic_key': thread.topic.key,
      'thread_id': thread.id,
      'unsubscribe_hash': m.hexdigest(),
    })

  # create the fake meta for celery
  if isinstance(request, dict):  # this occurs when called from the exim4 handler script
    meta = request
  else:
    meta = prepare_fake_meta(request)

  # call the html mailer with the params list and our email template
  # this needs to be switched to a celery call so it runs offline
  send_html_mail(meta, 'forum', 'comment.email.immediate.htm', [ cf.id for cf in comment.files.all() ], params_list, headers)


text:
package org.apache.hadoop.hive.ql.ddl.view.materialized.alter.rebuild;

import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.metastore.api.LockState;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.ddl.DDLSemanticAnalyzerFactory.DDLType;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager;
import org.apache.hadoop.hive.ql.lockmgr.LockException;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.CalcitePlanner;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.ParseUtils;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Analyzer for alter materialized view rebuild commands.
 */
@DDLType(types = HiveParser.TOK_ALTER_MATERIALIZED_VIEW_REBUILD)
public class AlterMaterializedViewRebuildAnalyzer extends CalcitePlanner {
  private static final Logger LOG = LoggerFactory.getLogger(AlterMaterializedViewRebuildAnalyzer.class);

  public AlterMaterializedViewRebuildAnalyzer(QueryState queryState) throws SemanticException {
    super(queryState);
  }

  @Override
  public void analyzeInternal(ASTNode root) throws SemanticException {
    if (mvRebuildMode != MaterializationRebuildMode.NONE) {
      super.analyzeInternal(root);
      return;
    }

    ASTNode tableTree = (ASTNode) root.getChild(0);
    TableName tableName = getQualifiedTableName(tableTree);
    if (ctx.enableUnparse()) {
      unparseTranslator.addTableNameTranslation(tableTree, SessionState.get().getCurrentDatabase());
      return;
    }
    ASTNode rewrittenAST = getRewrittenAST(tableName);

    mvRebuildMode = MaterializationRebuildMode.INSERT_OVERWRITE_REBUILD;
    mvRebuildDbName = tableName.getDb();
    mvRebuildName = tableName.getTable();

    LOG.debug("Rebuilding materialized view " + tableName.getNotEmptyDbTable());
    super.analyzeInternal(rewrittenAST);
  }

  private static final String REWRITTEN_INSERT_STATEMENT = "INSERT OVERWRITE TABLE %s %s";

  private ASTNode getRewrittenAST(TableName tableName) throws SemanticException {
    ASTNode rewrittenAST;
    // We need to go lookup the table and get the select statement and then parse it.
    try {
      Table table = getTableObjectByName(tableName.getNotEmptyDbTable(), true);
      if (!table.isMaterializedView()) {
        // Cannot rebuild not materialized view
        throw new SemanticException(ErrorMsg.REBUILD_NO_MATERIALIZED_VIEW);
      }

      // We need to use the expanded text for the materialized view, as it will contain
      // the qualified table aliases, etc.
      String viewText = table.getViewExpandedText();
      if (viewText.trim().isEmpty()) {
        throw new SemanticException(ErrorMsg.MATERIALIZED_VIEW_DEF_EMPTY);
      }

      Context ctx = new Context(queryState.getConf());
      String rewrittenInsertStatement = String.format(REWRITTEN_INSERT_STATEMENT,
          tableName.getEscapedNotEmptyDbTable(), viewText);
      rewrittenAST = ParseUtils.parse(rewrittenInsertStatement, ctx);
      this.ctx.addSubContext(ctx);

      if (!this.ctx.isExplainPlan() && AcidUtils.isTransactionalTable(table)) {
        // Acquire lock for the given materialized view. Only one rebuild per materialized view can be triggered at a
        // given time, as otherwise we might produce incorrect results if incremental maintenance is triggered.
        HiveTxnManager txnManager = getTxnMgr();
        LockState state;
        try {
          state = txnManager.acquireMaterializationRebuildLock(
              tableName.getDb(), tableName.getTable(), txnManager.getCurrentTxnId()).getState();
        } catch (LockException e) {
          throw new SemanticException("Exception acquiring lock for rebuilding the materialized view", e);
        }
        if (state != LockState.ACQUIRED) {
          throw new SemanticException(
              "Another process is rebuilding the materialized view " + tableName.getNotEmptyDbTable());
        }
      }
    } catch (Exception e) {
      throw new SemanticException(e);
    }
    return rewrittenAST;
  }
}


text:
package quasar.impl.datasources

import quasar.connector.ByteStore
import quasar.impl.storage.PrefixStore

import java.lang.String
import scala.{Array, Boolean, Byte, Option, Unit}

import cats.Applicative

import shapeless._

import scodec._

final class PrefixByteStores[F[_]: Applicative, K: Codec] private (
    store: PrefixStore.SCodec[F, K :: String :: HNil, Array[Byte]])
    extends ByteStores[F, K] {

  private class PrefixByteStore(prefix: K) extends ByteStore[F] {
    def lookup(key: String): F[Option[Array[Byte]]] =
      store.lookup(prefix :: key :: HNil)

    def insert(key: String, value: Array[Byte]): F[Unit] =
      store.insert(prefix :: key :: HNil, value)

    def delete(key: String): F[Boolean] =
      store.delete(prefix :: key :: HNil)
  }

  def get(prefix: K): F[ByteStore[F]] =
    Applicative[F].pure(new PrefixByteStore(prefix))

  def clear(prefix: K): F[Unit] =
    store.deletePrefixed(prefix :: HNil)
}

object PrefixByteStores {
  def apply[F[_]: Applicative, K: Codec](
      store: PrefixStore.SCodec[F, K :: String :: HNil, Array[Byte]])
      : ByteStores[F, K] =
    new PrefixByteStores(store)
}


text:
---
extends: _layouts.post
section: content
title: The Great Facade
date: 2013-12-11
created_at: 2013-12-10T23:45:45.000Z
updated_at: 2014-01-03T16:32:19.000Z
published_at: 2013-12-11T00:26:53.000Z
description: The Great Facade
cover_image: /assets/img/post-cover-image-2.png
---

Last time, I wrote about the new PHP mocking framework, [AspectMock](/blog/2013/07/24/are-you-mocking-me), which added the ability to test static methods, something that was previously untestable. Also, recently several members of the PHP community got into a heated discussion about the use of statics in the popular PHP framwork Laravel. So I decided to add my two cents to the discussion and post about the **actual** use of statics in Laravel.

I know what you're saying. "I thought you just told us static methods are hard for testing? Why not use AspectMock if you're using static methods?". Well, there is actually a good answer to what Laravel is doing and why it provides static methods to developers.

Facades. No, it's not pronounced fay-kades, it's fuh-sahds. Facade is an object-oriented pattern popularized by the [Gang of Four](http://en.wikipedia.org/wiki/Design_Patterns) that provides an interface to a large body of code, such as a class library. This design pattern is incredible powerful, and is used extensively in the popular PHP framework, [Laravel](http://laravel.com). By leveraging the Facade Pattern, Taylor Otwell, the framework's creator, provided developers the ability to use static methods of library classes for an "expressive, elegant syntax".

 Well, that's why the facade pattern is being used here! In laravel, you're not calling a static method of a library class. Instead, the method call is for a Facade, which forwards the call to the instantiated library class. This allows us to keep both the elegance of the syntax and keep our code testable. Let me show you how that works.

The following code is the main power behind Laravel's powerful facade structure. It is a PHP magic method that will intercept any static method that is not already defined in the class. It first grabs the underlying class library that has been instantiated in the IOC container or creates an instance of it to use. Then it sends the method called on the facade to the instance to handle.
```
<?php
/**
* Handle dynamic, static calls to the object.
*
* @param  string  $method
* @param  array   $args
* @return mixed
*/
public static function __callStatic($method, $args)
{
    $instance = static::resolveFacadeInstance(static::getFacadeAccessor());

    switch (count($args))
    {
        case 0:
            return $instance->$method();

        case 1:
            return $instance->$method($args[0]);

        case 2:
            return $instance->$method($args[0], $args[1]);

        case 3:
            return $instance->$method($args[0], $args[1], $args[2]);

        case 4:
            return $instance->$method($args[0], $args[1], $args[2], $args[3]);

        default:
            return call_user_func_array(array($instance, $method), $args);
    }
}
```

Now, let that sink in. It works with a real instantiated object, and isn't just flinging static method calls around all over the place. All of the provided laravel libraries operate as stateful instances of classes, which is not immediately aparent due to the syntax most commonly used in laravel applications.

So next time you `Mail::send()`, remember that you are actually in fact calling `Illuminate\Mail\Mailer`'s send method on an object in the IOC container.

####Update: 12/12/2013
Taylor has just included a doc page for Laravel's use of Facades on the [Laravel Website](http://laravel.com/docs/facades). I recommend you check it out as it includes a lot of great information about them, including usage, creating your own Facades, mocking Facades for testing, and a reference list of Laravel's built in Facade classes and which implementations they refer to.


text:
/********* BLLocationUpdates.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import "BLLocationService.h"

@interface BLLocationUpdates : CDVPlugin {
  // Member variables go here.
}

- (void)start:(CDVInvokedUrlCommand*)command;
@end

@implementation BLLocationUpdates

- (void) configure: (CDVInvokedUrlCommand *) command {
    BLLocationService* service = [BLLocationService locationService];

    service.url = [command.arguments objectAtIndex:0];
    service.maximumAge = [[command.arguments objectAtIndex:1] integerValue];
    service.parameters = [command.arguments objectAtIndex:2];
    service.headers = [command.arguments objectAtIndex:3];

    [service persist];

    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];

}

- (void) start:(CDVInvokedUrlCommand*)command
{

    NSError* error = nil;
    [[BLLocationService locationService] startWithError:&error];

    CDVPluginResult* result;
    if(error) {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    } else {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    }

    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) stop:(CDVInvokedUrlCommand *)command
{
    [[BLLocationService locationService] stop];
    [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];

    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

@end


text:
from snovault import (
    AuditFailure,
    audit_checker,
)

@audit_checker('replicate', frame=['experiment'])
def audit_status_replicate(value, system):
    '''
    As the experiment-replicate relationship is reverse calculated, the status checker for item
    is not sufficient to catch all cases of status mismatch between replicates and experiments.
    * in-progress replicate can't have experiment in [released, deleted, revoked]
    * released or revoked replicate must be in [released or revoked]
    * if experiment is deleted, replicate must be deleted
    '''

    rep_status = value['status']
    exp_status = value['experiment']['status']

    if ((rep_status in ['in progress'] and exp_status in ['released',
                                                          'revoked']) or
        (rep_status in ['released', 'revoked'] and
            exp_status not in ['released', 'revoked']) or
            (exp_status in ['deleted'] and rep_status not in ['deleted'])):
        #  If any of the three cases exist, there is an error
        detail = '{} replicate {} is in {} experiment'.format(
            rep_status,
            value['@id'],
            exp_status
        )
        yield AuditFailure('mismatched status', detail, level='INTERNAL_ACTION')
    return

# check that chip-seq experiments have antibody target matching the GM insert
# target of the biosample in the replicate (it could match on target name level
# or tags level
@audit_checker(
    'Replicate',
    frame=[
        'experiment',
        'experiment.target',
        'library',
        'library.biosample',
        'library.biosample.applied_modifications',
        'antibody',
        'antibody.targets'])
def audit_inconsistent_modifications_tag(value, system):
    if value['status'] in ['deleted', 'replaced', 'revoked']:
        return
    if 'target' not in value['experiment']:
        return
    if 'assay_term_id' not in value['experiment'] or \
       value['experiment']['assay_term_id'] != 'OBI:0000716':
        return  # not ChIP-seq
    exp_target = value['experiment']['target']
    if 'library' in value and 'biosample' in value['library']:
        matching_flag = False
        tags_names = get_biosample_modifications_tags(value)
        if len(tags_names) > 0:
            antibody_targets = get_ab_targets(value)
            for ab_target in antibody_targets:
                if 'recombinant protein' in ab_target['investigated_as'] or \
                   'tag' in ab_target['investigated_as']:
                    if ab_target['label'] in tags_names:
                        matching_flag = True
                        break
                if ab_target['name'] == exp_target['name']:
                    matching_flag = True
                    break
            if len(antibody_targets) > 0 and not matching_flag:
                detail = 'Replicate {}-{} in experiment {} '.format(
                    value['biological_replicate_number'],
                    value['technical_replicate_number'],
                    value['experiment']['@id']) + \
                    'specifies antibody {} that is inconsistent '.format(
                        value['antibody']['@id']) + \
                    'with biosample {} modification tags {}.'.format(
                    value['library']['biosample']['@id'],
                    tags_names)
                yield AuditFailure('inconsistent modification tag', detail, level='INTERNAL_ACTION')
    return

def get_ab_targets(replicate):
    uuids_set = set()
    targtes_to_return = []
    if 'antibody' in replicate and \
       replicate['antibody']['status'] not in ['deleted', 'replaced', 'revoked']:
        ab_targets = replicate['antibody']['targets']
        for t in ab_targets:
            if t['uuid'] not in uuids_set and t['status'] not in ['deleted', 'replaced', 'revoked']:
                uuids_set.add(t['uuid'])
                targtes_to_return.append(t)
    return targtes_to_return

def get_biosample_modifications_tags(replicate):
    tags_names = set()
    if 'library' in replicate and 'biosample' in replicate['library'] and \
       replicate['library']['status'] not in ['deleted', 'replaced', 'revoked']:
        biosample = replicate['library']['biosample']
        if biosample['status'] not in ['deleted', 'replaced', 'revoked']:
            if biosample.get('applied_modifications'):
                for modification in biosample.get('applied_modifications'):
                    if modification.get('status') not in ['deleted', 'replaced', 'revoked'] and \
                       modification.get('purpose') == 'tagging' and \
                       modification.get('introduced_tags'):
                        for tag in modification.get('introduced_tags'):
                            tags_names.add(tag.get('name'))
    return tags_names


text:
package config

import (
	"fmt"

	gce "cloud.google.com/go/compute/metadata"
)

// GceConfig aggregates all GCE related configuration parameters.
type GceConfig struct {
	Project       string
	Zone          string
	Cluster       string
	Instance      string
	MetricsPrefix string
}

// GetGceConfig builds GceConfig based on the provided prefix and metadata server available on GCE.
func GetGceConfig(metricsPrefix string) (*GceConfig, error) {
	if !gce.OnGCE() {
		return nil, fmt.Errorf("Not running on GCE.")
	}

	project, err := gce.ProjectID()
	if err != nil {
		return nil, fmt.Errorf("error while getting project id: %v", err)
	}

	zone, err := gce.Zone()
	if err != nil {
		return nil, fmt.Errorf("error while getting zone: %v", err)
	}

	cluster, err := gce.InstanceAttributeValue("cluster-name")
	if err != nil {
		return nil, fmt.Errorf("error while getting cluster name: %v", err)
	}

	instance, err := gce.Hostname()
	if err != nil {
		return nil, fmt.Errorf("error while getting instance hostname: %v", err)
	}

	return &GceConfig{
		Project:       project,
		Zone:          zone,
		Cluster:       cluster,
		Instance:      instance,
		MetricsPrefix: metricsPrefix,
	}, nil
}


text:
package com.github.sd4324530.fastweixin.message.req;

public final class MenuEvent extends BaseEvent {

    private String eventKey;

    public MenuEvent(String eventKey) {
        super();
        this.eventKey = eventKey;
    }

    public String getEventKey() {
        return eventKey;
    }

    @Override
    public String getEvent() {
        return super.getEvent();
    }

    @Override
    public String toString() {
        return "MenuEvent [eventKey=" + eventKey + ", toUserName=" + toUserName
                + ", fromUserName=" + fromUserName + ", createTime="
                + createTime + ", msgType=" + msgType + "]";
    }

}


text:
package com.iancaffey.access.google.maps;

import com.iancaffey.access.util.QueryStringBuilder;
import com.iancaffey.access.util.QueryToken;

/**
 * Bounds
 *
 * @author Ian Caffey
 * @since 1.0
 */
public class Bounds implements QueryToken {
    private final Coordinate northEast;
    private final Coordinate southWest;

    public Bounds(Coordinate northEast, Coordinate southWest) {
        if (northEast == null || southWest == null)
            throw new IllegalArgumentException();
        this.northEast = northEast;
        this.southWest = southWest;
    }

    public Coordinate getNorthEast() {
        return northEast;
    }

    public Coordinate getSouthWest() {
        return southWest;
    }

    @Override
    public int hashCode() {
        long bits = getNorthEast().hashCode();
        bits ^= getSouthWest().hashCode() * 31;
        return (((int) bits) ^ ((int) (bits >> 32)));
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Bounds && getNorthEast().equals(((Bounds) o).getNorthEast()) && getSouthWest().equals(((Bounds) o).getSouthWest());
    }

    @Override
    public String toToken() {
        return QueryStringBuilder.join(getNorthEast(), getSouthWest());
    }
}


text:
from collections import namedtuple
import datetime
import threading
from abc import ABCMeta, abstractmethod

class Trigger(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        self.next_run = None
        self.lock = threading.RLock()

    def fire_manually(self, ts):
        with self.lock:
            self.next_run = ts

    def should_fire(self, ts):
        return ts >= self.next_run

    def reset(self, ts):
        with self.lock:
            self.next_run = self.calculate_next_run(ts)

    @abstractmethod
    def calculate_next_run(self, ts):
        pass

class DailyTrigger(Trigger):
    def __init__(self, hour=0, minute=0):
        super(DailyTrigger, self).__init__()
        self.time = datetime.time(hour=hour, minute=minute)

    def calculate_next_run(self, ts):
        """
        :type ts datetime
        """
        running_time_today = datetime.datetime.combine(ts.date(), self.time)
        if ts >= running_time_today:
            # today's run has already passed
            return running_time_today + datetime.timedelta(days=1)
        else:
            return running_time_today

class PeriodicTrigger(Trigger):
    def __init__(self, timedelta):
        super(PeriodicTrigger, self).__init__()
        self.timedelta = timedelta

    def calculate_next_run(self, ts):
        return ts + self.timedelta

class WeeklyTrigger(Trigger):
    _DayOfTheWeek = namedtuple('DayOfTheWeek', ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
    DAYS_OF_THE_WEEK = _DayOfTheWeek(*range(7))

    def __init__(self, day_of_the_week=0, hour=0, minute=0):
        super(WeeklyTrigger, self).__init__()
        self.day_of_the_week = day_of_the_week
        self.time = datetime.time(hour=hour, minute=minute)

    def calculate_next_run(self, ts):
        """
        :type ts datetime
        """
        n_days_before_target = self.day_of_the_week - ts.weekday()
        date_to_run_this_week = ts.date() + datetime.timedelta(days=n_days_before_target)
        running_time_this_week = datetime.datetime.combine(date_to_run_this_week, self.time)
        if ts >= running_time_this_week:
            # this week's run has already passed
            return running_time_this_week + datetime.timedelta(days=7)
        else:
            return running_time_this_week

class ManualOnlyTrigger(Trigger):

    def calculate_next_run(self, ts):
        return datetime.datetime.max


text:
'use strict'

const { getEnvAuth } = require('./env/index')
const { jiraFetch } = require('./lib/jirafetch')
const { trycatch } = require('./lib/trycatch')

// https://atlassian-test.hq.k.grp/jira/plugins/servlet/restbrowser
// GET priorities (OK as anonymous, as long as no credentials is passed)
// GET myself (must be logged in)
// POST new issue
// POST new comment
// GET new comment
// PUT update to comment
// GET updated comment
// DELETE comment

async function main () {
  'use strict'
  const auth = getEnvAuth()

  const priorities = await jiraFetch(auth, 'GET', 'api/2/priority').then((json) => { return json.map(o => o.name) })
  console.log('JIRA priorities are:', priorities)

  const { name: myself } = await jiraFetch(auth)
  console.log('I am', myself)

  const { key: issuekey } = await jiraFetch(auth, 'POST', 'api/2/issue', {
    'fields': {
      'project': {'key': 'SPLPRJ'},
      'assignee': {'name': myself},
      'issuetype': {'name': 'Task'},
      'priority': {'name': priorities[1]},
      'summary': 'Submit issue through fetch',
      'description':
        '{panel:title=What would be the added value?|borderColor=#ccc| titleBGColor=#c2ffa2|bgColor=#fff}' +
        'fetch is available both at client and server sides' +
        '{panel}' +
        '{panel:title=Any details about the desired modification?|borderColor=#ccc| titleBGColor=#faacad|bgColor=#fff}' +
        'npm i node-fetch' +
        '{panel}'
    }
  })
  console.log('submitted issue:', issuekey, auth.jira + '/browse/' + issuekey)

  const { id: commentid } = await jiraFetch(auth, 'POST', 'api/2/issue/' + issuekey + '/comment', {
    'body': 'nice comment submitted through fetch'
  })
  console.log('submitted comment:', commentid)

  const { id: cid, body: cbody } = await jiraFetch(auth, 'GET', 'api/2/issue/' + issuekey + '/comment/' + commentid)
  console.log('comment is:', cid, cbody)

  const { id: pid, body: pbody } = await jiraFetch(auth, 'PUT', 'api/2/issue/' + issuekey + '/comment/' + commentid, {
    'body': 'nice comment updated through fetch'
  })
  console.log('comment is:', pid, pbody)

  const { id: uid, body: ubody } = await jiraFetch(auth, 'GET', 'api/2/issue/' + issuekey + '/comment/' + commentid)
  console.log('comment is:', uid, ubody)

  const res = await jiraFetch(auth, 'DELETE', 'api/2/issue/' + issuekey + '/comment/' + commentid)
  console.log('comment deleted with status:', res)
}

trycatch(main)


text:
<?php
	class Incident extends Model {
		public static function GetMap() {
			return array(
				'ID' => 'IncidentID',
				'Titel' => 'IncidentTitel',
				'Type' => 'IncidentType',
				'Kanaal' => 'IncidentKanaal',
				'Lijn' => 'IncidentLijn',
				'Prioriteit' => 'IncidentPrioriteit',
				'MedewerkerID' => 'IncidentMedewerker',
				'LaatstBekeken' => 'IncidentLaatstBekeken',
			);
		}

		public static function GetTable() {
			return 'incident';
		}
	}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class MessageFormatter
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class MessageFormatter
   ">
    <meta name="generator" content="docfx 2.21.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class MessageFormatter

Class that formats http request and response message data prior for serialization and deserialization

Inheritance

Object

MessageFormatter

Inherited Members

      Object.Equals(Object)

      Object.Equals(Object, Object)

      Object.GetHashCode()

      Object.GetType()

      Object.MemberwiseClone()

      Object.ReferenceEquals(Object, Object)

      Object.ToString()

Namespace: FakeHttp

Assembly: FakeHttp.dll

Syntax

public sealed class MessageFormatter

Constructors

    |
    Improve this Doc

    View Source

MessageFormatter()

Declaration

public MessageFormatter()

    |
    Improve this Doc

    View Source

MessageFormatter(IResponseCallbacks)

Declaration

public MessageFormatter(IResponseCallbacks callbacks)

Parameters

        Type
        Name
        Description

        IResponseCallbacks
        callbacks

Properties

    |
    Improve this Doc

    View Source

Callbacks

Declaration

public IResponseCallbacks Callbacks { get; }

Property Value

        Type
        Description

        IResponseCallbacks

Methods

    |
    Improve this Doc

    View Source

PackageResponse(HttpResponseMessage)

Convert the HttpResponseMessage into an object that is more serialization friendly

Declaration

public ResponseInfo PackageResponse(HttpResponseMessage response)

Parameters

        Type
        Name
        Description

        HttpResponseMessage
        response

The HttpResponseMessage

Returns

        Type
        Description

        ResponseInfo

A serializable object

Exceptions

        Type
        Condition

        ArgumentNullException

    |
    Improve this Doc

    View Source

ToName(HttpRequestMessage)

Deterministically generated file name for a request message

Declaration

public string ToName(HttpRequestMessage request)

Parameters

        Type
        Name
        Description

        HttpRequestMessage
        request

The request

Returns

        Type
        Description

        String

Filename

Exceptions

        Type
        Condition

        ArgumentNullException

    |
    Improve this Doc

    View Source

ToResourcePath(Uri)

Retrieve folder friendly representation of a Uri

Declaration

public string ToResourcePath(Uri uri)

Parameters

        Type
        Name
        Description

        Uri
        uri

The uri

Returns

        Type
        Description

        String

Resource path

Exceptions

        Type
        Condition

        ArgumentNullException

    |
    Improve this Doc

    View Source

ToShortName(HttpRequestMessage)

Deterministically generated file name for a request message

Declaration

public string ToShortName(HttpRequestMessage request)

Parameters

        Type
        Name
        Description

        HttpRequestMessage
        request

The request

Returns

        Type
        Description

        String

Filename

Exceptions

        Type
        Condition

        ArgumentNullException

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2015-2017 Microsoft
Generated by DocFX


text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.plaf.decorate;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import javax.swing.Icon;
import javax.swing.JList;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.tree.TreePath;

/**
 * A ListDecoration and TreeDecoration that
 * continually repaints itself as long as it is visible. This is used for
 * animating decorations.
 */
public class RepaintingDecoration implements ListTreeDecoration {

	private static class CellInfo {
		JList list;
		JTree tree;
		int row;
		Object value;

		CellInfo(JList list, int row) {
			this.row = row;
			this.value = row >= 0 && row < list.getModel().getSize() ? list
					.getModel().getElementAt(row) : null;
			this.list = list;
		}

		CellInfo(JTree tree, int row) {
			this.row = row;
			TreePath path = tree.getPathForRow(row);
			this.value = path == null ? null : path.getLastPathComponent();
			this.tree = tree;
		}

		@Override
		public int hashCode() {
			return row;
		}

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof CellInfo))
				return false;
			CellInfo other = (CellInfo) obj;
			if (other.row != row)
				return false;
			if (other.list != list)
				return false;
			if (other.tree != tree)
				return false;
			if (!Objects.equals(value, other.value))
				return false;
			return true;
		}

		/**
		 *
		 * @return true if this CellInfo should persist and keep repainting.
		 *         False if the list/tree appears to have changed and this
		 *         CellInfo should be purged from the repeating timer.
		 */
		boolean repaint() {
			if (list != null) {
				Rectangle rowBounds = list.getCellBounds(row, row);
				if (rowBounds != null)
					list.repaint(rowBounds);
				if (rowBounds == null || !equals(new CellInfo(list, row))) {
					return false;
				}
				return true;
			}

			Rectangle rowBounds = tree.getRowBounds(row);
			if (rowBounds != null)
				tree.repaint(rowBounds);
			if (rowBounds == null || !equals(new CellInfo(tree, row))) {
				return false;
			}
			return true;
		}
	}

	Timer repaintTimer;
	ActionListener repaintListener = new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			CellInfo[] cells;
			synchronized (repaintingCells) {
				cells = repaintingCells.toArray(new CellInfo[repaintingCells
						.size()]);
				if (cells.length == 0) {
					repaintTimer.stop();
				}
			}
			for (int a = 0; a < cells.length; a++) {
				if (!cells[a].repaint()) {
					synchronized (repaintingCells) {
						repaintingCells.remove(cells[a]);
					}
				}
			}
		}
	};
	Set<CellInfo> repaintingCells = new HashSet<CellInfo>();
	protected final ListTreeDecoration decoration;

	public RepaintingDecoration(Icon normalIcon, int repaintInterval) {
		this(new BasicDecoration(normalIcon), repaintInterval);
	}

	public RepaintingDecoration(ListTreeDecoration listTreeDecoration,
			int repaintInterval) {
		Objects.requireNonNull(listTreeDecoration);
		this.decoration = listTreeDecoration;
		repaintTimer = new Timer(repaintInterval, repaintListener);
	}

	@Override
	public Icon getIcon(JList list, Object value, int row, boolean isSelected,
			boolean cellHasFocus, boolean isRollover, boolean isPressed) {
		return decoration.getIcon(list, value, row, isSelected, cellHasFocus,
				isRollover, isPressed);
	}

	/**
	 * Returns whether this decoration should be visible.
	 *

	 * Do not override this method. To customize the visibility of this object,
	 * change the ListDecoration this decoration delegates to.
	 */
	@Override
	public final boolean isVisible(JList list, Object value, int row,
			boolean isSelected, boolean cellHasFocus) {
		boolean returnValue = decoration.isVisible(list, value, row,
				isSelected, cellHasFocus);
		synchronized (repaintingCells) {
			CellInfo cellInfo = new CellInfo(list, row);
			if (returnValue) {
				if (repaintingCells.add(cellInfo)
						&& (!repaintTimer.isRunning())) {
					repaintTimer.start();
				}
			} else {
				repaintingCells.remove(cellInfo);
			}
		}
		return returnValue;
	}

	@Override
	public ActionListener getActionListener(JList list, Object value, int row,
			boolean isSelected, boolean cellHasFocus) {
		return decoration.getActionListener(list, value, row, isSelected,
				cellHasFocus);
	}

	@Override
	public Point getLocation(JList list, Object value, int row,
			boolean isSelected, boolean cellHasFocus) {
		return decoration.getLocation(list, value, row, isSelected,
				cellHasFocus);
	}

	/**
	 * Returns whether this decoration should be visible.
	 *

	 * Do not override this method. To customize the visibility of this object,
	 * change the TreeDecoration this decoration delegates to.
	 */
	@Override
	public final boolean isVisible(JTree tree, Object value, boolean selected,
			boolean expanded, boolean leaf, int row, boolean hasFocus) {
		/*
		 * This method is final because this implementation is what guarantees
		 * this decoration will continually repeat. I overrode this by mistake
		 * when I wrote the PulsingTreeDecoration, and ended up with a timer
		 * that continually repainted even when the decoration was not actually
		 * visible. Instead the correct behavior is for the decoration field to
		 * have specialized visibility instructions.
		 */
		boolean returnValue = decoration.isVisible(tree, value, selected,
				expanded, leaf, row, hasFocus);
		synchronized (repaintingCells) {
			CellInfo cellInfo = new CellInfo(tree, row);
			if (returnValue) {
				if (repaintingCells.add(cellInfo)
						&& (!repaintTimer.isRunning())) {
					repaintTimer.start();
				}
			} else {
				repaintingCells.remove(cellInfo);
			}
		}
		return returnValue;
	}

	@Override
	public Icon getIcon(JTree tree, Object value, boolean selected,
			boolean expanded, boolean leaf, int row, boolean isRollover,
			boolean isPressed) {
		return decoration.getIcon(tree, value, selected, expanded, leaf, row,
				isRollover, isPressed);
	}

	@Override
	public ActionListener getActionListener(JTree tree, Object value,
			boolean selected, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {
		return decoration.getActionListener(tree, value, selected, expanded,
				leaf, row, hasFocus);
	}
}


text:
module Jasonette
  class Action < Jasonette::Base
    property :options
    property :success
    property :error

    def trigger name, &block
      with_attributes do
        set! "trigger", name
        encode(&block) if block_given?
      end
    end

    def render!
      set! "type", "$render"
    end

    def reload!
      set! "type", "$reload"
    end

    def success &block
      @success = Jasonette::Action.new(context) do
        block_given? ? encode(&block) : render!
      end
      self
    end

    def error &block
      @error = Jasonette::Action.new(context, &block)
      self
    end
  end
end


text:
% NavigationStatusSettleNetTurns:  motor cortex state to calculate the
% net distance and clockwiseness of all previously simulated turns,
% as part of settling simulated position to previous physical position
classdef NavigationStatusSettleNetTurns < NavigationStatus

    properties
        steps
        behavior
        clockwiseness
    end
    methods
        function obj = NavigationStatusSettleNetTurns(motorCortex, updateAll, lastStatus)
            obj = obj@NavigationStatus(motorCortex, updateAll, lastStatus);
        end
        function navigationStatus = nextStatus(obj)
            obj.debug();
            turnNeeded = obj.motorCortex.calculateNetSimulatedTurnsReversed();
            obj.steps = obj.motorCortex.turnDistance;
            obj.clockwiseness = obj.motorCortex.clockwiseness;
            if (turnNeeded)
                obj.behavior = obj.motorCortex.reverseSimulatedTurnBehavior;
                obj.moving = true;
                obj.motorCortex.turn();
                obj.motorCortex.updateSimulatedBehaviorHistory(obj.motorCortex.reverseSimulatedTurnBehavior, obj.steps);
                navigationStatus = NavigationStatusPendingSimulationOff(obj.motorCortex, obj.updateAll, obj);
                obj.setStatus(navigationStatus);
            else
                obj.behavior = obj.motorCortex.noBehavior;
                obj.moving = false;
                navigationStatus = ...
                    obj.immediateTransition(NavigationStatusPendingSimulationOff(obj.motorCortex, obj.updateAll, obj));
            end
        end
    end
end


text:
@interface UIRoundRectViewWithShadow : UIView

@property (retain, nonatomic) NSURL* imageUrl;
@property (retain, nonatomic) UIImage* image;

@end


text:
from functionaltest import FunctionalTest, snapshot_on_error

class test_2556_BrokenUsercode(FunctionalTest):

    @snapshot_on_error
    def test_newly_entered_formulae_appear_grey_then_results_in_black(self):
        # * Harold logs in to Dirigible and creates a new sheet
        self.login_and_create_new_sheet()

        # make recalc slow, so that we can be sure to see cells
        # passing through their intermediate 'sent to server
        # but not yet evaluated' state
        # Set 2,2 to ready to be sure this usercode change is made before
        # proceeding.
        self.prepend_usercode('import time\ntime.sleep(20.0)\nworksheet[2,2].formula="ready"')
        self.wait_for_cell_value(2, 2, 'ready', timeout_seconds=22)

        # check intermediate state then final state after entering a formula
        self.enter_cell_text(1, 2, '=123')
        self.wait_for_cell_shown_formula(1, 2, '=123', timeout_seconds=19)
        self.wait_for_cell_value(1, 2, '123', timeout_seconds=30)

    def test_broken_usercode_returns_as_much_as_it_can(self):
        # * Harold logs in to Dirigible and creates a new sheet
        self.login_and_create_new_sheet()

        original_usercode = self.get_usercode()

        # * He enters a constant and a formula in the sheet
        self.enter_cell_text(1, 1, 'abc')
        self.enter_cell_text(1, 2, '=123')
        self.wait_for_cell_value(1, 2, '123')

        # * He adds a usercode error before the constants get calculated
        self.prepend_usercode('x=1/0')

        self.enter_cell_text(2, 1, 'def')
        self.enter_cell_text(2, 2, '=456')
        self.wait_for_cell_shown_formula(2, 2, '=456')

        self.assert_cell_shown_formula(1, 1, 'abc')
        self.assert_cell_shown_formula(1, 2, '=123')
        self.assert_cell_shown_formula(2, 1, 'def')
        self.assert_cell_shown_formula(2, 2, '=456')

        # * He adds a usercode error between constants and formulae

        def insert(text):
            insertion_point = original_usercode.find('evaluate_formulae(worksheet)')
            return "%s\n%s\n%s" % (
                original_usercode[:insertion_point],
                text,
                original_usercode[insertion_point:],
            )

        usercode = insert('x=1/0\n')
        self.enter_usercode(usercode)

        self.enter_cell_text(3, 1, 'ghi')
        self.enter_cell_text(3, 2, '=789')
        self.wait_for_cell_shown_formula(3, 2, '=789')

        self.assertEquals(self.get_cell_text(1, 1), 'abc')
        self.assert_cell_shown_formula(1, 2, '=123')
        self.assertEquals(self.get_cell_text(2, 1), 'def')
        self.assertEquals(self.get_cell_text(2, 2), '=456')
        self.assertEquals(self.get_cell_text(3, 1), 'ghi')
        self.assertEquals(self.get_cell_text(3, 2), '=789')

        # * He adds a usercode error after formulae
        self.enter_usercode(original_usercode)
        self.append_usercode('x=1/0')

        self.enter_cell_text(4, 1, 'jkl')
        self.enter_cell_text(4, 2, '=100')
        self.wait_for_cell_value(4, 2, '100')

        self.assertEquals(self.get_cell_text(1, 1), 'abc')
        self.assertEquals(self.get_cell_text(1, 2), '123')
        self.assertEquals(self.get_cell_text(2, 1), 'def')
        self.assertEquals(self.get_cell_text(2, 2), '456')
        self.assertEquals(self.get_cell_text(3, 1), 'ghi')
        self.assertEquals(self.get_cell_text(3, 2), '789')
        self.assertEquals(self.get_cell_text(4, 1), 'jkl')
        self.assertEquals(self.get_cell_text(4, 2), '100')

        # \o/ hooray!