text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

  <!-- 启用mvc注解 -->
  <mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <!--json处理-->
        <bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

  <!-- 静态资源 -->
    <mvc:resources location="/statics/img/" mapping="/*/statics/image/**"/>
    <mvc:resources location="/statics/css/" mapping="/*/statics/css/**"/>
    <mvc:resources location="/statics/js/" mapping="/*/statics/js/**"/>
    <mvc:resources location="/statics/fonts-awesome/" mapping="/*/statics/fonts-awesome/**"/>
  <!-- 拦截器 -->

  <!-- 扫描spring组件支持的注解 -->
  <context:component-scan base-package="com.elearning"/>

  <!-- 视图解析器:定义视图的前缀后缀 -->
  <bean id="resourceView" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  	<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  	<property name="prefix" value="/WEB-INF/pages/"/>
  	<property name="suffix" value=".jsp"/>
  </bean>

  <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="10000000000"/>
</bean>
</beans>


text:
<!DOCTYPE html>
<html>
<head>
  <title>Test page showing a video with media session actions and metadata</title>
</head>
<body>
  <video id="video" controls loop>
    <source src="../bigbuck.webm">
  </video>
<script>
const video = document.getElementById('video');

// Called by the browser test to start playback. Note that the browser test
// needs to explicitly disable user gesture requirements for autoplay for this
// function to work.
function play() {
  video.play().then(_ => {
    setupMetadata();
    setupActionHandlers();
  });
}

function setupMetadata() {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: "Big Buck Bunny",
    artist: "Blender Foundation"
  });
}

function setupActionHandlers() {
  // Add empty action handlers to tell the browser we want to show all the
  // possible action buttons.
  function doNothing() {}

  navigator.mediaSession.setActionHandler('previoustrack', doNothing);
  navigator.mediaSession.setActionHandler('nexttrack', doNothing);
  navigator.mediaSession.setActionHandler('seekbackward', doNothing);
  navigator.mediaSession.setActionHandler('seekforward', doNothing);
  navigator.mediaSession.setActionHandler('play', _ => { video.play(); });
  navigator.mediaSession.setActionHandler('pause', _ => { video.pause(); });
}

function disablePictureInPicture() {
  video.disablePictureInPicture = true;
}

function enablePictureInPicture() {
  video.disablePictureInPicture = false;
}
</script>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
.PHONY: adapter advertising

adapter:
	BASEDIR=.. \
	FILE_FILTER=adapter \
	xAPI_FILTER="Provisioner" \
	xMETHOD_FILTER=Attach LOG_LEVEL=trace \
		go run ./srcgen/main.go full --debug

advertising:
	BASEDIR=.. \
	FILE_FILTER=advertising-api \
	xAPI_FILTER="Provisioner" \
	xMETHOD_FILTER=Attach LOG_LEVEL=trace \
	go run ./srcgen/main.go full --debug

mesh:
	BASEDIR=.. \
	FILE_FILTER=mesh-api \
	xAPI_FILTER="Provisioner" \
	xMETHOD_FILTER=Attach LOG_LEVEL=trace \
	go run ./srcgen/main.go full --debug

advertisement-monitor:
	BASEDIR=.. \
	FILE_FILTER=advertisement-monitor-api \
	xAPI_FILTER="Provisioner" \
	xMETHOD_FILTER=Attach LOG_LEVEL=trace \
	go run ./srcgen/main.go full --debug


text:
require 'quick_test_helper'
require 'support/resque_helpers'
require 'support/monitoring_helpers'
require 'minitest/autorun'
require 'resque'

lib_require 'monitoring/checker'
lib_require 'monitoring/queue_size_check'
lib_require 'monitoring/check_result'
rails_require 'models/resque_instance'
rails_require 'models/job'
rails_require 'models/running_job'
rails_require 'models/resques'

module Monitoring
end
class Monitoring::QueueSizeCheckTest < MiniTest::Test
  include ResqueHelpers
  include MonitoringHelpers

  def setup_resques(test1: {}, test2: {}, test3: :ignore)
    Redis.new.flushall
    Resques.new([
      add_jobs(jobs: test1, resque_instance: resque_instance("test1",:resque)),
      add_jobs(jobs: test2, resque_instance: resque_instance("test2",:resque2)),
      test3 == :exception ? ExceptionResque.new : nil
    ].compact)
  end

  def test_type
    assert Monitoring::QueueSizeCheck.ancestors.include?(Monitoring::Checker)
  end

  def test_jobs_in_queue
    resques = setup_resques(test1: { mail: 10, cache: 4 },
                            test2: { mail: 3, admin: 2 })
    check = Monitoring::QueueSizeCheck.new(resques: resques)

    results = check.check!.sort_by { |result| "#{result.resque_name}.#{result.scope}" }

    assert_check_result results[0], resque_name: "test1" , scope: "cache" , check_count: 4
    assert_check_result results[1], resque_name: "test1" , scope: "mail"  , check_count: 10
    assert_check_result results[2], resque_name: "test2" , scope: "admin" , check_count: 2
    assert_check_result results[3], resque_name: "test2" , scope: "mail"  , check_count: 3

  end

  def test_exception_on_one_redis
    resques = setup_resques(test1: { mail: 10 },
                            test2: { admin: 2 },
                            test3: :exception)
    check = Monitoring::QueueSizeCheck.new(resques: resques)

    exception = begin
                  check.check!
                  nil
                rescue => ex
                  ex
                end
    refute_nil exception,"Expected an exception to be raised"
    assert_exception exception, message_match: /exception_resque/,
                                backtrace_includes: /monitoring_helpers.*waiting_by_queue/
  end
end


text:
package lejos.internal.dbus;

import org.freedesktop.dbus.Path;
import org.freedesktop.dbus.UInt32;

public class PinAgent implements Agent {

	private String pin;

	public PinAgent(String pin) {
		this.pin = pin;
	}

    public void Authorize(Path device, String uuid) {
    	System.out.println("Authorize called");
    }

    public void ConfirmModeChange(String mode)  {
    	System.out.println("ConfirmModeChange called");
    }

    public void DisplayPasskey(Path device, UInt32 passkey, byte entered) {
    }

    public void RequestConfirmation(Path device, UInt32 passkey) {
    }

    public UInt32 RequestPasskey(Path device) {
    	System.out.println("Request pass key called for " + device);
        return null;
    }

    public String RequestPinCode(Path device)  {
    	System.out.println("Request pin code called for " + device);
        return pin;
    }

    public void Cancel() {
    	System.out.println("Cancel called");
    }

    public void Release() {
    	System.out.println("Release called");
    }

    public boolean isRemote() {
        return false;
    }

}


text:
<?php
namespace Neos\FluidAdaptor\View;

use Neos\FluidAdaptor;

/**
 * A generic Fluid View exception.
 *
 * @api
 */
class Exception extends FluidAdaptor\Exception
{
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.">
    <title tabindex="1">get started | p5.js</title>
    <link rel="stylesheet" href="/assets/css/all.css?v=db3be6">
    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inconsolata&display=swap" rel="stylesheet">

    <link rel="shortcut icon" href="/../assets/img/favicon.ico">
    <link rel="icon" href="/../assets/img/favicon.ico">

    Skip to content

Language Settings

English

Español

简体中文

한국어

Site Navigation

      <input class="sidebar-menu-btn" type="checkbox" id="sidebar-menu-btn" />

Home

Editor

Download

Donate

Get Started

Reference

Libraries

Learn

Examples

Books

Community

Showcase

Forum

GitHub

Twitter

Get Started

This page walks you through setting up a p5.js project and making your first sketch. The easiest way to start is using the  p5.js editor, you can open the web editor and can scroll down to  Your First Sketch. If you would like to work on the the desktop version of p5.js you can scroll down to downloading instructions.

Your First Sketch

Code snippet with ellipse

In the p5.js web editor you should find the following code:

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
}

After background(220); include this line of code: ellipse(50,50,80,80);.

Now your code should be like this:

Code snippet with ellipse

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  ellipse(50,50,80,80);
}

The line you just added draws an ellipse, with its center 50 pixels over from the left and 50 pixels down from the top, with a width and height of 80 pixels.

On the editor press play to display your code in action!

Note for screenreader users

If you are using a screen reader, you must turn on the accessible outputs in the p5 online editor, outside the editor you must add the accessibility library in your html. To learn more visitusing p5 with a screen reader tutorial.

If you've typed everything correctly, this will appear in the display window:

If nothing appears, the editor may be having trouble understanding what you've typed. If this happens, make sure that you've copied the example code exactly: the numbers should be contained within parentheses and have commas between each of them, the line should end with a semicolon, and ellipse has to be spelled correctly.

One of the most difficult things about getting started with programming is that you have to be very specific about the syntax. The browser isn't always smart enough to know what you mean, and can be quite fussy about the placement of punctuation. You'll get used to it with a little practice. In the bottom left of the editor you will find the console section. Here, you can find messages from the editor with details about any errors it encounters.

Code snippet with interaction

Next, we'll skip ahead to a sketch that's a little more exciting. Modify the last example to try this:

function setup() {
  createCanvas(400, 400);
}

function draw() {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}

This program creates a canvas that is 400 pixels wide and 400 pixels high, and then starts drawing white circles at the position of the mouse. When a mouse button is pressed, the circle color changes to black. Run the code, move the mouse, and click to experience it.

What Next?

Check out the learn page and examples page for more.

Watch The Coding Train and Kadenze video tutorials.

View the  reference for full documentation.

If you wish to use p5 with a screenreader, check out the p5 with a screenreader tutorial.

If you have used Processing in the past, read the Processing transition tutorial to learn how to convert from Processing to p5.js, and the main differences between them.

Setting up p5.js with an editor on your own computer

To run p5.js in your computer you will need a text editor. You can use the

             code editor
            of your choice. Instructions for getting set up with
             Sublime Text 2
             are included below, other good editor options include Brackets  and Atom. If you are a screen reader user and not using the p5 web editor, you may want to use Notepad++  or
            Eclipse.

Downloading a copy of the p5.js library

The easiest way to start is by using the empty example that comes with the
          p5.js complete
           download.

If you look in index.html, you'll notice that it links to the file p5.js. If you would like to use the minified version (compressed for faster page loading), change the link to p5.min.js.

<script src="../p5.min.js"></script>

Using a hosted version of the p5.js library

Alternatively, you can link to a p5.js file hosted online. All versions of p5.js are stored in a CDN (Content Delivery Network). You can find a history of these versions in the

            p5.js CDN. In this case you can change the link to:

<script src="https://cdn.jsdelivr.net/npm/p5@[p5_version]/lib/p5.js"></script>

A sample HTML page might look like this:

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/p5@[p5_version]/lib/p5.js"></script>
    <script src="sketch.js"></script>
  </head>
  <body>
    <main>
    </main>
  </body>
</html>

Environment

          Open Sublime. Go to the File menu and choose Open... and choose the folder that your html and js files are located in. On the left sidebar, you should find the folder name at the top, with a list of the files contained in the folder directly below.

          Click on your sketch.js file and it will open on the right where you can edit it.

          Open the index.html file in your browser by double clicking on it in your file manager or type: file:///the/file/path/to/your/html
           in the address bar to view your sketch.

Parts of this tutorial were adapted from the book, Getting Started with p5.js, by Lauren McCarthy, Casey Reas, and Ben Fry, O'Reilly / Make 2015. Copyright © 2015. All rights reserved. Last modified at the p5.js 2019 Contributors Conference.

Credits

 p5.js is currently led by Moira
          Turner and was created by Lauren
          McCarthy. p5.js is developed by a community of collaborators, with support from the Processing
          Foundation  and
        NYU ITP. Identity and graphic design by Jerel Johnson. ©
          Info.

  <object type="image/svg+xml" data="../assets/img/thick-asterisk-alone.svg" id="asterisk-design-element" aria-hidden="true">
  </object>

Processing Sister Sites

Processing

p5.js

Processing.py

Processing for Android

Processing for Pi

Processing Foundation

      Skip to main content


text:
module ActiveAdmin
  # Exception class to raise when there is an authorized access
  # exception thrown. The exception has a few goodies that may
  # be useful for capturing / recognizing security issues.
  class AccessDenied < StandardError
    attr_reader :user, :action, :subject

    def initialize(user, action, subject)
      @user, @action, @subject = user, action, subject

      super()
    end

    def message
      I18n.t("active_admin.access_denied.message")
    end
  end

  class Error < RuntimeError
  end

  class ErrorLoading < Error
    # Locates the most recent file and line from the caught exception's backtrace.
    def find_cause(folder, backtrace)
      backtrace.grep(/\/(#{folder}\/.*\.rb):(\d+)/){ [$1, $2] }.first
    end
  end

  class DatabaseHitDuringLoad < ErrorLoading
    def initialize(exception)
      file, line = find_cause(:app, exception.backtrace)

      super "Your file, #{file} (line #{line}), caused a database error while Active Admin was loading. This " +
            "is most common when your database is missing or doesn't have the latest migrations applied. To " +
            "prevent this error, move the code to a place where it will only be run when a page is rendered. " +
            "One solution can be, to wrap the query in a Proc. " +
            "Original error message: #{exception.message}"
    end

    def self.capture
      yield
    rescue *database_error_classes => exception
      raise new exception
    end

    private

    def self.database_error_classes
      @classes ||= []
    end
  end

  class DependencyError < ErrorLoading
  end

  class NoMenuError < KeyError
  end

  class GeneratorError < Error
  end

end


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';

import sinon from 'sinon';

const FEEDBACK = '[role="alert"]';
const FIELD = 'textarea';
const LABEL = 'label div:first';

moduleForComponent('cui-textarea', 'Integration | Component | cui textarea', {
  integration: true,

  beforeEach() {
    this.set('value', null);
  },
});

test('should render `--label`', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --label="Foo"}}
  `);

  // Assert
  assert.equal(this.$(LABEL).text().trim(), 'Foo');
});

test('should bind --fieldAutoCapitalize to field', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --fieldAutoCapitalize="none"}}
  `);

  // Assert
  assert.equal(this.$(FIELD).attr('autocapitalize'), 'none');
});

test('should bind --fieldDisabled to field', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --fieldDisabled=true}}
  `);

  // Assert
  assert.ok(this.$(FIELD).is(':disabled'));
});

test('should bind --fieldMaxLength to field', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --fieldMaxLength="10"}}
  `);

  // Assert
  assert.equal(this.$(FIELD).attr('maxlength'), '10');
});

test('should bind --fieldPlaceholder to field', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --fieldPlaceholder="10"}}
  `);

  // Assert
  assert.equal(this.$(FIELD).attr('placeholder'), '10');
});

test('should bind --fieldValue to field', function(assert) {
  assert.expect(1);

  // Arrange
  this.set('value', 'Foo');

  // Act
  this.render(hbs`{{cui-textarea --fieldValue=value}}`);

  // Assert
  assert.equal(this.$(FIELD).val(), 'Foo');
});

test('should show feedback when input is invalid', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --fieldRequired=true --onInput=(action (mut value))}}
  `);
  this.$(FIELD).val('').trigger('input');

  // Assert
  return wait().then(() => {
    assert.equal(this.$(FEEDBACK).length, 1);
  });
});

test('should not show feedback when input is valid', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`{{cui-textarea}}`);

  // Assert
  assert.equal(this.$(FEEDBACK).length, 0);
});

test('should set aria-invalid to true on the field when feedback is visible', function(assert) {
  assert.expect(1);

  // Arrange
  this.set('errorMessage', null);

  // Act
  this.render(hbs`
    {{cui-textarea --fieldRequired=true --onInput=(action (mut value))}}
  `);
  this.$(FIELD).val('').trigger('input');

  // Assert
  return wait().then(() => {
    assert.equal(this.$(FIELD).attr('aria-invalid'), 'true');
  });
});

test('should prevent inputting line break when `--willPreventLineBreaks` is true', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --willPreventLineBreaks=true --onInput=(action (mut value))}}
  `);
  this.$(FIELD).val('Foo\n').trigger('input');

  // Assert
  return wait().then(() => {
    assert.equal(this.get('value'), 'Foo');
  });
});

test('should resize textarea when the text overflows and `--willAutoResize` is true', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --willAutoResize=true --onInput=(action (mut value))}}
  `);

  const ORIG_HEIGHT = this.$(FIELD).height();

  // Act
  this.$(FIELD).val('Foo\n\n\n\n\n\n\n').trigger('input');

  // Assert
  return wait().then(() => {
    assert.notEqual(ORIG_HEIGHT, this.$(FIELD).height());
  });
});

test('should not resize textarea when the text overflows and `--willAutoResize` is false', function(assert) {
  assert.expect(1);

  // Act
  this.render(hbs`
    {{cui-textarea --onInput=(action (mut value))}}
  `);

  const ORIG_HEIGHT = this.$(FIELD).height();

  // Act
  this.$(FIELD).val('Foo\n\n\n\n\n\n\n').trigger('input');

  // Assert
  return wait().then(() => {
    assert.equal(ORIG_HEIGHT, this.$(FIELD).height());
  });
});

test('should fire an external action on input when `--onInput` is passed in', function(assert) {
  assert.expect(1);

  // Arrange
  const stub = sinon.stub();

  this.set('onInput', stub);

  // Act
  this.render(hbs`{{cui-textarea --onInput=(action onInput)}}`);
  this.$(FIELD).val('Foo').trigger('input');

  // Assert
  return wait().then(() => {
    assert.ok(stub.calledWith('Foo'));
  });
});


text:
<?php get_header(); ?>

     <?php if ( have_posts() ) : ?>

Résultat de la recherche pour : <?php echo get_search_query();
     ?>

     <?php while ( have_posts() ) : the_post(); ?>
           <?php
                get_template_part( 'content', 'search' );
                endwhile;
           // Affichage si pas de contenu trouvé
           else :
                get_template_part( 'content', 'none' );

           endif;
           ?>

<?php get_footer(); ?>


text: R&B Company


text:
$:.unshift File.dirname(__FILE__) + '/../../lib'

require 'rubygems'
require 'test/unit'

require 'validates_captcha'

begin
  require 'ruby-debug'
  Debugger.start
rescue LoadError
end

require 'active_record'

ActiveRecord::Base.logger = Logger.new(nil)
ActiveRecord::Schema.verbose = false
ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => ':memory:'
ActiveRecord::Schema.define :version => 1 do
  create_table :widgets do |t|
    t.string :name
  end
end

class Widget < ActiveRecord::Base
  include ValidatesCaptcha::ModelValidation

  attr_accessible :name
end


text:
#include <gtest/gtest.h>
#include <iostream>
#include <vector>
#include <utility>

#include <base_local_planner/map_cell.h>
#include <base_local_planner/map_grid.h>
#include <base_local_planner/trajectory.h>
#include <base_local_planner/trajectory_planner.h>
#include <base_local_planner/costmap_model.h>
#include <costmap_2d/costmap_2d.h>
#include <math.h>

#include <geometry_msgs/Point.h>
#include <base_local_planner/Position2DInt.h>

#include "wavefront_map_accessor.h"

using namespace std;

namespace base_local_planner {

class TrajectoryPlannerTest : public testing::Test {
  public:
    TrajectoryPlannerTest(MapGrid* g, WavefrontMapAccessor* wave, const costmap_2d::Costmap2D& map, std::vector<geometry_msgs::Point> footprint_spec);
    void correctFootprint();
    void footprintObstacles();
    void checkGoalDistance();
    void checkPathDistance();
    virtual void TestBody(){}

    MapGrid* map_;
    WavefrontMapAccessor* wa;
    CostmapModel cm;
    TrajectoryPlanner tc;
};

TrajectoryPlannerTest::TrajectoryPlannerTest(MapGrid* g, WavefrontMapAccessor* wave, const costmap_2d::Costmap2D& map, std::vector<geometry_msgs::Point> footprint_spec)
: map_(g), wa(wave), cm(map), tc(cm, map, footprint_spec, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0)
{}

void TrajectoryPlannerTest::footprintObstacles(){
  //place an obstacle
  map_->operator ()(4, 6).target_dist = 1;
  wa->synchronize();
  EXPECT_EQ(wa->getCost(4,6), costmap_2d::LETHAL_OBSTACLE);
  Trajectory traj(0, 0, 0, 0.1, 30);
  //tc->generateTrajectory(4.5, 4.5, M_PI_2, 0, 0, 0, 4, 0, 0, 4, 0, 0, DBL_MAX, traj, 2, 30);
  tc.generateTrajectory(4.5, 4.5, M_PI_2, 0, 0, 0, 4, 0, 0, 4, 0, 0, DBL_MAX, traj);
  //we expect this path to hit the obstacle
  EXPECT_FLOAT_EQ(traj.cost_, -1.0);

  //place a wall next to the footprint of the robot
  tc.path_map_(7, 1).target_dist = 1;
  tc.path_map_(7, 3).target_dist = 1;
  tc.path_map_(7, 4).target_dist = 1;
  tc.path_map_(7, 5).target_dist = 1;
  tc.path_map_(7, 6).target_dist = 1;
  tc.path_map_(7, 7).target_dist = 1;
  wa->synchronize();

  //try to rotate into it
  //tc->generateTrajectory(4.5, 4.5, M_PI_2, 0, 0, 0, 0, 0, M_PI_2, 0, 0, M_PI_4, 100, traj, 2, 30);
  tc.generateTrajectory(4.5, 4.5, M_PI_2, 0, 0, 0, 0, 0, M_PI_2, 0, 0, M_PI_4, 100, traj);
  //we expect this path to hit the obstacle
  EXPECT_FLOAT_EQ(traj.cost_, -1.0);
}

void TrajectoryPlannerTest::checkGoalDistance(){
  //let's box a cell in and make sure that its distance gets set to max
  map_->operator ()(1, 2).target_dist = 1;
  map_->operator ()(1, 1).target_dist = 1;
  map_->operator ()(1, 0).target_dist = 1;
  map_->operator ()(2, 0).target_dist = 1;
  map_->operator ()(3, 0).target_dist = 1;
  map_->operator ()(3, 1).target_dist = 1;
  map_->operator ()(3, 2).target_dist = 1;
  map_->operator ()(2, 2).target_dist = 1;
  wa->synchronize();

  //set a goal
  tc.path_map_.resetPathDist();
  queue<MapCell*> target_dist_queue;
  MapCell& current = tc.path_map_(4, 9);
  current.target_dist = 0.0;
  current.target_mark = true;
  target_dist_queue.push(&current);
  tc.path_map_.computeTargetDistance(target_dist_queue, tc.costmap_);

  EXPECT_FLOAT_EQ(tc.path_map_(4, 8).target_dist, 1.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 7).target_dist, 2.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 6).target_dist, 100.0); //there's an obstacle here placed above
  EXPECT_FLOAT_EQ(tc.path_map_(4, 5).target_dist, 6.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 4).target_dist, 7.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 3).target_dist, 8.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 2).target_dist, 9.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 1).target_dist, 10.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 0).target_dist, 11.0);
  EXPECT_FLOAT_EQ(tc.path_map_(5, 8).target_dist, 2.0);
  EXPECT_FLOAT_EQ(tc.path_map_(9, 4).target_dist, 10.0);

  //check the boxed in cell
  EXPECT_FLOAT_EQ(100.0, tc.path_map_(2, 2).target_dist);

}

void TrajectoryPlannerTest::checkPathDistance(){
  tc.path_map_.resetPathDist();
  queue<MapCell*> target_dist_queue;
  MapCell& current = tc.path_map_(4, 9);
  current.target_dist = 0.0;
  current.target_mark = true;
  target_dist_queue.push(&current);
  tc.path_map_.computeTargetDistance(target_dist_queue, tc.costmap_);

  EXPECT_FLOAT_EQ(tc.path_map_(4, 8).target_dist, 1.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 7).target_dist, 2.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 6).target_dist, 100.0); //there's an obstacle here placed above
  EXPECT_FLOAT_EQ(tc.path_map_(4, 5).target_dist, 6.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 4).target_dist, 7.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 3).target_dist, 8.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 2).target_dist, 9.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 1).target_dist, 10.0);
  EXPECT_FLOAT_EQ(tc.path_map_(4, 0).target_dist, 11.0);
  EXPECT_FLOAT_EQ(tc.path_map_(5, 8).target_dist, 2.0);
  EXPECT_FLOAT_EQ(tc.path_map_(9, 4).target_dist, 10.0);

  //check the boxed in cell
  EXPECT_FLOAT_EQ(tc.path_map_(2, 2).target_dist, 100.0);

}

TrajectoryPlannerTest* tct = NULL;

TrajectoryPlannerTest* setup_testclass_singleton() {
  if (tct == NULL) {
    MapGrid* mg = new MapGrid (10, 10);
    WavefrontMapAccessor* wa = new WavefrontMapAccessor(mg, .25);
    const costmap_2d::Costmap2D& map = *wa;
    std::vector<geometry_msgs::Point> footprint_spec;
    geometry_msgs::Point pt;
    //create a square footprint
    pt.x = 2;
    pt.y = 2;
    footprint_spec.push_back(pt);
    pt.x = 2;
    pt.y = -2;
    footprint_spec.push_back(pt);
    pt.x = -2;
    pt.y = -2;
    footprint_spec.push_back(pt);
    pt.x = -2;
    pt.y = 2;
    footprint_spec.push_back(pt);

    tct = new base_local_planner::TrajectoryPlannerTest(mg, wa, map, footprint_spec);
  }
  return tct;
}

//make sure that trajectories that intersect obstacles are invalidated
TEST(TrajectoryPlannerTest, footprintObstacles){
  TrajectoryPlannerTest* tct = setup_testclass_singleton();
  tct->footprintObstacles();
}

//make sure that goal distance is being computed as expected
TEST(TrajectoryPlannerTest, checkGoalDistance){
  TrajectoryPlannerTest* tct = setup_testclass_singleton();
  tct->checkGoalDistance();
}

//make sure that path distance is being computed as expected
TEST(TrajectoryPlannerTest, checkPathDistance){
  TrajectoryPlannerTest* tct = setup_testclass_singleton();
  tct->checkPathDistance();
}

}; //namespace


text:
package inpro.gui;

import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;

import javax.swing.ImageIcon;

public class ImageTile extends Tile {

	Image image;
	Point size;
	boolean isVisible = true;

	public ImageTile(URL url) {
		ImageIcon img = new ImageIcon(url);
		this.image = img.getImage();
		size = new Point(image.getWidth(null), image.getHeight(null));
	}

	public void setVisible(boolean v) {
		isVisible = v;
	}

	@Override
	public void draw(Graphics g, boolean l) {
		if (isVisible)
			g.drawImage(image, refPoint.x - size.x / 2, refPoint.y - size.y / 2, null, null);
	}

	@Override
	public boolean matchesPosition(java.awt.Point p) {
		boolean s;
		s = ((refPoint.x - size.x / 2 < p.x) && (p.x < (refPoint.x + size.x / 2))
		&& (refPoint.y - size.y / 2 < p.y) && (p.y < (refPoint.y + size.y + size.y / 2)));
		return s;
	}

	@Override
	public void unplace() {
		// TODO Auto-generated method stub

	}

}


text:
require 'spec_helper'

describe Resque::Stress::Harness do
  let(:harness) {Resque::Stress::Harness.new}
  describe "#validate!" do
    it "should raise error if name is nil" do
      harness.name = nil
      expect {harness.validate!}.to raise_error
    end

    it "should raise error if name is empty" do
      harness.name = ''
      expect {harness.validate!}.to raise_error
    end
  end

  context "aggregate ops" do
    let(:queue1) {Resque::Stress::QueueDef.new}
    let(:queue2) {Resque::Stress::QueueDef.new}
    let(:job1) {Resque::Stress::JobDef.new}
    let(:job2) {Resque::Stress::JobDef.new}
    let(:job3) {Resque::Stress::JobDef.new}

    before do
      queue1.name = 'queue1'
      queue1.jobs << job1
      job1.queue = queue1
      queue1.jobs << job3
      job3.queue = queue1

      queue2.name = 'queue2'
      queue2.jobs << job2
      job2.queue = queue2

      job1.weight = 1
      job2.weight = 3
      job3.weight = 2

      harness.queues << queue1
      queue1.parent = harness
      harness.queues << queue2
      queue2.parent = harness
    end

    describe "#all_jobs" do
      it "should contain jobs from all queues" do
        result = Set.new(harness.all_jobs)
        result.should == Set.new([job1, job2, job3])
      end

      it "should have jobs sorted according to weight" do
        harness.all_jobs.should == [job2, job3, job1]
      end
    end

    describe "#total_weight" do
      it "should evaluate to the sum of all job weights" do
        expected = job1.weight + job2.weight + job3.weight
        harness.total_weight.should == expected
      end
    end

    describe "#job_for_roll" do
      it "should correctly pick job defs according to weighting" do
        harness.pick_job_def(0.1).should == job2
        harness.pick_job_def(0.2).should == job2
        harness.pick_job_def(0.3).should == job2
        harness.pick_job_def(0.4).should == job2
        harness.pick_job_def(0.5).should == job2
        harness.pick_job_def(0.6).should == job3
        harness.pick_job_def(0.7).should == job3
        harness.pick_job_def(0.8).should == job3
        harness.pick_job_def(0.9).should == job1
      end

      it "should pick most likely job for any arg < 0" do
        harness.pick_job_def(-1).should == job2
      end

      it "should pick least likely job for any arg >= 1" do
        harness.pick_job_def(1.0).should == job1
      end
    end
  end
end


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2018-2020 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime;

import android.app.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import android.net.Uri;

import android.os.Bundle;
import android.os.Handler;

import android.util.Log;

import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.appinventor.components.runtime.util.SdkLevel;

/**
 * Create a An activity that display's the Repl's startup splash screen
 * which will introduce the REPL and ask for necessary permissions.
 *
 */
public final class SplashActivity extends AppInventorCompatActivity {

  WebView webview;
  Handler handler;

  public class JavaInterface {
    Context mContext;

    public JavaInterface(Context context) {
      mContext = context;
    }

    @JavascriptInterface
    public boolean hasPermission(String permission) {
      if (SdkLevel.getLevel() < SdkLevel.LEVEL_MARSHMALLOW) {  // permissions granted at install prior to Marshmallow
        return true;
      } else if (ContextCompat.checkSelfPermission(mContext, permission) ==
        PackageManager.PERMISSION_GRANTED) {
        return true;
      } else {
        return false;
      }
    }

    @JavascriptInterface
    public void askPermission(String permission) {
      ActivityCompat.requestPermissions((Activity) SplashActivity.this,
        new String[] { permission}, 1);
    }

    @JavascriptInterface
    public String getVersion() {
      try {
        String packageName = mContext.getPackageName();
        PackageInfo pInfo = mContext.getPackageManager().getPackageInfo(packageName, 0);
        return (pInfo.versionName);
      } catch (NameNotFoundException e) {
        return "Unknown";
      }
    }

    @JavascriptInterface
    public void finished() {
      SplashActivity.this.handler.post(new Runnable() {
          @Override
          public void run() {
            SplashActivity.this.webview.destroy();
            SplashActivity.this.finish();
          }
        });
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    JavaInterface android = new JavaInterface(this);
    handler = new Handler();
    webview = new WebView(this);
    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);
    String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    webSettings.setDatabasePath(databasePath);

    // webview.setWebViewClient(new WebViewClient() {
    //     @Override
    //     public boolean shouldOverrideUrlLoading(WebView view, String url) {
    //       Log.i("WebView", "Handling url " + url);
    //       Uri uri = Uri.parse(url);
    //       String scheme = uri.getScheme();
    //       if (scheme.equals(Form.APPINVENTOR_URL_SCHEME)) {
    //         Intent resultIntent = new Intent();
    //         resultIntent.setData(uri);
    //         setResult(RESULT_OK, resultIntent);
    //         finish();
    //       } else {
    //         view.loadUrl(url);
    //       }
    //       return true;
    //     }
    //   });

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier,
          long currentQuota, long estimatedSize, long totalUsedQuota,
          WebStorage.QuotaUpdater quotaUpdater) {
          quotaUpdater.updateQuota(5 * 1024 * 1024);
        }
      });
    setContentView(webview);
    // Uncomment the line below to enable debugging
    // the splash screen (splash.html)
    //
    // webview.setWebContentsDebuggingEnabled(true);
    webview.addJavascriptInterface(android, "Android");
    webview.loadUrl("file:///android_asset/splash.html");
  }

  @Override
  public void onRequestPermissionsResult(int code,
    String permissions[], int[] grantResults) {
    for (int i = 0; i < permissions.length; i++ ) {
      String permission = permissions[i];
      int grantResult = grantResults[i];
      boolean granted = false;
      if (grantResult == PackageManager.PERMISSION_GRANTED) {
        granted = true;
      }
      webview.loadUrl("javascript:permresult('" + permission + "'," + granted + ")");
    }
  }

}


text:
from .base import BaseField

class ManyToManyField(BaseField):

    """
    """

    def __init__(
        self,
        related,
        field=None,
        related_field=None,
        backref=None,
        ondelete=None,
        *args,
        **kwargs
    ):
        super(ManyToManyField, self).__init__(*args, **kwargs)
        self.related = related
        self.backref = backref
        self.field = field
        self.related_field = related_field
        self.ondelete = ondelete


text:
<?php namespace MovBizz\Turn;

use Laracasts\Commander\CommandHandler;
use Session;

class ResetAvailablePlayersCommandHandler implements CommandHandler {

    /**
     * Handle the command.
     *
     * @param object $command
     * @return void
     */
    public function handle($command)
    {
    	Session::set('game.availablePlayers', $command->players);
    }

}


text: Successfully visited privileged page


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

namespace CSharpQuickReference.src
{
    // struct is lightweight alternative to a class

        // new instances of the class are placed on the heap ,
        // new instances of the struct are placed on the stack

    // we're not working with references like with class but working directly with the struct instance
        // that means when we pass struct to function it's passed by value not by refrence

    // we use structs when we want to represent more simple data structures - and especially if we  know that we will be instatiating lots of them
    // Point, Rectangle, Color structs are only few Microsoft have in store for us
    class Structs
    {
        public static structEntity  newStruct = new structEntity("red");
        public structEntity newstr2 = new structEntity("blue");
        public CustomClass1 neo = new CustomClass1();
        public string majento;
        public static void getDefStructor()
        {

            // can use static fields in static method
           // newstr2.Describe(); // object reference is required for non static method , field or property
            Console.WriteLine(newStruct.Describe());
        }
    }
    // interfaces can be applied to struct
    struct structEntity
    {
        // we cant initialize fields on the beginnign
        // no inheritance from class or structs
        private string color;

        public structEntity(string color)
        {
            this.color = color;
            this.Color = color;
        }

        public string Describe()
        {
            return " textstring ";
        }

        public string Color
        {
            get;
            set;
        }
    }
}


text:
#include <aws/s3-crt/model/ObjectLockEnabled.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace S3Crt
  {
    namespace Model
    {
      namespace ObjectLockEnabledMapper
      {

        static const int Enabled_HASH = HashingUtils::HashString("Enabled");

        ObjectLockEnabled GetObjectLockEnabledForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Enabled_HASH)
          {
            return ObjectLockEnabled::Enabled;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ObjectLockEnabled>(hashCode);
          }

          return ObjectLockEnabled::NOT_SET;
        }

        Aws::String GetNameForObjectLockEnabled(ObjectLockEnabled enumValue)
        {
          switch(enumValue)
          {
          case ObjectLockEnabled::Enabled:
            return "Enabled";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ObjectLockEnabledMapper
    } // namespace Model
  } // namespace S3Crt
} // namespace Aws


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System.Security.Permissions
{
    [System.AttributeUsageAttribute((System.AttributeTargets)(109), AllowMultiple = true, Inherited = false)]
    public sealed partial class PublisherIdentityPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
    {
        public PublisherIdentityPermissionAttribute(System.Security.Permissions.SecurityAction action) : base(default(System.Security.Permissions.SecurityAction)) { }
        public string CertFile { get; set; }
        public string SignedFile { get; set; }
        public string X509Certificate { get; set; }
        public override System.Security.IPermission CreatePermission() { return default(System.Security.IPermission); }
    }
}


text:
import subutai
import subuco
from time import sleep
if subutai.GetOS() == 'w':
    import subuw as subup
elif subutai.GetOS() == 'l':
    import subul as subup
elif subutai.GetOS() == 'd':
    import subud as subup

def subutaistart():
    rc = 0
    tmpDir = subutai.GetTmpDir()
    installDir = subutai.GetInstallDir()

    p2p = subup.P2P(tmpDir, installDir)
    rc = p2p.PreInstall()
    if rc != 0:
        sleep(10)
        subutai.Shutdown()
        return rc
    rc = p2p.Download()
    if rc != 0:
        sleep(10)
        subutai.Shutdown()
        return rc
    rc = p2p.PostInstall()
    if rc != 0:
        sleep(10)
        subutai.Shutdown()
        return rc
    subutai.SetProgress(1.00)

    sleep(3)
    subutai.Shutdown()

    return 0


text:
package storage

import (
	"errors"
	"github.com/grooveshark/golib/gslog"
	"time"
)

// CommandRet is returned from a Command in the RetCh. It's really just a tuple
// around the return value and an error
type CommandRet struct {
	Ret interface{}
	Err error
}

// Command is sent to a Storage, and contains all data necessary to
// complete a call and return any data from it. Both methods implemented aren't
// really used outside of the CommandFactory and Storage they're being
// created for, so their behavior isn't terribly important.
type Command interface {

	// Cmd returns the basic command that's going to be executed. This will
	// differ depending on backend
	Cmd() string

	// Args is a list of arguments to the command. This will also differ
	// depending on platform.
	Args() []interface{}
}

// CommandBundle is a grouping of a Command and a channel on which the
// CommandRet for that command will be returned.
type CommandBundle struct {
	Cmd   Command
	RetCh chan *CommandRet
}

// A storage unit connection is a connection to a single storage unit, which
// acts like a basic tcp connection but could in theory be just about anything.
type Storage interface {

	// Connect is called on a zero'd Storage and causes it to create its
	// initial connection to the datastore and set up any internal go-routines
	// that are needed. It also passes in the channel the connection should read
	// CommandBundles off of, process, and respond to using the bundle's RetCh
	Connect(cmdCh chan *CommandBundle, conntype, addr string,
		extra ...interface{}) error

	// Given the command and arguments for an action on the datastore, returns a
	// Command instance. This method should not actually affect anything about
	// the Storage connection.
	NewCommand(string, ...interface{}) Command

	// Returns whether or not a command is allowed to be called under any
	// circumstances. This method should not actually affect anything about the
	// Storage connection.
	CommandAllowed(string) bool

	// Returns whether or not a command will modify state within the datastore
	// (and therefore potentially require authentication). This method should
	// not actually affect anything about the Storage connection.
	CommandModifies(string) bool

	// Returns whether or not a command requires administrative privileges (and
	// therefore potentially require authentication). This method should not
	// actually affect anything about the Storage connection.
	CommandIsAdmin(string) bool

	// Close tells the connection that it's no longer needed. It should close
	// any external resources it has open and tell all internal go-routines to
	// end execution. Any subsequent calls to the Storage will cause a
	// panic.
	Close() error
}

// A storage unit is a pool of storage unit conns which can be opened and closed
// as a single group. It also multiplexes calls across the connections.
type StorageUnit struct {
	ConnType, Addr string
	conns          []Storage
	cmdCh          chan *CommandBundle
	closeCh        chan chan error
}

// NewStorageUnit takes in a slice of zero'd Storages, a connection
// type/address, and any extra info which will be passed back to the Connect
// function of each Storage. If any of the calls to Connect result in an
// error all the previous Storages will be Close'd and that error will
// be returned.
func NewStorageUnit(
	sucs []Storage,
	conntype, addr string,
	extra ...interface{}) (*StorageUnit, error) {

	su := StorageUnit{
		ConnType: conntype,
		Addr:     addr,
		conns:    make([]Storage, 0, len(sucs)),
		cmdCh:    make(chan *CommandBundle),
		closeCh:  make(chan chan error),
	}

	for _, suc := range sucs {
		if err := suc.Connect(su.cmdCh, conntype, addr, extra...); err == nil {
			su.conns = append(su.conns, suc)
		} else {
			su.internalClose()
			return nil, err
		}
	}

	go su.spin()
	return &su, nil
}

func (su *StorageUnit) spin() {
	for {
		select {
		case retCh := <-su.closeCh:
			retCh <- su.internalClose()
			su.tempGround()
			close(su.closeCh)
			close(su.cmdCh)
			return
		}
	}
}

func (su *StorageUnit) internalClose() error {
	var retErr error
	for i := range su.conns {
		if err := su.conns[i].Close(); err != nil {
			retErr = err
		}
	}
	return retErr
}

func (su *StorageUnit) tempGround() {
	timeout := time.After(10 * time.Second)
	for {
		select {
		case <-su.cmdCh:
			gslog.Warn("Dropping command in storage unit because it's closed")
		case <-timeout:
			return
		}
	}
}

// Close goes through all Storages that are currently active and calls
// Close() on each one. The last non-nil error to be returned by any of those
// Close calls is returned, or nil if none of them returned an error. Any
// subsequent calls to the StorageUnit will cause a panic.
func (su *StorageUnit) Close() error {
	retCh := make(chan error)
	su.closeCh <- retCh
	return <-retCh
}

// Cmd takes in a command bundle and performs the command in one of the
// Storage's connections
func (su *StorageUnit) Cmd(cmd Command) (interface{}, error) {
	cmdb := &CommandBundle{cmd, make(chan *CommandRet)}
	select {
	case su.cmdCh <- cmdb:
	case <-time.After(10 * time.Second):
		gslog.Errorf("send command %s:%s timeout", su.ConnType, su.Addr)
		return nil, errors.New("timeout")
	}

	select {
	case cret := <-cmdb.RetCh:
		return cret.Ret, cret.Err
	case <-time.After(10 * time.Second):
		gslog.Errorf("receive response %s:%s timeout", su.ConnType, su.Addr)
		return nil, errors.New("timeout")
	}
}

// Returns a new Command instance based on the given command and arguments
func (su *StorageUnit) NewCommand(cmd string, args ...interface{}) Command {
	return su.conns[0].NewCommand(cmd, args...)
}

// Returns whether or not a command is allowed to be run at all on the datastore
func (su *StorageUnit) CommandAllowed(cmd string) bool {
	return su.conns[0].CommandAllowed(cmd)
}

// Returns whether or not a command modifies state on the datastore
func (su *StorageUnit) CommandModifies(cmd string) bool {
	return su.conns[0].CommandModifies(cmd)
}

func (su *StorageUnit) CommandIsAdmin(cmd string) bool {
	return su.conns[0].CommandIsAdmin(cmd)
}


text: step_into_lwrp 'thing'


text:
printf "############################################\n"
printf "# Ubuntu 20.04 Install Automation #\n"
printf "############################################\n\n"

##########################################################################################
## Set bash options
##########################################################################################
set -e # Exit on error
#set -x # Enable debugging

##########################################################################################
## Define helper functions
##########################################################################################

genpasswd() {
	local l=$1
       	[ "$l" == "" ] && l=16
      	tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}

##########################################################################################
## Define variables with default variables
##########################################################################################

export COMPANY=mycompany
export BASEDIR=`pwd`
export LOGDIR='/tmp'
export DATE=`date +%Y-%m-%d_%H%M`
export MONITORIX_PASS=`genpasswd`
# export CRONJOBS_PASS=`genpasswd`
export DEBIAN_FRONTEND=noninteractive # Make apt-get install non-interactive

export DO_CHANGE_TIMEZONE=N
export DO_SYSTEM_UPDATE=N
export DO_SWAPFILE_INSTALL=N
export DO_EXTRAS_INSTALL=N
export DO_GENERAL_SERVER_SETTINGS=N
export DO_MONITORIX_INSTALL=N
export DO_NETDATA_INSTALL=N
export DO_DOCKER_INSTALL=N
export DO_UFW_INSTALL=N
export DO_SWAP_INSTALL=N

# @TODO - INSTALL RSYSLOG + POSTGRES DUMPER

export UFW_ALLOW_PUBLIC_HTTP=Y
export UFW_ALLOW_PUBLIC_HTTPS=Y
export UFW_ALLOW_POSTHOG=Y
export UFW_ALLOW_NETDATA=Y
export UFW_ALLOW_MONITORIX=Y

export TIMEZONE="Europe/Copenhagen"
export NTP="dk.pool.ntp.org"
export NTP_FALLBACK="pool.ntp.org"

export EMAIL_DOMAIN="mydomain.com"
export INFO_EMAIL="my.server.email@${EMAIL_DOMAIN}"

export SECURE_SUBNET="MYIPRANGE/32"
export SECURE_SUBNET_DESC="MY subnet"

##########################################################################################
## Message/logging functions
##########################################################################################

# Yellow
show_yellow () {
    echo $(tput bold)$(tput setaf 4) $@ $(tput sgr 0)
}
# White
show_norm () {
    echo $(tput bold)$(tput setaf 9) $@ $(tput sgr 0)
}
# Blue
show_info () {
    echo $(tput bold)$(tput setaf 4) $@ $(tput sgr 0)
}
# Green
show_warn () {
    echo $(tput bold)$(tput setaf 2) $@ $(tput sgr 0)
}
# Red
show_err ()  {
    echo $(tput bold)$(tput setaf 1) $@ $(tput sgr 0)
}

##########################################################################################
## Check if we're are root
##########################################################################################

if [[ $EUID -ne 0 ]]; then
   show_err "Script must be run as root. Please check logfile and fix error manually."
   exit 1
fi

##########################################################################################
## Check if cronscripts folder exists and create it if it doesn't
##########################################################################################

if [ ! -d $CRONDIR ]
then
   mkdir -p $CRONDIR
fi

##########################################################################################
## Get input
##########################################################################################

# Change company name (folder under /srv/mycompany/
read -p "Enter company name (i.e. 'mycompany'): " COMPANY
echo "COMPANY: "$COMPANY

##########################################################################################
## Set variables from input
##########################################################################################

export CRONDIR="/srv/$COMPANY/cronscripts"
export DEPLOYDIR="/srv/$COMPANY/deploy"
export BACKUPDIR="/srv/$COMPANY/deploy/automation-backup"

# Create crondir if it doesn't exist
if [ ! -d $CRONDIR ]
   then
      mkdir -p $CRONDIR
fi

# Create automation-backup dir if it doesn't exist - also creates ($DEPLOYDIR)
if [ ! -d $BACKUPDIR ]
   then
      mkdir -p $BACKUPDIR
fi

# Write to secret file
echo $DATE >> $CRONDIR/pswd

##########################################################################################
## Get input
##########################################################################################

# Change timezone?
while true; do
    read -p "Do You want to change timezone (default: $TIMEZONE) (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_CHANGE_TIMEZONE=Y && read -p "Enter timezone (i.e. 'Europe/Copenhagen'): " TIMEZONE; break;;
        [Nn]* ) DO_CHANGE_TIMEZONE=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_CHANGE_TIMEZONE: "$DO_CHANGE_TIMEZONE
echo "TIMEZONE: "$TIMEZONE

# Change NTP?
while true; do
    read -p "Do You want to change NTP server (default: $NTP) (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_CHANGE_NTP=Y && read -p "Enter NTP server fallback (i.e. 'dk.pool.ntp.org'): " NTP; break;;
        [Nn]* ) DO_CHANGE_NTP=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_CHANGE_NTP: "$DO_CHANGE_NTP
echo "NTP: "$NTP

# Change NTP FALLBACK?
while true; do
    read -p "Do You want to change NTP server fallback (default: $NTP_FALLBACK) (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_CHANGE_NTP=Y && read -p "Enter NTP server fallback (i.e. 'pool.ntp.org'): " NTP_FALLBACK; break;;
        [Nn]* ) DO_CHANGE_NTP=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_CHANGE_NTP_FALLBACK: "$DO_CHANGE_NTP_NTP_FALLBACK
echo "NTP_FALLBACK: "$NTP_FALLBACK

# Change e-mail domain
while true; do
    read -p "Do You want to change e-mail domain? (default is $EMAIL_DOMAIN) (Y/N)? " yn
    case $yn in
        [Yy]* ) SET_EMAIL_DOMAIN=Y && read -p "Enter e-mail domain (only domain part of e-mail address): " EMAIL_DOMAIN; break;;
        [Nn]* ) SET_EMAIL_DOMAIN=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "SET_EMAIL_DOMAIN: "$SET_EMAIL_DOMAIN
echo "EMAIL_DOMAIN: "$EMAIL_DOMAIN

# Change e-mail alias
while true; do
    read -p "Do You want to change e-mail address? (default is $INFO_EMAIL) (Y/N)? " yn
    case $yn in
        [Yy]* ) SET_EMAIL_DOMAIN=Y && read -p "Enter the xxx part before @ in the e-mail address (xxx@domain.com): " INFO_EMAIL; break;;
        [Nn]* ) SET_EMAIL_DOMAIN=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "SET_EMAIL_ADDRESS: "$SET_EMAIL_ADDRESS
echo "INFO_EMAIL: "$INFO_EMAIL

# System update
while true; do
    read -p "Do You want to update system (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_SYSTEM_UPDATE=Y; break;;
        [Nn]* ) DO_SYSTEM_UPDATE=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_SYSTEM_UPDATE: "$DO_SYSTEM_UPDATE

# General server settings install
while true; do
    read -p "Do You want to install general server settings (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_GENERAL_SERVER_SETTINGS=Y; break;;
        [Nn]* ) DO_GENERAL_SERVER_SETTINGS=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_GENERAL_SERVER_SETTINGS: "$DO_GENERAL_SERVER_SETTINGS

# Swap install
while true; do
    read -p "Do you want to install secure swap file (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_SWAP_INSTALL=Y; break;;
        [Nn]* ) DO_SWAP_INSTALL=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_SWAP_INSTALL: "$DO_SWAP_INSTALL

# Monitorix install
while true; do
    read -p "Do You want to install Monitorix (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_MONITORIX_INSTALL=Y; break;;
        [Nn]* ) DO_MONITORIX_INSTALL=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_MONITORIX_INSTALL: "$DO_MONITORIX_INSTALL

# Netdata install
while true; do
    read -p "Do You want to install Netdata (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_NETDATA_INSTALL=Y; break;;
        [Nn]* ) DO_NETDATA_INSTALL=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_NETDATA_INSTALL: "$DO_NETDATA_INSTALL

# Docker install
while true; do
    read -p "Do You want to install Docker (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_DOCKER_INSTALL=Y; break;;
        [Nn]* ) DO_DOCKER_INSTALL=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_DOCKER_INSTALL: "$DO_DOCKER_INSTALL

# UFW install
while true; do
    read -p "Do You want to install UFW (Y/N)? " yn
    case $yn in
        [Yy]* ) DO_UFW_INSTALL=Y; break;;
        [Nn]* ) DO_UFW_INSTALL=N; break;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo "DO_UFW_INSTALL: "$DO_UFW_INSTALL

# Ask for UFW port openings
if [[ $DO_UFW_INSTALL =~ [Yy]$ ]]
   then
      read -p "Enter CIDR IP range for SECURE_SUBNET: " SECURE_SUBNET; echo
      read -p "Enter CIDR IP range description for SECURE_SUBNET_DESC: " SECURE_SUBNET_DESC; echo
      read -p "Do You want to allow port 80 (http) to World (Y/N)?" -n 1 UFW_ALLOW_PUBLIC_HTTP; echo
      read -p "Do You want to allow port 443 (https) to World (Y/N)?" -n 1 UFW_ALLOW_PUBLIC_HTTPS; echo
      read -p "Do You want to allow port 8443 (Posthog) to World (Y/N)?" -n 1 UFW_ALLOW_POSTHOG; echo
      read -p "Do You want to allow port 8081 (Monitorix) to World (Y/N)?" -n 1 UFW_ALLOW_MONITORIX; echo
      read -p "Do You want to allow port 19999 (Netdata) to World (Y/N)?" -n 1 UFW_ALLOW_NETDATA; echo
fi

##########################################################################################
## Prepare ufw.sh
##########################################################################################

# Build UFW_HEADER
UFW_HEADER="#!/bin/bash
# UFW_HEADER START
ufw --force reset
# ufw allow proto tcp from $SECURE_SUBNET to any port 22 # $SECURE_SUBNET_DESC to SSH
ufw allow 22/tcp # SSH
ufw allow 161/udp # SNMP
# UFW_HEADER END
"

if [[ $DO_UFW_INSTALL =~ [Yy]$ ]]
   then
      echo "$UFW_HEADER" > $CRONDIR/ufw.sh
fi

##########################################################################################
## Execute subscripts
##########################################################################################

printf "\n-----------------------------------------------------------\n"
printf "\nWill now execute subscripts based on Your previous choices.\n"

read -p "Do You want to continue (Y/N)?" -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
   then
       printf "\n\n--------------------\n"
       show_norm "Executing subscripts"
       printf "\n--------------------\n"
   else
       printf "\n\n------------------\n"
       show_warn "Exiting gracefully"
       printf "\n------------------\n"
       exit 0
fi

# Start timer
START_TIME=`date +%s`

# Set timezone
if [[ $DO_SET_TIMEZONE =~ [Yy]$ ]]
   then
      cp -p /usr/share/zoneinfo/$TIMEZONE /etc/localtime
      echo "${TIMEZONE}" > /etc/timezone
      show_yellow "Timezone set to $TIMEZONE"
fi

printf "\n--------------------\n"

# System update
if [[ $DO_SYSTEM_UPDATE =~ [Yy]$ ]]
   then
       source $BASEDIR/subscripts/system_update.sh
   else
       show_warn "System update will not be performed"
fi

printf "\n--------------------\n"

# General server settings install
if [[ $DO_GENERAL_SERVER_SETTINGS =~ [Yy]$ ]]
   then
       source $BASEDIR/subscripts/general_system_settings.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/secure_shared_memory_install.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/sysctl_install.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/maldet_install.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/rkhunter_install.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/clamav_install.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/fail2ban_install.sh
       printf "\n--------------------\n"
       source $BASEDIR/subscripts/sendmail_install.sh # @TODO - Aliases could perhaps be used for e-mail forwarding as I asked about
   else
      show_warn "General server settings will not be installed"
fi

printf "\n--------------------\n"

# Swap install
if [[ $DO_SWAP_INSTALL =~ [Yy]$ ]]
   then
       source $BASEDIR/subscripts/swap_install.sh
   else
       show_warn "Swap not selected."
fi

printf "\n--------------------\n"

# Docker install
if [[ $DO_DOCKER_INSTALL =~ [Yy]$ ]]
   then
       source $BASEDIR/subscripts/docker_install.sh
   else
       show_warn "Docker will not be installed"
fi

printf "\n--------------------\n"

# Netdata install
if [[ $DO_NETDATA_INSTALL =~ [Yy]$ ]]
   then
       source $BASEDIR/subscripts/netdata_install.sh
   else
       show_warn "Netdata will not be installed"
fi

printf "\n--------------------\n"

# Monitorix install / MUST BE DONE SECOND LAST DUE TO MONITORING BEING ALTERED ACCORDING TO INSTALLATION
if [[ $DO_MONITORIX_INSTALL =~ [Yy]$ ]]
   then
       source $BASEDIR/subscripts/monitorix_install.sh
   else
       show_warn "Monitorix will not be installed"
fi

printf "\n--------------------\n"

# UFW script install / MUST BE DONE LAST DUE TO UFW BEING ALTERED ACCORDING TO INSTALLATION
if [[ $DO_UFW_INSTALL =~ [Yy]$ ]]
   then
       ufw status numbered >> $BACKUPDIR/ufw

       echo "ufw enable" >> $CRONDIR/ufw.sh
       source $BASEDIR/subscripts/ufw_install.sh
   else
       show_warn "UFW script will not be installed"
fi

printf "\n--------------------\n"

# Write to pswd and secure file
echo "" >> $CRONDIR/pswd
chmod 0600 $CRONDIR/pswd

# End timer
END_TIME=`date +%s`

# Say bye
show_norm "Installation done (took `expr $END_TIME - $START_TIME` seconds). Have a nice day."


text:
class AddPreSubmissionMessage < ActiveRecord::Migration
  def self.up
    add_column :exercises, :submit_pre_message, :text
  end

  def self.down
    remove_column :exercises, :submit_pre_message
  end
end


text:
/* ***************************************************************
 *  This file is part of STATegra EMS.
 *
 *  STATegra EMS is free software: you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation, either version 3 of
 *  the License, or (at your option) any later version.
 *
 *  STATegra EMS is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with STATegra EMS.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  More info http://bioinfo.cipf.es/stategraems
 *  Technical contact stategraemsdev@gmail.com
 *  *************************************************************** */
package bdManager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.dbcp.BasicDataSourceFactory;

/**
 *
 * @author
 */
public class DBConnectionManager {

    private static DBConnectionManager connectionManager_instance = null;
    private HashMap<Long, Connection> connections = null;
    private DataSource connectionPool;
    private static String data_location;
    Properties properties;

    private DBConnectionManager() throws SQLException {
        initConnectionManager();
    }

    private void initConnectionManager() throws SQLException {
        try {
            connections = new HashMap<Long, Connection>();
            properties = new Properties();
            properties.load(new FileReader(this.data_location + "/db_config.properties"));
            if(properties.get("host") != null){ //Since version 0.8
                properties.setProperty("password", new String(Base64.decodeBase64(properties.getProperty("password"))));
            }else{
                System.err.println("Old version for settings, trying to fix...");
                String host = properties.get("url").toString();
                host = host.replace("jdbc:mysql://", "");
                host = host.replace("/" + properties.get("databasename").toString(), "");
                properties.setProperty("host", host);
            }
            connectionPool = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception ex) {
            System.err.println(String.format("%tc", new Date()) + " STATEGRAEMS LOG > FAILED TRYING TO OPEN A NEW CONNECTIONS POOL");
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            String exceptionTraceAsString = sw.toString();
            System.err.println(String.format("%tc", new Date()) + " STATEGRAEMS LOG > Exception " + ex.getClass().getName() + " TRACE: " + exceptionTraceAsString);

            throw new SQLException("Unable to connect with DATABASE");
        }
    }

//    private void cleanConnectionManager() throws SQLException {
//        try {
//            //CLOSE ALL CONENCTIONS
//            for (Long id : connections.keySet()) {
//                this.connections.get(id).close();
//            }
//
//            this.connections.clear();
//            connectionPool = null;
//        } catch (Exception ex) {
//            System.err.println(String.format("%tc", new Date()) + " STATEGRAEMS LOG > FAILED TRYING TO CLOSE ALL CONNECTIONS POOL");
//            StringWriter sw = new StringWriter();
//            ex.printStackTrace(new PrintWriter(sw));
//            String exceptionTraceAsString = sw.toString();
//            System.err.println(String.format("%tc", new Date()) + " STATEGRAEMS LOG > Exception " + ex.getClass().getName() + " TRACE: " + exceptionTraceAsString);
//
//            throw new SQLException("Unable to close the DATABASE connection");
//        }
//    }

    public static String getDataLocation() {
        return DBConnectionManager.data_location;
    }

    public static void setDataLocation(String data_location) {
        DBConnectionManager.data_location = data_location;
    }

    public Properties getProperties() {
        return properties;
    }

    private synchronized static void createConnectionManager() throws SQLException {
        if (connectionManager_instance == null) {
            connectionManager_instance = new DBConnectionManager();
        }
    }

    public static DBConnectionManager getConnectionManager() throws SQLException {
        if (connectionManager_instance == null) {
            createConnectionManager();
        }
        return connectionManager_instance;
    }

//    public synchronized static void reloadConnectionManager() throws SQLException {
//        if (connectionManager_instance == null) {
//            connectionManager_instance = new DBConnectionManager();
//            return;
//        }
//        connectionManager_instance.cleanConnectionManager();
//        connectionManager_instance.initConnectionManager();
//    }

    public void closeConnection() throws SQLException {
        long threadID = Thread.currentThread().getId();
        Connection connection = this.connections.get(threadID);

        if (connection != null) {
            if (!connection.isClosed()) {
                connection.close();
            }
            this.connections.remove(threadID);
        } else {
            throw new SQLException("Session for thread " + threadID + " is not opened.");
        }
    }

    public synchronized Connection openConnection() throws SQLException {
        long threadID = Thread.currentThread().getId();
        Connection connection = this.connectionPool.getConnection();
        connections.put(threadID, connection);
        return connection;
    }

    public Connection getConnection() throws SQLException {
        long threadID = Thread.currentThread().getId();
        Connection connection = this.connections.get(threadID);
        if (connection != null) {
            if (connection.isClosed()) {
                return null;
            }
            return connection;
        } else {
            return openConnection();
        }
    }

    public java.sql.PreparedStatement prepareStatement(String query) throws SQLException {
        java.sql.PreparedStatement ps;
        Connection connection = getConnection();
        ps = connection.prepareStatement(query);
        return ps;
    }

    public ResultSet execute(PreparedStatement statement, boolean isQuery) throws SQLException {
        if (isQuery) {
            ResultSet rs = null;
            rs = statement.executeQuery();
            return rs;
        } else {
            statement.execute();
        }
        return null;
    }

    public void setAutoCommit(boolean state) throws SQLException {
        getConnection().setAutoCommit(state);
    }

    public void rollback() throws SQLException {
        getConnection().rollback();
    }

    public void commit() throws SQLException {
        getConnection().commit();
    }

    public String doDatabaseDump(String filePath) throws Exception {
        PrintWriter out = null;
        Properties properties = new Properties();
        properties.load(new FileReader(data_location + "/db_config.properties"));

//        String dumpCommand = "mysqldump  "
//                + "--complete-insert --insert-ignore --force "
//                + "--single-transaction --no-create-info --skip-comments "
//                + "--user=" + properties.getProperty("username")
//                + " --password=" + properties.getProperty("password")
//                + " " + properties.getProperty("databasename");
        String dumpCommand = "mysqldump  "
                + " --host " + properties.getProperty("host")
                + " --complete-insert --insert-ignore --force"
                + " --single-transaction --add-drop-table --skip-comments"
                + " --user=" + properties.getProperty("username")
                + " --password=" + new String(Base64.decodeBase64(properties.getProperty("password")))
                + " " + properties.getProperty("databasename");
        Runtime rt = Runtime.getRuntime();
//        dumpCommand+= " >> " + filePath;
//        System.out.println(dumpCommand);
        Process dumpProcess = rt.exec(dumpCommand);

        BufferedReader br = new BufferedReader(new InputStreamReader(dumpProcess.getInputStream()));
        String line = br.readLine();
        String output = "";
        // Mientras se haya leido alguna linea
        while (line != null) {
            output += "\n" + line;
            line = br.readLine();
        }
        int exitCode = dumpProcess.waitFor();

        if (exitCode != 0) {
            throw new Exception("Failed while executing mysql dump commands. Error: " + output);
        }

        String fileHeader = "USE " + properties.getProperty("databasename") + ";";
        fileHeader += "\nSTART TRANSACTION;";
        fileHeader += "\nBEGIN;";
        fileHeader += "\n    set FOREIGN_KEY_CHECKS = 1;\n";

        String fileFooter = "\n    set FOREIGN_KEY_CHECKS = 0;";
        fileFooter += "\nCOMMIT;";

        out = new PrintWriter(new BufferedWriter(new FileWriter(filePath, true)));
        out.println(fileHeader);
        out.println(output);
//        BufferedReader br = new BufferedReader(new InputStreamReader(dumpProcess.getInputStream()));
//        String line = br.readLine();
//        while (line != null) {
//            out.println(line);
//            line = br.readLine();
//        }
        out.println(fileFooter);
        out.close();

        return filePath;
    }
}


text:
package ar.org.fitc.test.rmi.integration.fase2.socketfactory;

import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RemoteCipher<T extends Serializable> extends Remote {

	public byte[] encipher(T s) throws RemoteException;
	public T decipher(byte[] b) throws RemoteException;
	public byte[][] encipher(T[] s) throws RemoteException;
	public T[] decipher(byte[][] b) throws RemoteException;

	public Class getTClass() throws RemoteException;
}


text:
import React, { Component, PropTypes } from 'react';
import injectSheet from 'react-jss';
import Textfield from 'react-mdl/lib/Textfield';
import IconButton from 'react-mdl/lib/IconButton';
import logo40 from 'assets/logo40.png';
import logoBig from 'assets/logo-main.png';
import logoSmall from 'assets/logo.png';
import { breakpoints } from 'modules/common/styles';

class Search extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    label: PropTypes.string.isRequired,
    onSearch: PropTypes.func.isRequired,
    value: PropTypes.string,
  }
  componentWillMount() {
    this.setState({ value: this.props.value || '' });
  }
  render() {
    const { label, onSearch, classes } = this.props;
    const { value } = this.state;
    return (
      <form
        className={classes.search}
        onSubmit={(e) => {
          e.preventDefault();
          onSearch(value);
        }}
      >
        <Textfield
          label={label}
          onChange={(e) => { this.setState({ value: e.target.value }); }}
          value={value}
        />
        <IconButton name="search" type="submit" />
      </form>
    );
  }
}

const StyledSearch = injectSheet({
  search: {
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    '& .mdl-textfield': {
      minWidth: 0,
      width: 'auto',
      flex: 1,
    },
  },
})(Search);

const DefaultHeader = ({ classes, search, main }) => (

    {
      search && search.label && search.onSearch && (


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>M.J. Serra | My bits</title>
    <link>http://lpantano.github.io/author/m.j.-serra/</link>
      <atom:link href="http://lpantano.github.io/author/m.j.-serra/index.xml" rel="self" type="application/rss+xml" />
    <description>M.J. Serra</description>
    <generator>Wowchemy (https://wowchemy.com)</generator><language>en-us</language><lastBuildDate>Wed, 01 Jan 2014 00:00:00 +0000</lastBuildDate>
    <image>
      <url>http://lpantano.github.io/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_3.png</url>
      <title>M.J. Serra</title>
      <link>http://lpantano.github.io/author/m.j.-serra/</link>
    </image>

    <item>
      <title>Regulation of miRNA strand selection: follow the leader?</title>
      <link>http://lpantano.github.io/publication/meijer-2014/</link>
      <pubDate>Wed, 01 Jan 2014 00:00:00 +0000</pubDate>
      <guid>http://lpantano.github.io/publication/meijer-2014/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
package org.dashbuilder.client.dashboard;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dashbuilder.client.resources.i18n.AppConstants;
import org.dashbuilder.displayer.DisplayerSettings;
import org.dashbuilder.displayer.client.PerspectiveCoordinator;
import org.dashbuilder.displayer.json.DisplayerSettingsJSONMarshaller;
import org.dashbuilder.displayer.client.widgets.DisplayerEditor;
import org.dashbuilder.displayer.client.widgets.DisplayerEditorPopup;
import org.jboss.errai.ioc.client.container.IOC;
import org.jboss.errai.ioc.client.container.IOCBeanDef;
import org.jboss.errai.ioc.client.container.SyncBeanManagerImpl;
import org.uberfire.client.mvp.PerspectiveActivity;
import org.uberfire.client.mvp.PerspectiveManager;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.client.workbench.panels.impl.MultiListWorkbenchPanelPresenter;
import org.uberfire.ext.widgets.common.client.common.popups.YesNoCancelPopup;
import org.uberfire.mvp.Command;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;
import org.uberfire.workbench.model.menu.MenuFactory;
import org.uberfire.workbench.model.menu.Menus;
import org.uberfire.workbench.model.toolbar.ToolBar;

/**
 * The dashboard composer perspective.
 */
public class DashboardPerspectiveActivity  implements PerspectiveActivity {

    private DashboardManager dashboardManager;
    private PerspectiveManager perspectiveManager;
    private PlaceManager placeManager;
    private DisplayerSettingsJSONMarshaller jsonMarshaller;
    private PerspectiveCoordinator perspectiveCoordinator;

    private PlaceRequest place;
    private String id;
    private boolean persistent;

    public DashboardPerspectiveActivity() {
    }

    public DashboardPerspectiveActivity(String id,
            DashboardManager dashboardManager,
            PerspectiveManager perspectiveManager,
            PlaceManager placeManager,
            PerspectiveCoordinator perspectiveCoordinator,
            DisplayerSettingsJSONMarshaller jsonMarshaller) {

        this.id = id;
        this.persistent = true;
        this.dashboardManager = dashboardManager;
        this.perspectiveManager = perspectiveManager;
        this.placeManager = placeManager;
        this.perspectiveCoordinator = perspectiveCoordinator;
        this.jsonMarshaller = jsonMarshaller;
    }

    public String getDisplayName() {
        return id.substring(10);
    }

    @Override
    public PlaceRequest getPlace() {
        return place;
    }

    @Override
    public void onStartup(final PlaceRequest place) {
        this.place = place;
    }

    @Override
    public void onOpen() {
    }

    @Override
    public void onClose() {
    }

    @Override
    public void onShutdown() {
    }

    @Override
    public PerspectiveDefinition getDefaultPerspectiveLayout() {
        PerspectiveDefinition perspective = new PerspectiveDefinitionImpl(MultiListWorkbenchPanelPresenter.class.getName());
        perspective.setName(id);
        return perspective;
    }

    @Override
    public String getIdentifier() {
        return id;
    }

    @Override
    public boolean isDefault() {
        return false;
    }

    @Override
    public boolean isTransient() {
        return !persistent;
    }

    @Override
    public Menus getMenus() {
        return MenuFactory
                .newTopLevelMenu(AppConstants.INSTANCE.dashboard_new_displayer())
                .respondsWith(getNewDisplayerCommand())
                .endMenu()
                .newTopLevelMenu(AppConstants.INSTANCE.dashboard_delete_dashboard())
                .respondsWith(getShowDeletePopupCommand())
                .endMenu().build();
    }

    @Override
    public ToolBar getToolBar() {
        return null;
    }

    @Override
    public String getSignatureId() {
        return id;
    }

    @Override
    public Collection<String> getRoles() {
        return Collections.emptyList();
    }

    @Override
    public Collection<String> getTraits() {
        return Collections.emptyList();
    }

    // Internal stuff

    public boolean isPersistent() {
        return persistent;
    }

    public void setPersistent(boolean persistent) {
        this.persistent = persistent;
    }

    protected YesNoCancelPopup deleteDashboardPopup;

    private Command getShowDeletePopupCommand() {
        return new Command() {
            public void execute() {
                deleteDashboardPopup = YesNoCancelPopup.newYesNoCancelPopup(
                        AppConstants.INSTANCE.dashboard_delete_popup_title(),
                        AppConstants.INSTANCE.dashboard_delete_popup_content(),
                        getDoDeleteCommand(),
                        getCancelDeleteCommand(),
                        null);
                deleteDashboardPopup.show();
            }
        };
    }

    private Command getCancelDeleteCommand() {
        return new Command() {
            public void execute() {
                deleteDashboardPopup.hide();
            }
        };
    }

    private Command getDoDeleteCommand() {
        return new Command() {
            public void execute() {
                perspectiveManager.removePerspectiveState(id, new Command() {
                    public void execute() {
                        dashboardManager.removeDashboard(id);
                        placeManager.goTo(getDefaultPerspectiveActivity().getIdentifier());
                    }
                });
            }
        };
    }

    private Command getNewDisplayerCommand() {
        return new Command() {
            public void execute() {
                /* Displayer settings == null => Create a brand new displayer */
                perspectiveCoordinator.editOn();
                DisplayerEditorPopup displayerEditor = getDisplayerEditorPopup();
                displayerEditor.init(null, new DisplayerEditor.Listener() {

                    public void onClose(final DisplayerEditor editor) {
                        perspectiveCoordinator.editOff();
                    }

                    public void onSave(final DisplayerEditor editor) {
                        perspectiveCoordinator.editOff();
                        placeManager.goTo(createPlaceRequest(editor.getDisplayerSettings()));
                        perspectiveManager.savePerspectiveState(new Command() {public void execute() {}});
                    }
                });
            }
        };
    }

    protected DisplayerEditorPopup getDisplayerEditorPopup() {
        Collection<IOCBeanDef<DisplayerEditorPopup>> beans = IOC.getBeanManager().lookupBeans(DisplayerEditorPopup.class);
        IOCBeanDef<DisplayerEditorPopup> beanDef = beans.iterator().next();
        return beanDef.getInstance();
    }

    private PlaceRequest createPlaceRequest(DisplayerSettings displayerSettings) {
        String json = jsonMarshaller.toJsonString(displayerSettings);
        Map<String,String> params = new HashMap<String,String>();
        params.put("json", json);
        params.put("edit", "true");
        params.put("clone", "true");
        return new DefaultPlaceRequest("DisplayerScreen", params);
    }

    private PerspectiveActivity getDefaultPerspectiveActivity() {
        PerspectiveActivity first = null;
        SyncBeanManagerImpl beanManager = (SyncBeanManagerImpl) IOC.getBeanManager();
        Collection<IOCBeanDef<PerspectiveActivity>> perspectives = beanManager.lookupBeans(PerspectiveActivity.class);
        Iterator<IOCBeanDef<PerspectiveActivity>> perspectivesIterator = perspectives.iterator();
        while (perspectivesIterator.hasNext() ) {

            IOCBeanDef<PerspectiveActivity> perspective = perspectivesIterator.next();
            PerspectiveActivity instance = perspective.getInstance();

            if (instance.isDefault()) {
                return instance;
            }
            if (first == null) {
                first = instance;
            }
        }
        return first;
    }
}


text:
*memap* is a simple utility useful to display static memory information required by [mbed](https://github.com/mbedmicro/mbed) applications. This information is produced by analysing the memory map file previously generated by your toolchain.

Note: this tool is showing static RAM usage and the total size of allocated heap and stack space defined at compile time, not the actual heap and stack usage (which may be different depending on your application).

## Table of Contents

1. [Using memap](#using-memap)
1. [Information on memory sections](#info-mem-sections)
1. [Current support](#current-support)
1. [Known problems](#known-problems)

## Using memap

*memap* is automatically invoked after an mbed build finishes succesfully. But it's also possible to manually run the program with different command line options, for example:

```
$> python memap.py
usage: memap.py [-h] -t TOOLCHAIN [-o OUTPUT] [-e EXPORT] [-v] file

Memory Map File Analyser for ARM mbed version 0.3.11

positional arguments:
  file                  memory map file

optional arguments:
  -h, --help            show this help message and exit
  -t TOOLCHAIN, --toolchain TOOLCHAIN
                        select a toolchain used to build the memory map file
                        (ARM, GCC_ARM, IAR)
  -o OUTPUT, --output OUTPUT
                        output file name
  -e EXPORT, --export EXPORT
                        export format (examples: 'json', 'csv-ci', 'table':
                        default)
  -v, --version         show program's version number and exit
```

Example:

```
$> python memap.py GCC_ARM\myprog3.map -t GCC_ARM

+----------------------------+-------+-------+------+
| Module                     | .text | .data | .bss |
+----------------------------+-------+-------+------+
| Fill                       |   170 |     0 | 2294 |
| Misc                       | 36282 |  2220 | 2152 |
| core/hal                   | 15396 |    16 |  568 |
| core/rtos                  |  6751 |    24 | 2662 |
| features/FEATURE_IPV4      |    96 |     0 |   48 |
| frameworks/greentea-client |   912 |    28 |   44 |
| frameworks/utest           |  3079 |     0 |  732 |
| Subtotals                  | 62686 |  2288 | 8500 |
+----------------------------+-------+-------+------+
Allocated Heap: 65540 bytes
Allocated Stack: 32768 bytes
Total Static RAM memory (data + bss): 10788 bytes
Total RAM memory (data + bss + heap + stack): 109096 bytes
Total Flash memory (text + data + misc): 66014 bytes

```

## Information on memory sections

Find here extended description on the multiple memory sections shown in the previous table.

- text: is where the code application and constants are located in Flash
- data: non-zero initialized variables; allocated in both RAM and Flash memory (variables are initialized in RAM at run time from Flash)
- bss: uninitialized data allocated in RAM, or variables initialized to zero
- heap: dynamic allocated memory defined at build time, usually used by malloc, etc, in RAM
- stack: used to store local data, temporary data when branching to a subroutine and context switch info; it's considered dynamic allocated memory region in RAM defined at build time

On the other hand, there are other entries which do not correspond to modules directly and require a bit of clarification:

- Fill: this entry represents the bytes in multiple sections (RAM and Flash) that the toolchain has filled with zeros because requires subsequent data or code to be aligment appropriately in memory
- Misc: it mainly represents helper libraries introduced by the toolchain (e.g. libc) but there might be other modules not part of mbed

## Current support

*memap* has been tested on Windows 7, Linux and Mac.

Supported map files generated by the following toolchains: GCC_ARM, ARM (ARM Compiler 5) and IAR.

## Known problems & New features

This utility is considered 'Alpha' quality at the moment.
Please note, the information generated by this utility may not be fully accurate and may vary from one toolchain to another.

If you are seeing problems or would like new features to be added then please raise a ticket on [GitHub](https://github.com/mbedmicro/mbed/issues) and use ```[memap] ``` in the title.


text:
/*jslint node: true */

/************************************************************************
The MIT License (MIT)

Copyright (c) 2014

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**************************************************************************/

module.exports = function(grunt) {
	"use strict";
	var apigee_conf = require('./grunt/apigee-config.js')
	var helper = require('./grunt/lib/helper-functions.js');
	var searchNReplace = require('./grunt/search-and-replace-files.js');
	require('time-grunt')(grunt);
	// Project configuration.
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		apigee_profiles : apigee_conf.profiles(grunt),//{
		    availabletasks: {
		        tasks: {}
		    },
			clean: ["target"],
			mkdir: {
				all: {
					options: {
						create: ['target', 'target/apiproxy/resources/java/', 'target/java/bin']
					},
				},
			},
			copy: {
				"java-jar" : {
						src: ['java/lib/*.jar', '!java/lib/expressions-1.0.0.jar', '!java/lib/message-flow-1.0.0.jar'],
						dest: 'target/apiproxy/resources/java/', filter: 'isFile', flatten: true, expand : true,
				},
				apiproxy: {
							src: 'apiproxy/**',
							dest: './target/',
				},
				"node-target": { // copy node folder to target for search and replace
							src: './node/**',
							dest: './target/'
				},
				"node-js-root": { //copy app.js and package.json
								expand : true,
								src: './target/node/*',
								dest: './target/apiproxy/resources/node/', filter: 'isFile', flatten: true
					},
			},
		// make a zipfile
		compress: {
			"node-modules": helper.setNodeResources('./target/node/node_modules/' ,{
									mode : 'zip',
									archive: './target/apiproxy/resources/node/node_modules.zip'
								}, [
								{expand: true, cwd: './target/node/node_modules/', src: ['**'], dest: 'node_modules/' } // makes all src relative to cwd
								]),

			"node-public": helper.setNodeResources('./target/node/public/', {
								mode : 'zip',
								archive: './target/apiproxy/resources/node/public.zip'
							},[
								{expand: true, cwd: './target/node/public/', src: ['**'], dest: 'public/' }, // makes all src relative to cwd
							]),
			"node-config": helper.setNodeResources('./target/node/config/', {
								mode : 'zip',
								archive: './target/apiproxy/resources/node/config.zip'
							},[
								{expand: true, cwd: './target/node/config/', src: ['**'], dest: 'config/' }, // makes all src relative to cwd
							]),
			"node-resources": helper.setNodeResources('./target/node/resources/', {
								mode : 'zip',
								archive: './target/apiproxy/resources/node/resources.zip'
							},[
								{expand: true, cwd: './target/node/resources/', src: ['**'], dest: 'resources/' }, // makes all src relative to cwd
							]),
			main: {
				options: {
					mode : 'zip',
					archive: "target/<%= apigee_profiles[grunt.option('env')].apiproxy %>.zip"
				},
				files: [
					{expand: true, cwd: 'target/apiproxy/', src: ['**'], dest: 'apiproxy/' }, // makes all src relative to cwd
					]
				}
		},
		// task for configuration management: search and replace elements within XML files
		xmlpoke: apigee_conf.xmlconfig(grunt.option('env'), grunt),
	    // Configure a mochaTest task
	    mochaTest: {
	    	test: {
	    		options: {
	    			reporter: 'spec', //supported reporters: tap
	    			timeout : 5000,
	    			quiet: false // Optionally suppress output to standard out (defaults to false)
	    		},
	    		src: ["tests/<%= apigee_profiles[grunt.option('env')].apiproxy %>**.js"]
	    	}
	    },
	    jshint: {
		    options: { //see options reference http://www.jshint.com/docs/options/
		    	curly: true,
		    	eqeqeq: true,
		    	eqnull: true,
		    	browser: true,
		    	asi : true,
		    	debug : true,
		    	undef : true,
		    	unused : true,
		    	maxcomplexity : 5,
		    	reporter: require('jshint-stylish')
		    },
		    all: ['Gruntfile.js', 'apiproxy/**/*.js', 'tests/**/*.js', 'tasks/*.js']
		},
	    eslint: {                               // task
	    	options: {
	            config: 'grunt/conf/eslint.json',     // custom config
	            rulesdir: ['grunt/conf/rules']        // custom rules
	        },
	        target: ['Gruntfile.js', 'target/apiproxy/**/*.js', 'tests/**/*.js', 'tasks/*.js']                 // array of files
	    },
		'string-replace': {
			dist : searchNReplace.searchAndReplaceFiles(grunt.option('env'), grunt)
		},
	    shell: {
	        options: {
	            stderr: false,
	            failOnError : true
	        },
	        // Remove comments to enable JavaCallout Policy
	        // javaCompile: {
	        //     command: 'javac -sourcepath ./java/src/**/*.java -d ./target/java/bin -cp java/lib/expressions-1.0.0.jar:java/lib/message-flow-1.0.0.jar:jar:java/lib/message-flow-1.0.1.jar java/src/com/example/SimpleJavaCallout.java',
	        // },
	        // javaJar : {
	        //     command: 'jar cvf target/apiproxy/resources/java/javaCallouts.jar -C target/java/bin .',
	        // },

	        //run jmeter tests from Grunt
/*	        "run_jmeter_tests" : {
	             command: 'mvn install -P <%= grunt.option("env") %>',
	        },*/
          apigee_npm_node_modules : {
               command: "npm install --prefix './node'",
          },
	    },
	    notify: {
	    	task_name: {
	    		options: {
	        	// Task-specific options go here.
	        }
		    },
		    ApiDeployed: {
		    	options: {
		    		message: 'Deployment is ready!'
		    	}
		    }
  		},
        complexity: {
            generic: {
                src: ['target/apiproxy/**/*.js', 'tests/**/*.js', 'tasks/*.js'],
                exclude: ['doNotTest.js'],
                options: {
                    breakOnErrors: true,
                    jsLintXML: 'report.xml',         // create XML JSLint-like report
                    checkstyleXML: 'checkstyle.xml', // create checkstyle report
                    errorsOnly: false,               // show only maintainability errors
                    cyclomatic: [3, 7, 12],          // or optionally a single value, like 3
                    halstead: [8, 13, 20],           // or optionally a single value, like 8
                    maintainability: 100,
                    hideComplexFunctions: false,      // only display maintainability
                    broadcast: false                 // broadcast data over event-bus
                }
            },
        },
		prompt: helper.prompts(grunt)
// Configure this task to support KVM data config migrations
/*      "apigee_kvm": {
          "testmyapi-test" : {
            options: {
              type: "env"
            },
            files: [{src: ['config/kvm/testmyapi/testmyapi-test/*.json']},
            ]
          },
          "testmyapi-prod" : {
            options: {
              type: "env"
            },
            files: [{src: ['config/kvm/testmyapi/testmyapi-prod/*.json']},
            ]
          },
          "testmyapi" : {
            options: {
              type: "org"
            },
            files: [{src: ['config/kvm/testmyapi/*.json']},
            ]
          }
      },*/
	})

require('load-grunt-tasks')(grunt);

// importKVM at Organization and Environment level. See apigee_kvm task above
grunt.registerTask('importKVMs', ['apigee_kvm:' + grunt.config.get("apigee_profiles")[grunt.option('env')].org + '-' + grunt.option("env"), 'apigee_kvm:' + grunt.config.get("apigee_profiles")[grunt.option('env')].org]);

grunt.registerTask('buildApiBundle', 'Build zip without importing it to Edge', ['apigeeGruntPluginBanner', 'prompt', 'clean', 'saveGitRevision', 'shell:apigee_npm_node_modules', 'mkdir','copy', 'xmlpoke', 'string-replace', 'jshint', 'eslint', 'complexity', /*'shell'*/ 'compressAlias']);
  //1. import revision bumping revision id
  grunt.registerTask('IMPORT_DEPLOY_BUMP_REVISION', [ 'buildApiBundle', 'getDeployedApiRevisions', 'undeployApiRevision',
    'apigee_import_api_bundle', 'installNpmRevisionAlias', 'deployApiRevisionAlias', 'executeTests', /*'shell:run_jmeter_tests',*/ 'notify:ApiDeployed']);

  //2. update revision keeping same id
  grunt.registerTask('UPDATE_CURRENT_REVISION', [ 'buildApiBundle', 'getDeployedApiRevisions', 'undeployApiRevision',
    'updateApiRevision', 'installNpmRevisionAlias', 'deployApiRevisionAlias', 'executeTests', 'notify:ApiDeployed']);

  //3. import revision and run seamless deployment
  grunt.registerTask('DEPLOY_IMPORT_BUMP_SEAMLESS_REVISION', [ 'buildApiBundle', 'getDeployedApiRevisions', 'apigee_import_api_bundle',
  	'installNpmRevisionAlias', 'deployApiRevisionAlias', 'executeTests', /*'shell:run_jmeter_tests',*/ 'notify:ApiDeployed']);

  //set to DEPLOY_IMPORT_BUMP_SEAMLESS_REVISION by default. This is critical for production for seamless deploymen and not lose traffic
  grunt.registerTask('default', [ /*'importKVMs',*/'DEPLOY_IMPORT_BUMP_SEAMLESS_REVISION' ]);

	grunt.loadTasks('grunt/tasks');
	if(grunt.option.flags().indexOf('--help') === -1 && !grunt.option('env')) {
		grunt.fail.fatal('Invalid environment --env={env}.')
	}
};