repo
string
commit
string
message
string
diff
string
Peeja/rubot
24061c3c8972277e67ec14f30dc603e2fcde7fc6
Ignoring test.rb.
diff --git a/.gitignore b/.gitignore index dc3650f..8c2e3bc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ ._* .DS_Store doc coverage pkg + +# Used locally for testing Rubot. Convenient to keep it in the tree. +test.rb \ No newline at end of file
Peeja/rubot
0dffdd4a6a1ecbdc5ba6e869883e7b74c920a2db
Implemented Aria::Robot#options[:host].
diff --git a/ext/rubot_aria/extconf.rb b/ext/rubot_aria/extconf.rb index a5d8945..8a9ed86 100644 --- a/ext/rubot_aria/extconf.rb +++ b/ext/rubot_aria/extconf.rb @@ -1,10 +1,9 @@ require 'rubygems' require 'mkmf-rice' -require 'facets/module/alias' dir_config("Aria", "/usr/local/Aria/include", "/usr/local/Aria/lib") unless have_library('Aria') exit end create_makefile('rubot_aria') diff --git a/ext/rubot_aria/rubot_aria.cpp b/ext/rubot_aria/rubot_aria.cpp index 79a468e..0bbaea4 100644 --- a/ext/rubot_aria/rubot_aria.cpp +++ b/ext/rubot_aria/rubot_aria.cpp @@ -1,102 +1,115 @@ +#include <csignal> +#include <iostream> #include "rice/Module.hpp" #include "rice/Data_Type.hpp" #include "rice/Constructor.hpp" #include "Aria.h" +using namespace std; using namespace Rice; // Initializes Aria if it hasn't been done already. void ensureAriaInit() { static char inited = 0; - if (!inited) Aria::init(); + if (!inited) Aria::init(Aria::SIGHANDLE_NONE); inited = 1; } /* * RAAction * Generic ArAction that runs a Ruby proc when it fires. * */ class RAAction : public ArAction { public: RAAction(const char *name); virtual ~RAAction(void) {}; virtual ArActionDesired *fire(ArActionDesired currentDesired); protected: ArActionDesired myDesired; }; RAAction::RAAction(const char *name) : ArAction(name) {} ArActionDesired *RAAction::fire(ArActionDesired currentDesired) { myDesired.reset(); myDesired.merge(&currentDesired); return &myDesired; } /* * RARobotManager * Encapsulates an ArRobot and its connection. * */ class RARobotManager { public: RARobotManager(); void go(const char *argString); private: ArRobot myRobot; }; +// Not working yet +// void handler(int signum) +// { +// cout << "Got signal." << endl; +// } + RARobotManager::RARobotManager() : myRobot() {} // Connect to robot and run. void RARobotManager::go(const char *argString="") { ensureAriaInit(); ArArgumentBuilder args; args.add(argString); ArSimpleConnector conn(&args); conn.parseArgs(); // TODO: Handle connection error conn.connectRobot(&myRobot); myRobot.enableMotors(); + + // Not working yet. + // signal(SIGINT, handler); + myRobot.run(true); } extern "C" void Init_rubot_aria() { // Define Rubot::Adapters::Aria. Object rb_MRubot = Class(rb_cObject).const_get("Rubot"); Object rb_MAdapters = Module(rb_MRubot).const_get("Adapters"); Object rb_MAria = Module(rb_MAdapters) .define_module("Aria") ; // Define Rubot::Adapters::Aria::RobotManager. // Rubot::Adapters::Aria::Robot is defined in Ruby and uses this class. Data_Type<RARobotManager> rb_cAriaRobot = Module(rb_MAria) .define_class<RARobotManager>("RobotManager") .define_constructor(Constructor<RARobotManager>()) .define_method("go",&RARobotManager::go) ; } diff --git a/lib/rubot/adapters/aria/robot.rb b/lib/rubot/adapters/aria/robot.rb index cb5092b..519146f 100644 --- a/lib/rubot/adapters/aria/robot.rb +++ b/lib/rubot/adapters/aria/robot.rb @@ -1,14 +1,16 @@ module Rubot::Adapters::Aria class Robot attr_reader :options def initialize @options = {} @manager = RobotManager.new end def run - @manager.go "" + args = '' + args << "-rh #{@options[:host]}" if @options[:host] + @manager.go args end end end diff --git a/spec/rubot/adapters/aria/robot_spec.rb b/spec/rubot/adapters/aria/robot_spec.rb index 73c8e68..f5d6b31 100644 --- a/spec/rubot/adapters/aria/robot_spec.rb +++ b/spec/rubot/adapters/aria/robot_spec.rb @@ -1,26 +1,32 @@ require File.join(File.dirname(__FILE__), %w[.. .. .. spec_helper]) # fred = Rubot::Adapters::Aria::Robot.new -# fred.options[:host] = localhost +# fred.options[:host] = 'localhost' include Rubot::Adapters::Aria describe Robot do before(:each) do @mock_manager = mock("manager") RobotManager.should_receive(:new).and_return(@mock_manager) @robot = Robot.new end it "should have options hash" do @robot.options[:be_awesome] = true @robot.options.keys.should include(:be_awesome) end it "should run the robot" do @mock_manager.should_receive(:go) @robot.run end - # Test args + it "should connect to the specified host" do + @robot.options[:host] = 'robothost' + @mock_manager.should_receive(:go).with(/-rh robothost/) + @robot.run + end + + # Add serial connection support. end
Peeja/rubot
aa39e361fb5356d68874a61f8fd85224be387d1e
Implemented Aria::Robot#run.
diff --git a/lib/rubot/adapters/aria/robot.rb b/lib/rubot/adapters/aria/robot.rb index 78b8fd3..cb5092b 100644 --- a/lib/rubot/adapters/aria/robot.rb +++ b/lib/rubot/adapters/aria/robot.rb @@ -1,7 +1,14 @@ -class Rubot::Adapters::Aria::Robot - attr_reader :options +module Rubot::Adapters::Aria + class Robot + attr_reader :options - def initialize - @options = {} + def initialize + @options = {} + @manager = RobotManager.new + end + + def run + @manager.go "" + end end end diff --git a/spec/rubot/adapters/aria/robot_spec.rb b/spec/rubot/adapters/aria/robot_spec.rb index 6d25129..73c8e68 100644 --- a/spec/rubot/adapters/aria/robot_spec.rb +++ b/spec/rubot/adapters/aria/robot_spec.rb @@ -1,15 +1,26 @@ require File.join(File.dirname(__FILE__), %w[.. .. .. spec_helper]) -# fred = Rubot::Adapters::Aria::Robot +# fred = Rubot::Adapters::Aria::Robot.new # fred.options[:host] = localhost -describe Rubot::Adapters::Aria::Robot do +include Rubot::Adapters::Aria + +describe Robot do before(:each) do - @robot = Rubot::Adapters::Aria::Robot.new + @mock_manager = mock("manager") + RobotManager.should_receive(:new).and_return(@mock_manager) + @robot = Robot.new end it "should have options hash" do @robot.options[:be_awesome] = true @robot.options.keys.should include(:be_awesome) end + + it "should run the robot" do + @mock_manager.should_receive(:go) + @robot.run + end + + # Test args end
Peeja/rubot
514466c480d2c7762b3233746fa5b2fcfbbb6734
Removed Rubot::Robot; robots can be duck-typed and don't need a base class. Took out Rubot's capacity to keep track of robots. Robots don't need to be listed by name in a directory, just make a robot and keep it in a variable. DSL layer will implement names. Shifted the tree a bit to make implementation files line up better with their specs.
diff --git a/lib/rubot.rb b/lib/rubot.rb index 023abd6..0ed6085 100644 --- a/lib/rubot.rb +++ b/lib/rubot.rb @@ -1,29 +1,15 @@ # Require everything except things under rubot/adapters/ (which load lazily). # (Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')] - # Dir[File.join(::File.dirname(__FILE__), 'rubot', 'adapters', '**')]).sort.each {|rb| require rb} require 'facets/string/case' unless defined? Rubot require 'rubot/adapters' require 'rubot/meta' -require 'rubot/robot' module Rubot - # Returns a hash of the robots Rubot knows about. - # my_favorite_bot = Rubot.robots[:fred] - def self.robots - @@robots ||= {} - end - - # Creates a new robot named +name+ using the adapter +adapter+ and adds it - # to Rubot. - def self.add_robot(name, adapter) - mod_name = adapter.to_s.camelcase(true).to_sym - - robots[name] = Adapters.const_get(mod_name).const_get(:Robot).new name - end end -end \ No newline at end of file +end diff --git a/lib/rubot/adapters/aria.rb b/lib/rubot/adapters/aria.rb index 9e77eab..234197a 100644 --- a/lib/rubot/adapters/aria.rb +++ b/lib/rubot/adapters/aria.rb @@ -1,10 +1,4 @@ require 'rubot' if not defined? Rubot require 'rubot_aria' -class Rubot::Adapters::Aria::Robot - attr_reader :options - - def initialize - @options = [] - end -end \ No newline at end of file +require File.dirname(__FILE__) + "/aria/robot" diff --git a/lib/rubot/adapters/aria/robot.rb b/lib/rubot/adapters/aria/robot.rb new file mode 100644 index 0000000..78b8fd3 --- /dev/null +++ b/lib/rubot/adapters/aria/robot.rb @@ -0,0 +1,7 @@ +class Rubot::Adapters::Aria::Robot + attr_reader :options + + def initialize + @options = {} + end +end diff --git a/lib/rubot/robot.rb b/lib/rubot/robot.rb deleted file mode 100644 index 090d457..0000000 --- a/lib/rubot/robot.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Rubot::Robot - attr_reader :name - - def initialize(name) - @name = name.to_s - end -end diff --git a/spec/adapters/aria/robot_spec.rb b/spec/adapters/aria/robot_spec.rb deleted file mode 100644 index 5f8a6ae..0000000 --- a/spec/adapters/aria/robot_spec.rb +++ /dev/null @@ -1,12 +0,0 @@ -require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) - -describe Rubot::Adapters::Aria::Robot do - before(:each) do - @robot = Rubot::Adapters::Aria::Robot.new - end - - it "should have options array" do - @robot.options << :be_awesome - @robot.options.should include(:be_awesome) - end -end diff --git a/spec/adapters/aria_spec.rb b/spec/adapters/aria_spec.rb deleted file mode 100644 index e9b75f9..0000000 --- a/spec/adapters/aria_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require File.join(File.dirname(__FILE__), %w[.. spec_helper]) - -describe Rubot::Adapters::Aria do - -end diff --git a/spec/adapters/aria/robot_manager_spec.rb b/spec/rubot/adapters/aria/robot_manager_spec.rb similarity index 84% rename from spec/adapters/aria/robot_manager_spec.rb rename to spec/rubot/adapters/aria/robot_manager_spec.rb index 83be1cc..845ea17 100644 --- a/spec/adapters/aria/robot_manager_spec.rb +++ b/spec/rubot/adapters/aria/robot_manager_spec.rb @@ -1,12 +1,12 @@ -require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) +require File.join(File.dirname(__FILE__), %w[.. .. .. spec_helper]) describe Rubot::Adapters::Aria::RobotManager do it "should be creatable" do lambda { Rubot::Adapters::Aria::RobotManager.new }.should_not raise_error end # We can't really test that #go works, but we can make sure it's defined. it "should connect to robot" do Rubot::Adapters::Aria::RobotManager.instance_methods.should include("go") end end diff --git a/spec/rubot/adapters/aria/robot_spec.rb b/spec/rubot/adapters/aria/robot_spec.rb new file mode 100644 index 0000000..6d25129 --- /dev/null +++ b/spec/rubot/adapters/aria/robot_spec.rb @@ -0,0 +1,15 @@ +require File.join(File.dirname(__FILE__), %w[.. .. .. spec_helper]) + +# fred = Rubot::Adapters::Aria::Robot +# fred.options[:host] = localhost + +describe Rubot::Adapters::Aria::Robot do + before(:each) do + @robot = Rubot::Adapters::Aria::Robot.new + end + + it "should have options hash" do + @robot.options[:be_awesome] = true + @robot.options.keys.should include(:be_awesome) + end +end diff --git a/spec/rubot/adapters/aria_spec.rb b/spec/rubot/adapters/aria_spec.rb new file mode 100644 index 0000000..e93a370 --- /dev/null +++ b/spec/rubot/adapters/aria_spec.rb @@ -0,0 +1,5 @@ +require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) + +describe Rubot::Adapters::Aria do + +end diff --git a/spec/adapters/spec_helper.rb b/spec/rubot/adapters/spec_helper.rb similarity index 100% rename from spec/adapters/spec_helper.rb rename to spec/rubot/adapters/spec_helper.rb diff --git a/spec/rubot/robot_spec.rb b/spec/rubot/robot_spec.rb deleted file mode 100644 index 253bbae..0000000 --- a/spec/rubot/robot_spec.rb +++ /dev/null @@ -1,17 +0,0 @@ -require File.dirname(__FILE__) + '/../spec_helper' - -describe Rubot::Robot do - before(:each) do - @robot = Rubot::Robot.new :harry - end - - it "should have a name" do - @robot.name.should == "harry" - end - - it "should have behaviors" do - pending - @robot.should respond_to(:behaviors) - @robot.behaviors.should respond_to(:[]) - end -end diff --git a/spec/rubot_spec.rb b/spec/rubot_spec.rb index f4ad9ef..d1c1bcd 100644 --- a/spec/rubot_spec.rb +++ b/spec/rubot_spec.rb @@ -1,22 +1,4 @@ require File.join(File.dirname(__FILE__), %w[spec_helper]) -module Rubot::Adapters::AcmeRobotics - class Robot < Rubot::Robot; end -end - describe Rubot do - it "should have robots" do - Rubot.should respond_to(:robots) - Rubot.robots.should respond_to(:[]) - end - - it "should create robots" do - Rubot.should respond_to(:add_robot) - Rubot.add_robot(:fred, :acme_robotics) - Rubot.robots[:fred].should be_a_kind_of(Rubot::Adapters::AcmeRobotics::Robot) - end - - it "should not add a robot from an unknown adapter" do - lambda { Rubot.add_robot(:roger, :johnson_bots) }.should raise_error(Rubot::AdapterMissingError) - end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f7deae2..2ca1de6 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,17 +1,19 @@ # $Id$ -require File.expand_path( - File.join(File.dirname(__FILE__), %w[.. lib rubot])) +$LOAD_PATH.unshift File.join(File.dirname(__FILE__), %w[.. ext rubot_aria]) +$LOAD_PATH.unshift File.join(File.dirname(__FILE__), %w[.. ext rubot_asimov]) +$LOAD_PATH.unshift File.join(File.dirname(__FILE__), %w[.. lib]) +require 'rubot' Spec::Runner.configure do |config| # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr end # EOF
Peeja/rubot
ad61a7f9eb03f7b608d90610a6eba5f54d5e2505
Changed a lot of things. Committing and getting back on the wagon while tests are passing.
diff --git a/Rakefile b/Rakefile index 7ad09da..83862ed 100644 --- a/Rakefile +++ b/Rakefile @@ -1,26 +1,27 @@ # Look in the tasks/setup.rb file for the various options that can be # configured in this Rakefile. The .rake files in the tasks directory # are where the options are used. load 'tasks/setup.rb' ensure_in_path 'lib' require 'rubot' task :default => 'spec:run' PROJ.name = 'rubot' PROJ.authors = 'Peter Jaros (Peeja)' PROJ.email = 'peter.a.jaros@gmail.com' PROJ.url = 'FIXME (project homepage)' PROJ.rubyforge_name = 'rubot' PROJ.spec_opts += File.read('spec/spec.opts').split +PROJ.spec_opts << '-fs' # Don't expect test coverage of any file with an absolute path. PROJ.rcov_opts << '--exclude' << '^/' << '--exclude' << 'meta.rb$' PROJ.rcov_threshold_exact = true PROJ.exclude << '^.git/' << '.gitignore$' << '.DS_Store$' # EOF diff --git a/ext/rubot_aria/rubot_aria.cpp b/ext/rubot_aria/rubot_aria.cpp index 1ad88f5..79a468e 100644 --- a/ext/rubot_aria/rubot_aria.cpp +++ b/ext/rubot_aria/rubot_aria.cpp @@ -1,26 +1,102 @@ #include "rice/Module.hpp" #include "rice/Data_Type.hpp" #include "rice/Constructor.hpp" #include "Aria.h" using namespace Rice; +// Initializes Aria if it hasn't been done already. +void ensureAriaInit() +{ + static char inited = 0; + if (!inited) Aria::init(); + inited = 1; +} + + +/* + * RAAction + * Generic ArAction that runs a Ruby proc when it fires. + * + */ + +class RAAction : public ArAction +{ +public: + RAAction(const char *name); + virtual ~RAAction(void) {}; + virtual ArActionDesired *fire(ArActionDesired currentDesired); + +protected: + ArActionDesired myDesired; +}; + +RAAction::RAAction(const char *name) + : ArAction(name) +{} + +ArActionDesired *RAAction::fire(ArActionDesired currentDesired) +{ + myDesired.reset(); + myDesired.merge(&currentDesired); + + + return &myDesired; +} + + +/* + * RARobotManager + * Encapsulates an ArRobot and its connection. + * + */ + +class RARobotManager +{ +public: + RARobotManager(); + void go(const char *argString); + +private: + ArRobot myRobot; +}; + +RARobotManager::RARobotManager() + : myRobot() {} + +// Connect to robot and run. +void RARobotManager::go(const char *argString="") +{ + ensureAriaInit(); + ArArgumentBuilder args; + args.add(argString); + ArSimpleConnector conn(&args); + conn.parseArgs(); + // TODO: Handle connection error + conn.connectRobot(&myRobot); + myRobot.enableMotors(); + myRobot.run(true); +} + + + + + extern "C" void Init_rubot_aria() { // Define Rubot::Adapters::Aria. Object rb_MRubot = Class(rb_cObject).const_get("Rubot"); Object rb_MAdapters = Module(rb_MRubot).const_get("Adapters"); - Object rb_MAria = Module(rb_MAdapters).define_module("Aria") - .define_module_function("init", Aria::init) - ; + Object rb_MAria = Module(rb_MAdapters) + .define_module("Aria") + ; - // Define Rubot::Adapters::Aria::Robot_. - // Rubot::Adapters::Aria::Robot wraps this class as a Rubot::Robot subclass, - // which Rice won't let us define while wrapping a C++ class. - Data_Type<ArRobot> rb_cAriaRobot = Module(rb_MAria) - .define_class<ArRobot>("Robot_") - .define_constructor(Constructor<ArRobot>()) - .define_method("addRangeDevice",&ArRobot::addRangeDevice) - ; + // Define Rubot::Adapters::Aria::RobotManager. + // Rubot::Adapters::Aria::Robot is defined in Ruby and uses this class. + Data_Type<RARobotManager> rb_cAriaRobot = Module(rb_MAria) + .define_class<RARobotManager>("RobotManager") + .define_constructor(Constructor<RARobotManager>()) + .define_method("go",&RARobotManager::go) + ; } diff --git a/lib/rubot.rb b/lib/rubot.rb index bd7f443..023abd6 100644 --- a/lib/rubot.rb +++ b/lib/rubot.rb @@ -1,20 +1,29 @@ # Require everything except things under rubot/adapters/ (which load lazily). -(Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')] - - Dir[File.join(::File.dirname(__FILE__), 'rubot', 'adapters', '**')]).sort.each {|rb| require rb} +# (Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')] - +# Dir[File.join(::File.dirname(__FILE__), 'rubot', 'adapters', '**')]).sort.each {|rb| require rb} + require 'facets/string/case' +unless defined? Rubot + +require 'rubot/adapters' +require 'rubot/meta' +require 'rubot/robot' + module Rubot # Returns a hash of the robots Rubot knows about. # my_favorite_bot = Rubot.robots[:fred] def self.robots @@robots ||= {} end # Creates a new robot named +name+ using the adapter +adapter+ and adds it # to Rubot. def self.add_robot(name, adapter) mod_name = adapter.to_s.camelcase(true).to_sym robots[name] = Adapters.const_get(mod_name).const_get(:Robot).new name end end + +end \ No newline at end of file diff --git a/lib/rubot/adapters.rb b/lib/rubot/adapters.rb index 99c36a8..b18adb2 100644 --- a/lib/rubot/adapters.rb +++ b/lib/rubot/adapters.rb @@ -1,28 +1,38 @@ require 'facets/string/case' +require 'facets/module/alias' # This module contains the robotics adapters. For instance, the ACME # Robotics adapter would be <tt>Rubot::Adapters::AcmeRobotics</tt>. Its robot # class would be <tt>Rubot::Adapters::AcmeRobotics::Robot</tt>, and one can be # created with # # Rubot.add_robot(:fred, :acme_robotics) # # or, in Rubot syntax, # # robot :fred do # adapter :acme_robotics # end -module Adapters +module Rubot # Raised when attempting to create a robot with an unrecognized adapter. class AdapterMissingError < Exception; end - - def self.const_missing(name) - begin - little_name = name.to_s.snakecase - require "rubot/adapters/#{little_name}" - return get_const(name) - rescue LoadError, NameError - raise AdapterMissingError, "Adapter #{mod_name} not found." + + module Adapters + class << self + def const_missing_with_autoload(name) + begin + req_name = "rubot/adapters/#{name.to_s.snakecase}" + require req_name + if const_defined? name + return const_get(name) + else + raise AdapterMissingError, "Adapter #{name} not loaded by '#{req_name}'." + end + rescue LoadError + raise AdapterMissingError, "Adapter #{name} not found." + end + end + alias_method_chain :const_missing, :autoload end end end diff --git a/lib/rubot/adapters/aria.rb b/lib/rubot/adapters/aria.rb index 3da1eb4..9e77eab 100644 --- a/lib/rubot/adapters/aria.rb +++ b/lib/rubot/adapters/aria.rb @@ -1,6 +1,10 @@ -require 'rubot' +require 'rubot' if not defined? Rubot require 'rubot_aria' -class Rubot::Adapters::Aria::Robot < Rubot::Robot +class Rubot::Adapters::Aria::Robot + attr_reader :options + def initialize + @options = [] + end end \ No newline at end of file diff --git a/spec/adapters/aria/robot_manager_spec.rb b/spec/adapters/aria/robot_manager_spec.rb new file mode 100644 index 0000000..83be1cc --- /dev/null +++ b/spec/adapters/aria/robot_manager_spec.rb @@ -0,0 +1,12 @@ +require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) + +describe Rubot::Adapters::Aria::RobotManager do + it "should be creatable" do + lambda { Rubot::Adapters::Aria::RobotManager.new }.should_not raise_error + end + + # We can't really test that #go works, but we can make sure it's defined. + it "should connect to robot" do + Rubot::Adapters::Aria::RobotManager.instance_methods.should include("go") + end +end diff --git a/spec/adapters/aria/robot_spec.rb b/spec/adapters/aria/robot_spec.rb index 86519e1..5f8a6ae 100644 --- a/spec/adapters/aria/robot_spec.rb +++ b/spec/adapters/aria/robot_spec.rb @@ -1,16 +1,12 @@ -require File.join(File.dirname(__FILE__), %w[.. spec_helper]) - -unless $spec_skip +require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) describe Rubot::Adapters::Aria::Robot do - it "should be createable" do - lambda { Aria::Robot.new }.should_not raise_error(TypeError) + before(:each) do + @robot = Rubot::Adapters::Aria::Robot.new end - it "should let us add a range device" do - r = Aria::Robot.new - lambda { r.addRangeDevice }.should_not raise_error(NoMethodError) + it "should have options array" do + @robot.options << :be_awesome + @robot.options.should include(:be_awesome) end end - -end \ No newline at end of file diff --git a/spec/load_paths.rb b/spec/load_paths.rb index 76d38ad..9b50ca0 100644 --- a/spec/load_paths.rb +++ b/spec/load_paths.rb @@ -1,6 +1,9 @@ # Adds load paths to extensions for RSpec. At build, extensions end up in lib/ anyhow. Dir['ext/*'].each do |dir| if test ?d, dir - $LOAD_PATH << dir + $LOAD_PATH.unshift dir end end + +# The rake task takes care of this for us, but autotest needs it. +$LOAD_PATH.unshift 'lib' unless $LOAD_PATH.include? 'lib' \ No newline at end of file
Peeja/rubot
08f79e2b1bfd14f230cde4365646fcbcf6e35dd9
Refactoring adaptor system.
diff --git a/.autotest b/.autotest index 3bc541c..e91a6d2 100644 --- a/.autotest +++ b/.autotest @@ -1,17 +1,20 @@ Autotest.add_hook :initialize do |at| + # Ignore the ._* files TextMate likes to leave about. + at.add_exception(/\/\._[^\/]*$/) + # Set up mapping for extensions. # When foo.so is changed, rerun all specs under spec/ext/foo/. at.add_mapping(/\/([^\/]*).so$/) do |f, m| ext = m[1] r = Regexp.new("ext/#{ext}/.*_spec\.rb$") at.files_matching r end # Set up mapping for spec helpers. # When foo/spec_helper.rb is changed, rerun all specs under foo/. # Doesn't do anything; not sure why. # at.add_mapping(/^(.*)\/spec_helper.rb$/) do |f, m| # dir = m[1] # Dir["#{dir}/**/*.rb"] # end end diff --git a/Rakefile b/Rakefile index 5af381e..7ad09da 100644 --- a/Rakefile +++ b/Rakefile @@ -1,26 +1,26 @@ # Look in the tasks/setup.rb file for the various options that can be # configured in this Rakefile. The .rake files in the tasks directory # are where the options are used. load 'tasks/setup.rb' ensure_in_path 'lib' require 'rubot' task :default => 'spec:run' PROJ.name = 'rubot' PROJ.authors = 'Peter Jaros (Peeja)' PROJ.email = 'peter.a.jaros@gmail.com' PROJ.url = 'FIXME (project homepage)' PROJ.rubyforge_name = 'rubot' -PROJ.spec_opts << '--color' +PROJ.spec_opts += File.read('spec/spec.opts').split # Don't expect test coverage of any file with an absolute path. PROJ.rcov_opts << '--exclude' << '^/' << '--exclude' << 'meta.rb$' PROJ.rcov_threshold_exact = true PROJ.exclude << '^.git/' << '.gitignore$' << '.DS_Store$' # EOF diff --git a/ext/rubot_aria/rubot_aria.cpp b/ext/rubot_aria/rubot_aria.cpp index 6f38d05..1ad88f5 100644 --- a/ext/rubot_aria/rubot_aria.cpp +++ b/ext/rubot_aria/rubot_aria.cpp @@ -1,23 +1,26 @@ #include "rice/Module.hpp" #include "rice/Data_Type.hpp" #include "rice/Constructor.hpp" #include "Aria.h" using namespace Rice; -const char *convertBool(Object /* self */, int val) { - return ArUtil::convertBool(val); -} - extern "C" void Init_rubot_aria() { - Module rb_MAria = - define_module("Aria") - // .define_module_function("init", init) - .define_module_function("convertBool", convertBool); + // Define Rubot::Adapters::Aria. + Object rb_MRubot = Class(rb_cObject).const_get("Rubot"); + Object rb_MAdapters = Module(rb_MRubot).const_get("Adapters"); + Object rb_MAria = Module(rb_MAdapters).define_module("Aria") + .define_module_function("init", Aria::init) + ; - Data_Type<ArRobot> rb_cRobot = rb_MAria.define_class<ArRobot>("Robot") - .define_constructor(Constructor<ArRobot>()) - .define_method("addRangeDevice",&ArRobot::addRangeDevice); + // Define Rubot::Adapters::Aria::Robot_. + // Rubot::Adapters::Aria::Robot wraps this class as a Rubot::Robot subclass, + // which Rice won't let us define while wrapping a C++ class. + Data_Type<ArRobot> rb_cAriaRobot = Module(rb_MAria) + .define_class<ArRobot>("Robot_") + .define_constructor(Constructor<ArRobot>()) + .define_method("addRangeDevice",&ArRobot::addRangeDevice) + ; } diff --git a/lib/rubot.rb b/lib/rubot.rb index 2978998..bd7f443 100644 --- a/lib/rubot.rb +++ b/lib/rubot.rb @@ -1,42 +1,20 @@ # Require everything except things under rubot/adapters/ (which load lazily). (Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')] - Dir[File.join(::File.dirname(__FILE__), 'rubot', 'adapters', '**')]).sort.each {|rb| require rb} require 'facets/string/case' -module Rubot - - # This module contains the robotics adapters. For instance, the ACME - # Robotics adapter would be <tt>Rubot::Adapters::AcmeRobotics</tt>. Its robot - # class would be <tt>Rubot::Adapters::AcmeRobotics::Robot</tt>, and one can be - # created with - # - # Rubot.add_robot(:fred, :acme_robotics) - # - # or, in Rubot syntax, - # - # robot :fred do - # adapter :acme_robotics - # end - module Adapters; end - - # Raised when attempting to create a robot with an unrecognized adapter. - class AdapterMissingError < Exception; end - +module Rubot # Returns a hash of the robots Rubot knows about. # my_favorite_bot = Rubot.robots[:fred] def self.robots @@robots ||= {} end # Creates a new robot named +name+ using the adapter +adapter+ and adds it # to Rubot. def self.add_robot(name, adapter) mod_name = adapter.to_s.camelcase(true).to_sym - unless Adapters.const_defined?(mod_name) - raise AdapterMissingError, "Adapter #{mod_name} not found." - end - robots[name] = Adapters.const_get(mod_name).const_get(:Robot).new name end end diff --git a/lib/rubot/adapters.rb b/lib/rubot/adapters.rb new file mode 100644 index 0000000..99c36a8 --- /dev/null +++ b/lib/rubot/adapters.rb @@ -0,0 +1,28 @@ +require 'facets/string/case' + +# This module contains the robotics adapters. For instance, the ACME +# Robotics adapter would be <tt>Rubot::Adapters::AcmeRobotics</tt>. Its robot +# class would be <tt>Rubot::Adapters::AcmeRobotics::Robot</tt>, and one can be +# created with +# +# Rubot.add_robot(:fred, :acme_robotics) +# +# or, in Rubot syntax, +# +# robot :fred do +# adapter :acme_robotics +# end +module Adapters + # Raised when attempting to create a robot with an unrecognized adapter. + class AdapterMissingError < Exception; end + + def self.const_missing(name) + begin + little_name = name.to_s.snakecase + require "rubot/adapters/#{little_name}" + return get_const(name) + rescue LoadError, NameError + raise AdapterMissingError, "Adapter #{mod_name} not found." + end + end +end diff --git a/lib/rubot/adapters/aria.rb b/lib/rubot/adapters/aria.rb index b37aead..3da1eb4 100644 --- a/lib/rubot/adapters/aria.rb +++ b/lib/rubot/adapters/aria.rb @@ -1,2 +1,6 @@ require 'rubot' require 'rubot_aria' + +class Rubot::Adapters::Aria::Robot < Rubot::Robot + +end \ No newline at end of file diff --git a/spec/ext/rubot_aria/aria/robot_spec.rb b/spec/adapters/aria/robot_spec.rb similarity index 88% rename from spec/ext/rubot_aria/aria/robot_spec.rb rename to spec/adapters/aria/robot_spec.rb index 4d79e1a..86519e1 100644 --- a/spec/ext/rubot_aria/aria/robot_spec.rb +++ b/spec/adapters/aria/robot_spec.rb @@ -1,16 +1,16 @@ require File.join(File.dirname(__FILE__), %w[.. spec_helper]) unless $spec_skip -describe Aria::Robot do +describe Rubot::Adapters::Aria::Robot do it "should be createable" do lambda { Aria::Robot.new }.should_not raise_error(TypeError) end it "should let us add a range device" do r = Aria::Robot.new lambda { r.addRangeDevice }.should_not raise_error(NoMethodError) end end end \ No newline at end of file diff --git a/spec/adapters/aria_spec.rb b/spec/adapters/aria_spec.rb new file mode 100644 index 0000000..e9b75f9 --- /dev/null +++ b/spec/adapters/aria_spec.rb @@ -0,0 +1,5 @@ +require File.join(File.dirname(__FILE__), %w[.. spec_helper]) + +describe Rubot::Adapters::Aria do + +end diff --git a/spec/adapters/spec_helper.rb b/spec/adapters/spec_helper.rb new file mode 100644 index 0000000..48a32bd --- /dev/null +++ b/spec/adapters/spec_helper.rb @@ -0,0 +1,16 @@ +# require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) +# +# # TODO: Refactor and grep the error string to find the real problem. +# begin +# # If we get a LoadError, let the compiler catch up and try again. +# begin +# require File.join(File.dirname(__FILE__), %w[.. .. .. ext rubot_aria rubot_aria]) +# rescue LoadError => e +# sleep 0.5 +# require File.join(File.dirname(__FILE__), %w[.. .. .. ext rubot_aria rubot_aria]) +# end +# $spec_skip = false +# rescue LoadError => e +# puts "Extension 'rubot_aria' not built. Skipping..." +# $spec_skip = true +# end diff --git a/spec/ext/rubot_aria/aria_spec.rb b/spec/ext/rubot_aria/aria_spec.rb deleted file mode 100644 index a9f31d5..0000000 --- a/spec/ext/rubot_aria/aria_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -# $Id$ - -require File.join(File.dirname(__FILE__), %w[spec_helper]) - -unless $spec_skip - -describe Aria do - it "should provide Aria::Init()" do - pending - lambda { Aria::init }.should_not raise_error(NoMethodError) - end - - it "should convert ints to bools" do - Aria::convertBool(0).should == "false" - Aria::convertBool(1).should == "true" - end -end - -end - -# EOF diff --git a/spec/ext/rubot_aria/spec_helper.rb b/spec/ext/rubot_aria/spec_helper.rb deleted file mode 100644 index c0346ea..0000000 --- a/spec/ext/rubot_aria/spec_helper.rb +++ /dev/null @@ -1,16 +0,0 @@ -require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) - -# TODO: Refactor and grep the error string to find the real problem. -begin - # If we get a LoadError, let the compiler catch up and try again. - begin - require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) - rescue LoadError => e - sleep 0.5 - require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) - end - $spec_skip = false -rescue LoadError => e - puts "Extension 'aria' not built. Skipping..." - $spec_skip = true -end diff --git a/spec/load_paths.rb b/spec/load_paths.rb new file mode 100644 index 0000000..76d38ad --- /dev/null +++ b/spec/load_paths.rb @@ -0,0 +1,6 @@ +# Adds load paths to extensions for RSpec. At build, extensions end up in lib/ anyhow. +Dir['ext/*'].each do |dir| + if test ?d, dir + $LOAD_PATH << dir + end +end diff --git a/spec/spec.opts b/spec/spec.opts index 27a0405..a0536b0 100644 --- a/spec/spec.opts +++ b/spec/spec.opts @@ -1,2 +1,3 @@ --color --rrubygems \ No newline at end of file +-rrubygems +-rspec/load_paths \ No newline at end of file
Peeja/rubot
9ea0e9f58ea35ebb96222382ca1b5d5032757ae2
Make spec require rubygems.
diff --git a/spec/spec.opts b/spec/spec.opts index 4e1e0d2..27a0405 100644 --- a/spec/spec.opts +++ b/spec/spec.opts @@ -1 +1,2 @@ --color +-rrubygems \ No newline at end of file
Peeja/rubot
b97edb935726a534de01190c3e2e80b111e66956
Stubbing bin/rubot with main.
diff --git a/bin/rubot b/bin/rubot index f3a3cf6..ae09f71 100644 --- a/bin/rubot +++ b/bin/rubot @@ -1,8 +1,10 @@ #!/usr/bin/env ruby -require File.expand_path( - File.join(File.dirname(__FILE__), '..', 'lib', 'rubot')) +require 'rubygems' +require 'main' -# Put your code here - -# EOF +Main do + argument 'definition' do + required + end +end
Peeja/rubot
91899824b2d6f3ef27e01128201efb7dcdda7611
Improved Adapter build system; documentation changes
diff --git a/.gitignore b/.gitignore index 936b674..dc3650f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ ._* .DS_Store doc +coverage +pkg diff --git a/Adaptors.txt b/Adaptors.txt new file mode 100644 index 0000000..7f8b9a1 --- /dev/null +++ b/Adaptors.txt @@ -0,0 +1,3 @@ +== Writing a Rubot Adapter + +FIXME (stub) \ No newline at end of file diff --git a/Manifest.txt b/Manifest.txt index 651b345..64f0af7 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,29 +1,35 @@ +.autotest History.txt Manifest.txt +Notes.txt README.txt Rakefile bin/rubot -ext/aria/aria.cpp -ext/aria/extconf.rb +examples/test1.rb +ext/rubot_aria/extconf.rb +ext/rubot_aria/rubot_aria.cpp +ext/rubot_asimov/extconf.rb +ext/rubot_asimov/rubot_asimov.c lib/rubot.rb +lib/rubot/adapters/aria.rb +lib/rubot/adapters/asimov.rb lib/rubot/meta.rb lib/rubot/robot.rb -spec/ext/aria/aria/robot_spec.rb -spec/ext/aria/aria_spec.rb -spec/ext/aria/spec_helper.rb -spec/rubot/spec_helper.rb +spec/ext/rubot_aria/aria/robot_spec.rb +spec/ext/rubot_aria/aria_spec.rb +spec/ext/rubot_aria/spec_helper.rb +spec/rubot/robot_spec.rb spec/rubot_spec.rb spec/spec.opts spec/spec_helper.rb tasks/ann.rake tasks/annotations.rake tasks/doc.rake tasks/gem.rake tasks/manifest.rake tasks/post_load.rake tasks/rubyforge.rake tasks/setup.rb tasks/spec.rake tasks/svn.rake tasks/test.rake -test/test_rubot.rb diff --git a/Notes.txt b/Notes.txt index 053dcef..284e162 100644 --- a/Notes.txt +++ b/Notes.txt @@ -1,21 +1,23 @@ ---- Notes This file should not be included in distributions. ---- This code: robot :fred do adapter :aria end creates a new robot named 'fred' using the Aria adapter. This means that fred will be a Rubot::Adapters::Aria::Robot, a subclass of Rubot::Robot. Rubot API: Rubot.add_robot(name, adapter, options={}) Creates a new robot with given name using given adapter. Rubot.robots Returns the robots currently in service. + + diff --git a/Rakefile b/Rakefile index 11f7c12..5af381e 100644 --- a/Rakefile +++ b/Rakefile @@ -1,24 +1,26 @@ # Look in the tasks/setup.rb file for the various options that can be # configured in this Rakefile. The .rake files in the tasks directory # are where the options are used. load 'tasks/setup.rb' ensure_in_path 'lib' require 'rubot' task :default => 'spec:run' PROJ.name = 'rubot' PROJ.authors = 'Peter Jaros (Peeja)' PROJ.email = 'peter.a.jaros@gmail.com' PROJ.url = 'FIXME (project homepage)' PROJ.rubyforge_name = 'rubot' PROJ.spec_opts << '--color' # Don't expect test coverage of any file with an absolute path. PROJ.rcov_opts << '--exclude' << '^/' << '--exclude' << 'meta.rb$' PROJ.rcov_threshold_exact = true +PROJ.exclude << '^.git/' << '.gitignore$' << '.DS_Store$' + # EOF diff --git a/examples/test1.rb b/examples/test1.rb new file mode 100644 index 0000000..2edf8a5 --- /dev/null +++ b/examples/test1.rb @@ -0,0 +1 @@ +require 'rubot' \ No newline at end of file diff --git a/ext/aria/extconf.rb b/ext/rubot_aria/extconf.rb similarity index 85% rename from ext/aria/extconf.rb rename to ext/rubot_aria/extconf.rb index 2956e1c..a5d8945 100644 --- a/ext/aria/extconf.rb +++ b/ext/rubot_aria/extconf.rb @@ -1,10 +1,10 @@ require 'rubygems' require 'mkmf-rice' require 'facets/module/alias' dir_config("Aria", "/usr/local/Aria/include", "/usr/local/Aria/lib") unless have_library('Aria') exit end -create_makefile('aria') +create_makefile('rubot_aria') diff --git a/ext/aria/aria.cpp b/ext/rubot_aria/rubot_aria.cpp similarity index 96% rename from ext/aria/aria.cpp rename to ext/rubot_aria/rubot_aria.cpp index 0f65cf4..6f38d05 100644 --- a/ext/aria/aria.cpp +++ b/ext/rubot_aria/rubot_aria.cpp @@ -1,23 +1,23 @@ #include "rice/Module.hpp" #include "rice/Data_Type.hpp" #include "rice/Constructor.hpp" #include "Aria.h" using namespace Rice; const char *convertBool(Object /* self */, int val) { return ArUtil::convertBool(val); } extern "C" -void Init_aria() +void Init_rubot_aria() { Module rb_MAria = define_module("Aria") // .define_module_function("init", init) .define_module_function("convertBool", convertBool); Data_Type<ArRobot> rb_cRobot = rb_MAria.define_class<ArRobot>("Robot") .define_constructor(Constructor<ArRobot>()) .define_method("addRangeDevice",&ArRobot::addRangeDevice); } diff --git a/ext/rubot_asimov/extconf.rb b/ext/rubot_asimov/extconf.rb new file mode 100644 index 0000000..5ec9407 --- /dev/null +++ b/ext/rubot_asimov/extconf.rb @@ -0,0 +1,11 @@ +require 'mkmf' + +# puts "$configure_args:" +# p $configure_args +# puts "ARGV:" +# p ARGV +# puts "PWD: #{ENV['PWD']}" +# +# exit 1 + +create_makefile('rubot_asimov') \ No newline at end of file diff --git a/ext/rubot_asimov/rubot_asimov.c b/ext/rubot_asimov/rubot_asimov.c new file mode 100644 index 0000000..e3c0b25 --- /dev/null +++ b/ext/rubot_asimov/rubot_asimov.c @@ -0,0 +1,13 @@ +#include "ruby.h" + +void Init_rubot_asimov() +{ + // Define Rubot::Adapters::Asimov + VALUE rb_MRubot = rb_const_get(rb_cObject, rb_intern("Rubot")); + VALUE rb_MAdapters = rb_const_get(rb_MRubot,rb_intern("Adapters")); + VALUE rb_MAsimov = rb_define_module_under(rb_MAdapters, "Asimov"); + + // Define Rubot::Adapters::Asimov::Robot + VALUE rb_cRobot = rb_const_get(rb_MRubot, rb_intern("Robot")); + VALUE rb_cAsimovRobot = rb_define_class_under(rb_MAsimov, "Robot", rb_cRobot); +} diff --git a/lib/rubot.rb b/lib/rubot.rb index c19e99a..2978998 100644 --- a/lib/rubot.rb +++ b/lib/rubot.rb @@ -1,27 +1,42 @@ -Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')].sort.each {|rb| require rb} -require 'facets/string/case.rb' +# Require everything except things under rubot/adapters/ (which load lazily). +(Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')] - + Dir[File.join(::File.dirname(__FILE__), 'rubot', 'adapters', '**')]).sort.each {|rb| require rb} +require 'facets/string/case' module Rubot # This module contains the robotics adapters. For instance, the ACME - # Robotics adapter would be +Rubot::Adapters::AcmeRobotics+. Its robot - # class would be +Rubot::Adapters::AcmeRobotics::Robot+, and it can be + # Robotics adapter would be <tt>Rubot::Adapters::AcmeRobotics</tt>. Its robot + # class would be <tt>Rubot::Adapters::AcmeRobotics::Robot</tt>, and one can be + # created with + # + # Rubot.add_robot(:fred, :acme_robotics) + # + # or, in Rubot syntax, + # + # robot :fred do + # adapter :acme_robotics + # end module Adapters; end # Raised when attempting to create a robot with an unrecognized adapter. class AdapterMissingError < Exception; end + # Returns a hash of the robots Rubot knows about. + # my_favorite_bot = Rubot.robots[:fred] def self.robots @@robots ||= {} end - def self.add_robot(name, adapter, options={}) + # Creates a new robot named +name+ using the adapter +adapter+ and adds it + # to Rubot. + def self.add_robot(name, adapter) mod_name = adapter.to_s.camelcase(true).to_sym unless Adapters.const_defined?(mod_name) raise AdapterMissingError, "Adapter #{mod_name} not found." end - robots[name] = Adapters.const_get(mod_name).const_get(:Robot).new + robots[name] = Adapters.const_get(mod_name).const_get(:Robot).new name end end diff --git a/lib/rubot/adapters/aria.rb b/lib/rubot/adapters/aria.rb new file mode 100644 index 0000000..b37aead --- /dev/null +++ b/lib/rubot/adapters/aria.rb @@ -0,0 +1,2 @@ +require 'rubot' +require 'rubot_aria' diff --git a/lib/rubot/adapters/asimov.rb b/lib/rubot/adapters/asimov.rb new file mode 100644 index 0000000..6de4c78 --- /dev/null +++ b/lib/rubot/adapters/asimov.rb @@ -0,0 +1,2 @@ +require 'rubot' +require 'rubot_asimov' diff --git a/lib/rubot/robot.rb b/lib/rubot/robot.rb index 5156399..090d457 100644 --- a/lib/rubot/robot.rb +++ b/lib/rubot/robot.rb @@ -1,3 +1,7 @@ class Rubot::Robot + attr_reader :name + def initialize(name) + @name = name.to_s + end end diff --git a/spec/ext/aria/aria/robot_spec.rb b/spec/ext/rubot_aria/aria/robot_spec.rb similarity index 100% rename from spec/ext/aria/aria/robot_spec.rb rename to spec/ext/rubot_aria/aria/robot_spec.rb diff --git a/spec/ext/aria/aria_spec.rb b/spec/ext/rubot_aria/aria_spec.rb similarity index 100% rename from spec/ext/aria/aria_spec.rb rename to spec/ext/rubot_aria/aria_spec.rb diff --git a/spec/ext/aria/spec_helper.rb b/spec/ext/rubot_aria/spec_helper.rb similarity index 100% rename from spec/ext/aria/spec_helper.rb rename to spec/ext/rubot_aria/spec_helper.rb diff --git a/spec/rubot/robot_spec.rb b/spec/rubot/robot_spec.rb new file mode 100644 index 0000000..253bbae --- /dev/null +++ b/spec/rubot/robot_spec.rb @@ -0,0 +1,17 @@ +require File.dirname(__FILE__) + '/../spec_helper' + +describe Rubot::Robot do + before(:each) do + @robot = Rubot::Robot.new :harry + end + + it "should have a name" do + @robot.name.should == "harry" + end + + it "should have behaviors" do + pending + @robot.should respond_to(:behaviors) + @robot.behaviors.should respond_to(:[]) + end +end diff --git a/spec/rubot/spec_helper.rb b/spec/rubot/spec_helper.rb deleted file mode 100644 index 8a3e9c9..0000000 --- a/spec/rubot/spec_helper.rb +++ /dev/null @@ -1 +0,0 @@ -require File.join(File.dirname(__FILE__), %w[.. spec_helper]) diff --git a/spec/rubot_spec.rb b/spec/rubot_spec.rb index 8d5c4a1..f4ad9ef 100644 --- a/spec/rubot_spec.rb +++ b/spec/rubot_spec.rb @@ -1,22 +1,22 @@ require File.join(File.dirname(__FILE__), %w[spec_helper]) module Rubot::Adapters::AcmeRobotics class Robot < Rubot::Robot; end end describe Rubot do it "should have robots" do Rubot.should respond_to(:robots) Rubot.robots.should respond_to(:[]) end - it "should let the user add a robot" do + it "should create robots" do Rubot.should respond_to(:add_robot) Rubot.add_robot(:fred, :acme_robotics) Rubot.robots[:fred].should be_a_kind_of(Rubot::Adapters::AcmeRobotics::Robot) end - it "should not let the user add a robot from an unknown adapter" do + it "should not add a robot from an unknown adapter" do lambda { Rubot.add_robot(:roger, :johnson_bots) }.should raise_error(Rubot::AdapterMissingError) end end
Peeja/rubot
3e767397fb9ed876d0aa4c41822008bc58363b1a
Reorg; starting documentation; further developing API.
diff --git a/.gitignore b/.gitignore index eb00a60..936b674 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ ._* .DS_Store +doc diff --git a/Manifest.txt b/Manifest.txt index ce91f49..651b345 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,20 +1,29 @@ History.txt Manifest.txt README.txt Rakefile bin/rubot +ext/aria/aria.cpp +ext/aria/extconf.rb lib/rubot.rb +lib/rubot/meta.rb +lib/rubot/robot.rb +spec/ext/aria/aria/robot_spec.rb +spec/ext/aria/aria_spec.rb +spec/ext/aria/spec_helper.rb +spec/rubot/spec_helper.rb spec/rubot_spec.rb +spec/spec.opts spec/spec_helper.rb tasks/ann.rake tasks/annotations.rake tasks/doc.rake tasks/gem.rake tasks/manifest.rake tasks/post_load.rake tasks/rubyforge.rake tasks/setup.rb tasks/spec.rake tasks/svn.rake tasks/test.rake test/test_rubot.rb diff --git a/Notes.txt b/Notes.txt index 06152ab..053dcef 100644 --- a/Notes.txt +++ b/Notes.txt @@ -1,7 +1,21 @@ +---- +Notes + This file should not be included in distributions. +---- + This code: robot :fred do adapter :aria end -creates a new robot named 'fred' using the Aria adapter. This means that fred will be a Rubot::Adapters::Aria::Robot, a subclass of Rubot::Robot. \ No newline at end of file +creates a new robot named 'fred' using the Aria adapter. This means that fred will be a Rubot::Adapters::Aria::Robot, a subclass of Rubot::Robot. + + +Rubot API: + + Rubot.add_robot(name, adapter, options={}) + Creates a new robot with given name using given adapter. + + Rubot.robots + Returns the robots currently in service. diff --git a/Rakefile b/Rakefile index 4a939c7..11f7c12 100644 --- a/Rakefile +++ b/Rakefile @@ -1,20 +1,24 @@ # Look in the tasks/setup.rb file for the various options that can be # configured in this Rakefile. The .rake files in the tasks directory # are where the options are used. load 'tasks/setup.rb' ensure_in_path 'lib' require 'rubot' task :default => 'spec:run' PROJ.name = 'rubot' PROJ.authors = 'Peter Jaros (Peeja)' PROJ.email = 'peter.a.jaros@gmail.com' PROJ.url = 'FIXME (project homepage)' PROJ.rubyforge_name = 'rubot' PROJ.spec_opts << '--color' +# Don't expect test coverage of any file with an absolute path. +PROJ.rcov_opts << '--exclude' << '^/' << '--exclude' << 'meta.rb$' +PROJ.rcov_threshold_exact = true + # EOF diff --git a/lib/rubot.rb b/lib/rubot.rb index 356407f..c19e99a 100644 --- a/lib/rubot.rb +++ b/lib/rubot.rb @@ -1,56 +1,27 @@ -# $Id$ - -# Equivalent to a header guard in C/C++ -# Used to prevent the class/module from being loaded more than once -unless defined? Rubot +Dir[File.join(::File.dirname(__FILE__), '**', '*.rb')].sort.each {|rb| require rb} +require 'facets/string/case.rb' module Rubot - - # :stopdoc: - VERSION = '1.0.0' - LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR - PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR - # :startdoc: - - # Returns the version string for the library. - # - def self.version - VERSION + + # This module contains the robotics adapters. For instance, the ACME + # Robotics adapter would be +Rubot::Adapters::AcmeRobotics+. Its robot + # class would be +Rubot::Adapters::AcmeRobotics::Robot+, and it can be + module Adapters; end + + # Raised when attempting to create a robot with an unrecognized adapter. + class AdapterMissingError < Exception; end + + def self.robots + @@robots ||= {} end - - # Returns the library path for the module. If any arguments are given, - # they will be joined to the end of the libray path using - # <tt>File.join</tt>. - # - def self.libpath( *args ) - args.empty? ? LIBPATH : ::File.join(LIBPATH, *args) + + def self.add_robot(name, adapter, options={}) + mod_name = adapter.to_s.camelcase(true).to_sym + + unless Adapters.const_defined?(mod_name) + raise AdapterMissingError, "Adapter #{mod_name} not found." + end + + robots[name] = Adapters.const_get(mod_name).const_get(:Robot).new end - - # Returns the lpath for the module. If any arguments are given, - # they will be joined to the end of the path using - # <tt>File.join</tt>. - # - def self.path( *args ) - args.empty? ? PATH : ::File.join(PATH, *args) - end - - # Utility method used to rquire all files ending in .rb that lie in the - # directory below this file that has the same name as the filename passed - # in. Optionally, a specific _directory_ name can be passed in such that - # the _filename_ does not have to be equivalent to the directory. - # - def self.require_all_libs_relative_to( fname, dir = nil ) - dir ||= ::File.basename(fname, '.*') - search_me = ::File.expand_path( - ::File.join(::File.dirname(fname), dir, '**', '*.rb')) - - Dir.glob(search_me).sort.each {|rb| require rb} - end - -end # module Rubot - -Rubot.require_all_libs_relative_to __FILE__ - -end # unless defined? - -# EOF +end diff --git a/lib/rubot/meta.rb b/lib/rubot/meta.rb new file mode 100644 index 0000000..be6125b --- /dev/null +++ b/lib/rubot/meta.rb @@ -0,0 +1,13 @@ +module Rubot + # :stopdoc: + VERSION = '1.0.0' + LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR + PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR + # :startdoc: + + # Returns the version string for the library. + # + def self.version + VERSION + end +end diff --git a/lib/rubot/robot.rb b/lib/rubot/robot.rb new file mode 100644 index 0000000..5156399 --- /dev/null +++ b/lib/rubot/robot.rb @@ -0,0 +1,3 @@ +class Rubot::Robot + +end diff --git a/lib/rubot/rubot.rb b/lib/rubot/rubot.rb deleted file mode 100644 index d5c1706..0000000 --- a/lib/rubot/rubot.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Rubot - def self.robots - @@robots ||= {} - end - - def self.add_robot(name) - robots[name] = true - end -end \ No newline at end of file diff --git a/spec/rubot_spec.rb b/spec/rubot_spec.rb index 81b68ab..8d5c4a1 100644 --- a/spec/rubot_spec.rb +++ b/spec/rubot_spec.rb @@ -1,13 +1,22 @@ require File.join(File.dirname(__FILE__), %w[spec_helper]) +module Rubot::Adapters::AcmeRobotics + class Robot < Rubot::Robot; end +end + describe Rubot do it "should have robots" do Rubot.should respond_to(:robots) Rubot.robots.should respond_to(:[]) end it "should let the user add a robot" do Rubot.should respond_to(:add_robot) - lambda { Rubot.add_robot(:fred) }.should change { Rubot.robots.length }.by(1) + Rubot.add_robot(:fred, :acme_robotics) + Rubot.robots[:fred].should be_a_kind_of(Rubot::Adapters::AcmeRobotics::Robot) + end + + it "should not let the user add a robot from an unknown adapter" do + lambda { Rubot.add_robot(:roger, :johnson_bots) }.should raise_error(Rubot::AdapterMissingError) end end diff --git a/spec/spec.opts b/spec/spec.opts new file mode 100644 index 0000000..4e1e0d2 --- /dev/null +++ b/spec/spec.opts @@ -0,0 +1 @@ +--color diff --git a/test/test_rubot.rb b/test/test_rubot.rb deleted file mode 100644 index e69de29..0000000
Peeja/rubot
35932d8706866649ac2d47a6808275e84bfd0206
Beginning to build Robot architecture.
diff --git a/Notes.txt b/Notes.txt new file mode 100644 index 0000000..06152ab --- /dev/null +++ b/Notes.txt @@ -0,0 +1,7 @@ +This code: + + robot :fred do + adapter :aria + end + +creates a new robot named 'fred' using the Aria adapter. This means that fred will be a Rubot::Adapters::Aria::Robot, a subclass of Rubot::Robot. \ No newline at end of file diff --git a/lib/rubot/rubot.rb b/lib/rubot/rubot.rb new file mode 100644 index 0000000..d5c1706 --- /dev/null +++ b/lib/rubot/rubot.rb @@ -0,0 +1,9 @@ +module Rubot + def self.robots + @@robots ||= {} + end + + def self.add_robot(name) + robots[name] = true + end +end \ No newline at end of file diff --git a/spec/ext/aria/aria/robot_spec.rb b/spec/ext/aria/aria/robot_spec.rb index 7ac4421..4d79e1a 100644 --- a/spec/ext/aria/aria/robot_spec.rb +++ b/spec/ext/aria/aria/robot_spec.rb @@ -1,12 +1,16 @@ require File.join(File.dirname(__FILE__), %w[.. spec_helper]) +unless $spec_skip + describe Aria::Robot do it "should be createable" do lambda { Aria::Robot.new }.should_not raise_error(TypeError) end it "should let us add a range device" do r = Aria::Robot.new lambda { r.addRangeDevice }.should_not raise_error(NoMethodError) end +end + end \ No newline at end of file diff --git a/spec/ext/aria/aria_spec.rb b/spec/ext/aria/aria_spec.rb index 0cc6cff..a9f31d5 100644 --- a/spec/ext/aria/aria_spec.rb +++ b/spec/ext/aria/aria_spec.rb @@ -1,17 +1,21 @@ # $Id$ require File.join(File.dirname(__FILE__), %w[spec_helper]) +unless $spec_skip + describe Aria do it "should provide Aria::Init()" do pending lambda { Aria::init }.should_not raise_error(NoMethodError) end it "should convert ints to bools" do Aria::convertBool(0).should == "false" Aria::convertBool(1).should == "true" end end +end + # EOF diff --git a/spec/ext/aria/spec_helper.rb b/spec/ext/aria/spec_helper.rb index 567b0ed..c0346ea 100644 --- a/spec/ext/aria/spec_helper.rb +++ b/spec/ext/aria/spec_helper.rb @@ -1,9 +1,16 @@ require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) -# If we get a LoadError, let the compiler catch up and try again. +# TODO: Refactor and grep the error string to find the real problem. begin - require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) + # If we get a LoadError, let the compiler catch up and try again. + begin + require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) + rescue LoadError => e + sleep 0.5 + require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) + end + $spec_skip = false rescue LoadError => e - sleep 0.5 - require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) + puts "Extension 'aria' not built. Skipping..." + $spec_skip = true end diff --git a/spec/rubot/spec_helper.rb b/spec/rubot/spec_helper.rb new file mode 100644 index 0000000..8a3e9c9 --- /dev/null +++ b/spec/rubot/spec_helper.rb @@ -0,0 +1 @@ +require File.join(File.dirname(__FILE__), %w[.. spec_helper]) diff --git a/spec/rubot_spec.rb b/spec/rubot_spec.rb index 342a698..81b68ab 100644 --- a/spec/rubot_spec.rb +++ b/spec/rubot_spec.rb @@ -1,8 +1,13 @@ -# $Id$ - require File.join(File.dirname(__FILE__), %w[spec_helper]) describe Rubot do + it "should have robots" do + Rubot.should respond_to(:robots) + Rubot.robots.should respond_to(:[]) + end + + it "should let the user add a robot" do + Rubot.should respond_to(:add_robot) + lambda { Rubot.add_robot(:fred) }.should change { Rubot.robots.length }.by(1) + end end - -# EOF
Peeja/rubot
cf86abc44c3f7f1161aff0b7d67b67c5e45c97b6
Cleaned up extconf.rb.
diff --git a/ext/aria/extconf.rb b/ext/aria/extconf.rb index d7fe7d4..2956e1c 100644 --- a/ext/aria/extconf.rb +++ b/ext/aria/extconf.rb @@ -1,109 +1,10 @@ require 'rubygems' require 'mkmf-rice' require 'facets/module/alias' -# module Logging -# class << self -# def open_with_feature -# @log ||= File::open(@logfile, 'w') -# @log.sync = true -# $stderr.reopen(@log) -# $stdout.reopen(@log) -# puts "Foo" -# yield -# ensure -# $stderr.reopen(@orgerr) -# $stdout.reopen(@orgout) -# end -# alias_method_chain :open, :feature -# -# def postpone_with_feature -# tmplog = "mkmftmp#{@postpone += 1}.log" -# open do -# log, *save = @log, @logfile, @orgout, @orgerr -# @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log -# begin -# log.print(open {yield}) -# @log.close -# File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} -# ensure -# @log, @logfile, @orgout, @orgerr = log, *save -# @postpone -= 1 -# rm_f tmplog -# end -# end -# end -# alias_method_chain :postpone, :feature -# end -# end -# -# class << self -# # def link_command_with_puts(*args) -# # puts "Foo" -# # cmd = link_command_without_puts(*args) -# # puts cmd -# # cmd -# # end -# # alias_method_chain :link_command, :puts -# -# # def append_library_with_feature(*args) -# # puts "Foo" -# # # append_library_without_feature(*args) -# # end -# # alias_method_chain :append_library, :feature -# -# def message_with_feature(*s) -# # p s -# unless $extmk and not $VERBOSE -# printf(*s) -# $stdout.flush -# end -# end -# alias_method_chain :message, :feature -# -# def checking_for_with_feature(m, fmt = nil) -# f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim -# m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... " -# message "%s", m -# a = r = nil -# Logging::postpone do -# r = yield -# a = (fmt ? fmt % r : r ? "yes" : "no") << "\n" -# "#{f}#{m}-------------------- #{a}\n" -# end -# # puts a -# message(a) -# Logging::message "--------------------\n\n" -# r -# end -# alias_method_chain :checking_for, :feature -# -# -# def have_library_with_foo(lib, func = nil, headers = nil, &b) -# func = "main" if !func or func.empty? -# lib = with_config(lib+'lib', lib) -# checking_for checking_message("#{func}()", LIBARG%lib) do -# puts "Foo" -# if COMMON_LIBS.include?(lib) -# true -# else -# libs = append_library($libs, lib) -# if try_func(func, libs, headers, &b) -# $libs = libs -# true -# else -# false -# end -# end -# end -# end -# alias_method_chain :have_library, :foo -# end - dir_config("Aria", "/usr/local/Aria/include", "/usr/local/Aria/lib") -# unless have_library('Aria', 'Aria::Init') unless have_library('Aria') exit end create_makefile('aria')
Peeja/rubot
86bf3b87ad557535127bdea26cddf202f26f6c8c
Weekly Goal: Aria loaded into Ruby.
diff --git a/.autotest b/.autotest new file mode 100644 index 0000000..3bc541c --- /dev/null +++ b/.autotest @@ -0,0 +1,17 @@ +Autotest.add_hook :initialize do |at| + # Set up mapping for extensions. + # When foo.so is changed, rerun all specs under spec/ext/foo/. + at.add_mapping(/\/([^\/]*).so$/) do |f, m| + ext = m[1] + r = Regexp.new("ext/#{ext}/.*_spec\.rb$") + at.files_matching r + end + + # Set up mapping for spec helpers. + # When foo/spec_helper.rb is changed, rerun all specs under foo/. + # Doesn't do anything; not sure why. + # at.add_mapping(/^(.*)\/spec_helper.rb$/) do |f, m| + # dir = m[1] + # Dir["#{dir}/**/*.rb"] + # end +end diff --git a/.gitignore b/.gitignore index 72f1563..eb00a60 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -._* \ No newline at end of file +._* +.DS_Store diff --git a/ext/.gitignore b/ext/.gitignore new file mode 100644 index 0000000..60397d9 --- /dev/null +++ b/ext/.gitignore @@ -0,0 +1,4 @@ +*/Makefile +*/mkmf.log +*/*.o +*/*.so diff --git a/ext/aria/aria.cpp b/ext/aria/aria.cpp new file mode 100644 index 0000000..0f65cf4 --- /dev/null +++ b/ext/aria/aria.cpp @@ -0,0 +1,23 @@ +#include "rice/Module.hpp" +#include "rice/Data_Type.hpp" +#include "rice/Constructor.hpp" +#include "Aria.h" + +using namespace Rice; + +const char *convertBool(Object /* self */, int val) { + return ArUtil::convertBool(val); +} + +extern "C" +void Init_aria() +{ + Module rb_MAria = + define_module("Aria") + // .define_module_function("init", init) + .define_module_function("convertBool", convertBool); + + Data_Type<ArRobot> rb_cRobot = rb_MAria.define_class<ArRobot>("Robot") + .define_constructor(Constructor<ArRobot>()) + .define_method("addRangeDevice",&ArRobot::addRangeDevice); +} diff --git a/ext/aria/extconf.rb b/ext/aria/extconf.rb index 2d844cb..d7fe7d4 100644 --- a/ext/aria/extconf.rb +++ b/ext/aria/extconf.rb @@ -1,2 +1,109 @@ +require 'rubygems' require 'mkmf-rice' +require 'facets/module/alias' + +# module Logging +# class << self +# def open_with_feature +# @log ||= File::open(@logfile, 'w') +# @log.sync = true +# $stderr.reopen(@log) +# $stdout.reopen(@log) +# puts "Foo" +# yield +# ensure +# $stderr.reopen(@orgerr) +# $stdout.reopen(@orgout) +# end +# alias_method_chain :open, :feature +# +# def postpone_with_feature +# tmplog = "mkmftmp#{@postpone += 1}.log" +# open do +# log, *save = @log, @logfile, @orgout, @orgerr +# @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log +# begin +# log.print(open {yield}) +# @log.close +# File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} +# ensure +# @log, @logfile, @orgout, @orgerr = log, *save +# @postpone -= 1 +# rm_f tmplog +# end +# end +# end +# alias_method_chain :postpone, :feature +# end +# end +# +# class << self +# # def link_command_with_puts(*args) +# # puts "Foo" +# # cmd = link_command_without_puts(*args) +# # puts cmd +# # cmd +# # end +# # alias_method_chain :link_command, :puts +# +# # def append_library_with_feature(*args) +# # puts "Foo" +# # # append_library_without_feature(*args) +# # end +# # alias_method_chain :append_library, :feature +# +# def message_with_feature(*s) +# # p s +# unless $extmk and not $VERBOSE +# printf(*s) +# $stdout.flush +# end +# end +# alias_method_chain :message, :feature +# +# def checking_for_with_feature(m, fmt = nil) +# f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim +# m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... " +# message "%s", m +# a = r = nil +# Logging::postpone do +# r = yield +# a = (fmt ? fmt % r : r ? "yes" : "no") << "\n" +# "#{f}#{m}-------------------- #{a}\n" +# end +# # puts a +# message(a) +# Logging::message "--------------------\n\n" +# r +# end +# alias_method_chain :checking_for, :feature +# +# +# def have_library_with_foo(lib, func = nil, headers = nil, &b) +# func = "main" if !func or func.empty? +# lib = with_config(lib+'lib', lib) +# checking_for checking_message("#{func}()", LIBARG%lib) do +# puts "Foo" +# if COMMON_LIBS.include?(lib) +# true +# else +# libs = append_library($libs, lib) +# if try_func(func, libs, headers, &b) +# $libs = libs +# true +# else +# false +# end +# end +# end +# end +# alias_method_chain :have_library, :foo +# end + +dir_config("Aria", "/usr/local/Aria/include", "/usr/local/Aria/lib") +# unless have_library('Aria', 'Aria::Init') +unless have_library('Aria') + exit +end + create_makefile('aria') diff --git a/spec/ext/aria/aria/robot_spec.rb b/spec/ext/aria/aria/robot_spec.rb new file mode 100644 index 0000000..7ac4421 --- /dev/null +++ b/spec/ext/aria/aria/robot_spec.rb @@ -0,0 +1,12 @@ +require File.join(File.dirname(__FILE__), %w[.. spec_helper]) + +describe Aria::Robot do + it "should be createable" do + lambda { Aria::Robot.new }.should_not raise_error(TypeError) + end + + it "should let us add a range device" do + r = Aria::Robot.new + lambda { r.addRangeDevice }.should_not raise_error(NoMethodError) + end +end \ No newline at end of file diff --git a/spec/ext/aria/aria_spec.rb b/spec/ext/aria/aria_spec.rb new file mode 100644 index 0000000..0cc6cff --- /dev/null +++ b/spec/ext/aria/aria_spec.rb @@ -0,0 +1,17 @@ +# $Id$ + +require File.join(File.dirname(__FILE__), %w[spec_helper]) + +describe Aria do + it "should provide Aria::Init()" do + pending + lambda { Aria::init }.should_not raise_error(NoMethodError) + end + + it "should convert ints to bools" do + Aria::convertBool(0).should == "false" + Aria::convertBool(1).should == "true" + end +end + +# EOF diff --git a/spec/ext/aria/spec_helper.rb b/spec/ext/aria/spec_helper.rb new file mode 100644 index 0000000..567b0ed --- /dev/null +++ b/spec/ext/aria/spec_helper.rb @@ -0,0 +1,9 @@ +require File.join(File.dirname(__FILE__), %w[.. .. spec_helper]) + +# If we get a LoadError, let the compiler catch up and try again. +begin + require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) +rescue LoadError => e + sleep 0.5 + require File.join(File.dirname(__FILE__), %w[.. .. .. ext aria aria]) +end
tinyjs/jquery-table-highlighter
2bd44092d35316f94e51e72c31381872275737bc
inital commit
diff --git a/application.js b/application.js new file mode 100755 index 0000000..d9c8a28 --- /dev/null +++ b/application.js @@ -0,0 +1,3 @@ +$(document).ready(function() { + $('#page').tablehighlight(); +}); \ No newline at end of file diff --git a/index.html b/index.html new file mode 100755 index 0000000..7daa820 --- /dev/null +++ b/index.html @@ -0,0 +1,79 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <meta name="author" content="charlesmarshall" /> + + <link rel="icon" type="image/gif" href="/favicon.ico" /> + <link rel="stylesheet" href="http://tinyjs.com/files/projects/jquery-table-highlighter/table-styles.css" type="text/css" media="screen" charset="utf-8" /> + <script src="http://tinyjs.com/files/projects/jquery-table-highlighter/jquery.js" type="text/javascript" charset="utf-8"></script><script src="http://tinyjs.com/files/projects/jquery-table-highlighter/jquery.tablehightlight.js" type="text/javascript" charset="utf-8"></script><script src="http://tinyjs.com/files/projects/jquery-table-highlighter/application.js" type="text/javascript" charset="utf-8"></script> + + <title>Measurements are in mm unless stated otherwise</title> + +</head> + +<body> + <body> + <div id="page" class="clearfix"> + <h3>Measurements are in mm unless stated otherwise</h3> + <table class="simple_table"> + <tr class="row1"> + <th>Bore</th> + <td>77.7</td> + </tr> + <tr class="row2"> + <th>Stroke</th> + <td>79</td> + </tr> + <tr class="row1"> + <th>Compression</th> + <td>10.1 &#177; 0.2</td> + </tr> + </table> + + + <h3>Fuel Consumption is measured in mpg (litres per 100 km)</h3> + <table class="complex_table"> + <tr class="heading"> + <th></th> + <th class="manual">Manual</th> + <th class="auto">Automatic</th> + </tr> + + <tr class="row1"> + <th>Urban</th> + <td class="manual">9.6 (29.4)</td> + <td class="auto">9.8 (28.8)</td> + </tr> + <tr class="row2"> + <th>Extra urban</th> + <td class="manual">6.3 (44.8)</td> + <td class="auto">6.2 (45.6)</td> + </tr> + <tr class="row1"> + <th>Combined</th> + <td class="manual">7.5 (37.7)</td> + <td class="auto">7.5 (37.7)</td> + </tr> + </table> + + + </div> +</body> + + <script type="text/javascript"> + var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); + document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); + </script> + <script type="text/javascript"> + try { + var pageTracker = _gat._getTracker("UA-2549287-19"); + pageTracker._trackPageview(); + } catch(err) {} + </script> +</body> +</html> + + diff --git a/jquery-table-highlighter.zip b/jquery-table-highlighter.zip new file mode 100755 index 0000000..020c253 Binary files /dev/null and b/jquery-table-highlighter.zip differ diff --git a/jquery.js b/jquery.js new file mode 100755 index 0000000..3747929 --- /dev/null +++ b/jquery.js @@ -0,0 +1,32 @@ +/* + * jQuery 1.2.3 - New Wave Javascript + * + * Copyright (c) 2008 John Resig (jquery.com) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * $Date: 2008-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $ + * $Rev: 4663 $ + */ +(function(){if(window.jQuery)var _jQuery=window.jQuery;var jQuery=window.jQuery=function(selector,context){return new jQuery.prototype.init(selector,context);};if(window.$)var _$=window.$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var isSimple=/^.[^:#\[\.]*$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}else if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem)if(elem.id!=match[3])return jQuery().find(selector);else{this[0]=elem;this.length=1;return this;}else +selector=[];}}else +return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.3",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;this.each(function(i){if(this==elem)ret=i;});return ret;},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],name)||undefined;else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else +return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else +selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return!selector?this:this.pushStack(jQuery.merge(this.get(),selector.constructor==String?jQuery(selector).get():selector.length!=undefined&&(!selector.nodeName||jQuery.nodeName(selector,"form"))?selector:[selector]));},is:function(selector){return selector?jQuery.multiFilter(selector,this).length>0:false;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else +return(this[0].value||"").replace(/\r/g,"");}return undefined;}return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=value.constructor==Array?value:[value];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else +this.value=value;});},html:function(value){return value==undefined?(this.length?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value==null){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data==undefined&&this.length)data=jQuery.data(this[0],key);return data==null&&parts[1]?this.data(parts[0]):data;}else +return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script")){scripts=scripts.add(elem);}else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.prototype.init.prototype=jQuery.prototype;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else +jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==1){target=this;i=0;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){if(target===options[name])continue;if(deep&&options[name]&&typeof options[name]=="object"&&target[name]&&!options[name].nodeType)target[name]=jQuery.extend(target[name],options[name]);else if(options[name]!=undefined)target[name]=options[name];}return target;};var expando="jQuery"+(new Date()).getTime(),uuid=0,windowData={};var exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i;jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else +script.appendChild(document.createTextNode(data));head.appendChild(script);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!=undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){if(args){if(object.length==undefined){for(var name in object)if(callback.apply(object[name],args)===false)break;}else +for(var i=0,length=object.length;i<length;i++)if(callback.apply(object[i],args)===false)break;}else{if(object.length==undefined){for(var name in object)if(callback.call(object[name],name,object[name])===false)break;}else +for(var i=0,length=object.length,value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else +jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret;function color(elem){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=elem.style.outline;elem.style.outline="0 solid black";elem.style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&elem.style&&elem.style[name])ret=elem.style[name];else if(document.defaultView&&document.defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var getComputedStyle=document.defaultView.getComputedStyle(elem,null);if(getComputedStyle&&!color(elem))ret=getComputedStyle.getPropertyValue(name);else{var swap=[],stack=[];for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(var i=0;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(getComputedStyle&&getComputedStyle.getPropertyValue(name))||"";for(var i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var style=elem.style.left,runtimeStyle=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;elem.style.left=ret||0;ret=elem.style.pixelLeft+"px";elem.style.left=style;elem.runtimeStyle.left=runtimeStyle;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem=elem.toString();if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else +ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,""+value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(typeof array!="array")for(var i=0,length=array.length;i<length;i++)ret.push(array[i]);else +ret=array.slice(0);return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]==elem)return i;return-1;},merge:function(first,second){if(jQuery.browser.msie){for(var i=0;second[i];i++)if(second[i].nodeType!=8)first.push(second[i]);}else +for(var i=0;second[i];i++)first.push(second[i]);return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv&&callback(elems[i],i)||inv&&!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!==null&&value!=undefined){if(value.constructor!=Array)value=[value];ret=ret.concat(value);}}return ret;}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,innerHTML:"innerHTML",className:"className",value:"value",disabled:"disabled",checked:"checked",readonly:"readOnly",selected:"selected",maxlength:"maxLength",selectedIndex:"selectedIndex",defaultValue:"defaultValue",tagName:"tagName",nodeName:"nodeName"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem))r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval!=undefined)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered)return val;val=jQuery.event.handle.apply(arguments.callee.elem,arguments);return val;});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else +for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data||[]);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event)data.unshift(this.fix({type:type,target:elem}));data[0].type=type;if(exclusive)data[0].exclusive=true;if(jQuery.isFunction(jQuery.data(elem,"handle")))val=jQuery.data(elem,"handle").apply(elem,data);if(!fn&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var handlers=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in handlers){var handler=handlers[j];args[0].handler=handler;args[0].data=handler.data;if(!parts[1]&&!event.exclusive||handler.type==parts[1]){var ret=handler.apply(this,args);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie)event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=originalEvent.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0])return jQuery.event.trigger(type,data,this[0],false,fn);return undefined;},toggle:function(){var args=arguments;return this.click(function(event){this.lastToggle=0==this.lastToggle?1:0;event.preventDefault();return args[this.lastToggle].apply(this,arguments)||false;});},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else +jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var jsonp,jsre=/=\?(&|$)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get"){var ts=(new Date()).getTime();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");xml.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else +jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xml;},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else +for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else +s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else +e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(!elem)return undefined;type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].apply(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.apply(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=(new Date()).getTime();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),fixed=jQuery.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&jQuery.css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||jQuery.css(offsetChild,"position")=="absolute"))||(mozilla&&jQuery.css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}return results;};})(); \ No newline at end of file diff --git a/jquery.tablehightlight.js b/jquery.tablehightlight.js new file mode 100755 index 0000000..2a717a6 --- /dev/null +++ b/jquery.tablehightlight.js @@ -0,0 +1,84 @@ +(function($){ + $.fn.tablehighlight = function(options){ + var defaults ={ + simple_table: {tableclass: "simple_table", row1class: "row1", row1classactive: "row1-hover", row2class: "row2", row2classactive: "row2-hover"}, + complex_table: {tableclass: "complex_table", headerrowclass:"heading",highlightclass:"highlight", row1class: "row1", row1classactive: "row1-hover", row2class: "row2", row2classactive: "row2-hover"} + } + var options = $.extend(defaults, options); + + return this.each(function(){ + obj = $(this); + //simple table + obj.find("."+options['simple_table']['tableclass'] +" ."+options['simple_table']['row1class']+ + ", ."+options['simple_table']['tableclass'] +" ."+options['simple_table']['row2class']).hover( + function(){ + if($(this).is("."+options['simple_table']['row1class'])){ + $(this).addClass(options['simple_table']['row1classactive']); + }else{ + $(this).addClass(options['simple_table']['row2classactive']); + } + }, + function(){ + if($(this).is("."+options['simple_table']['row1classactive'])){ + $(this).removeClass(options['simple_table']['row1classactive']); + }else{ + $(this).removeClass(options['simple_table']['row2classactive']); + } + } + ); + //complex table + //row highlight for row1 + obj.find("."+options['complex_table']['tableclass'] +" ."+options['complex_table']['row1class']+" th, "+ + "."+options['complex_table']['tableclass'] +" ."+options['complex_table']['row2class']+" th").hover( + function(){ + if($(this).parent().is("."+options['complex_table']['row1class'])){ + $(this).parent().addClass(options['complex_table']['row1classactive']); + }else{ + $(this).parent().addClass(options['complex_table']['row2classactive']); + } + }, + function(){ + if($(this).parent().is("."+options['complex_table']['row1classactive'])){ + $(this).parent().removeClass(options['complex_table']['row1classactive']); + }else{ + $(this).parent().removeClass(options['complex_table']['row2classactive']); + } + } + ); + //heading highlight column + obj.find("."+options['complex_table']['tableclass'] +" ."+options['complex_table']['headerrowclass']+" th").hover( + function(){ + classname = $(this).attr('class'); + if(classname){ + $(this).parent().parent().find("."+classname).addClass(options['complex_table']['highlightclass']); + } + }, + function(){ + classname = $(this).attr('class'); + if(classname){ + classname = classname.substring(0, classname.indexOf(' ')); + $(this).parent().parent().find("."+classname).removeClass(options['complex_table']['highlightclass']); + } + } + ); + //clever one, hightlight column heading, row title and current column + obj.find("."+options['complex_table']['tableclass'] +" ."+options['complex_table']['row1class']+" td, "+ + "."+options['complex_table']['tableclass'] +" ."+options['complex_table']['row2class']+" td").hover( + function(){ + classname = $(this).attr('class'); + if(classname){ + $(this).parent().parent().find("."+options['complex_table']['headerrowclass']+" ."+classname).addClass(options['complex_table']['highlightclass']); + } + $(this).addClass(options['complex_table']['highlightclass']); + $(this).parent().find("th").addClass(options['complex_table']['highlightclass']); + + }, + function(){ + $("."+options['complex_table']['tableclass']).find("."+options['complex_table']['highlightclass']).removeClass(options['complex_table']['highlightclass']); + } + ); + + }); + } + +})(jQuery); \ No newline at end of file diff --git a/reset-fonts-grids.css b/reset-fonts-grids.css new file mode 100755 index 0000000..d23b767 --- /dev/null +++ b/reset-fonts-grids.css @@ -0,0 +1,8 @@ +/* +Copyright (c) 2007, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 2.4.1 +*/ +html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;font-variant:normal;}sup {vertical-align:text-top;}sub {vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}legend{color:#000;}body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}table {font-size:inherit;font:100%;}pre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;} +body{text-align:center;}#ft{clear:both;}#doc,#doc2,#doc3,#doc4,.yui-t1,.yui-t2,.yui-t3,.yui-t4,.yui-t5,.yui-t6,.yui-t7{margin:auto;text-align:left;width:57.69em;*width:56.301em;min-width:750px;}#doc2{width:73.074em;*width:71.313em;}#doc3{margin:auto 10px;width:auto;}#doc4{width:74.923em;*width:73.117em;}.yui-b{position:relative;}.yui-b{_position:static;}#yui-main .yui-b{position:static;}#yui-main{width:100%;}.yui-t1 #yui-main,.yui-t2 #yui-main,.yui-t3 #yui-main{float:right;margin-left:-25em;}.yui-t4 #yui-main,.yui-t5 #yui-main,.yui-t6 #yui-main{float:left;margin-right:-25em;}.yui-t1 .yui-b{float:left;width:12.3207em;*width:12.0106em;}.yui-t1 #yui-main .yui-b{margin-left:13.3207em;*margin-left:13.0106em;}.yui-t2 .yui-b{float:left;width:13.8456em;*width:13.512em;}.yui-t2 #yui-main .yui-b{margin-left:14.8456em;*margin-left:14.512em;}.yui-t3 .yui-b{float:left;width:23.0759em;*width:22.52em;}.yui-t3 #yui-main .yui-b{margin-left:24.0759em;*margin-left:23.52em;}.yui-t4 .yui-b{float:right;width:13.8456em;*width:13.512em;}.yui-t4 #yui-main .yui-b{margin-right:14.8456em;*margin-right:14.512em;}.yui-t5 .yui-b{float:right;width:18.4608em;*width:18.016em;}.yui-t5 #yui-main .yui-b{margin-right:19.4608em;*margin-right:19.016em;}.yui-t6 .yui-b{float:right;width:23.0759em;*width:22.52em;}.yui-t6 #yui-main .yui-b{margin-right:24.0759em;*margin-right:23.52em;}.yui-t7 #yui-main .yui-b{display:block;margin:0 0 1em 0;}#yui-main .yui-b{float:none;width:auto;}.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gb .yui-u,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{float:left;margin-left:2%;width:32%;}.yui-gb .yui-gb .yui-u,.yui-gb .yui-gc .yui-u{*margin-left:1.8%;_margin-left:4%;}.yui-g .yui-gb .yui-u{_margin-left:.8%;}.yui-gb .yui-u{float:right;}.yui-gb div.first{margin-left:0;float:left;}.yui-g .yui-gb div.first,.yui-gb .yui-gb div.first{*margin-right:0;*width:32%;_width:31.7%;}.yui-gb .yui-gc div.first,.yui-gb .yui-gd div.first{*margin-right:0;}.yui-gb .yui-gd .yui-u{*width:66%;_width:61.2%;}.yui-gb .yui-gd div.first{*width:31%;_width:29.5%;}.yui-g .yui-gc .yui-u,.yui-gb .yui-gc .yui-u{width:32%;_float:right;margin-right:0;_margin-left:0;}.yui-gb .yui-gc div.first{width:66%;*float:left;*margin-left:0;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf .yui-u{margin:0;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf,.yui-gc .yui-u,.yui-gd .yui-g,.yui-g .yui-gc .yui-u,.yui-ge .yui-u,.yui-ge .yui-g,.yui-gf .yui-g,.yui-gf .yui-u{float:right;}.yui-g .yui-gc div.first,.yui-g .yui-ge div.first,.yui-g div.first,.yui-gc div.first,.yui-gc div.first div.first,.yui-gd div.first,.yui-ge div.first,.yui-gf div.first{float:left;}.yui-g .yui-g .yui-u,.yui-gb .yui-g .yui-u,.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u,.yui-ge .yui-g .yui-u,.yui-gf .yui-g .yui-u{width:49%;*width:48.1%;*margin-left:0;}.yui-g .yui-g div.first{*margin:0;}.yui-gb .yui-g div.first{*margin-right:4%;_margin-right:1.3%;}.yui-gb .yui-gb .yui-u{_margin-left:.7%;}.yui-gb .yui-g div.first,.yui-gb .yui-gb div.first{*margin-left:0;}.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u{*width:48.1%;*margin-left:0;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf{width:49.1%;}.yui-g .yui-gb div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first{margin-left:0;}.yui-g .yui-gc div.first,.yui-gc div.first,.yui-gd .yui-g,.yui-gd .yui-u{width:66%;}.yui-gd div.first,.yui-gb .yui-gd div.first{width:32%;}.yui-g .yui-gd div.first{_width:29.9%;}.yui-ge .yui-u,.yui-ge .yui-g,.yui-gf div.first{width:24%;}.yui-gb .yui-ge div.yui-u,.yui-gb .yui-gf div.yui-u{float:right;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf div.first {float:left;}.yui-ge div.first,.yui-gf .yui-g,.yui-gf .yui-u{width:74.2%;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf div.first{*width:24%;_width:20%;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf .yui-u{*width:73.5%;_width:65.5%;}#bd:after,.yui-g:after,.yui-gb:after,.yui-gc:after,.yui-gd:after,.yui-ge:after,.yui-gf:after{content:".";display:block;height:0;clear:both;visibility:hidden;}#bd,.yui-g,.yui-gb,.yui-gc,.yui-gd,.yui-ge,.yui-gf{zoom:1;}.yui-gb .yui-u{float:left;} \ No newline at end of file diff --git a/table-styles.css b/table-styles.css new file mode 100755 index 0000000..c1f6918 --- /dev/null +++ b/table-styles.css @@ -0,0 +1,37 @@ +@import url("http://tinyjs.com/files/projects/measurements-are-in-mm-unless-stated-otherwise/reset-fonts-grids.css"); + +td, th{padding:3px 0;} +table{ + width:99%; + margin:15px auto; +} +/*tables*/ +.row1, .row2{ + margin:2px 0; + border-bottom:3px solid #fff; +} +.row1{background:#f7f7f7;} +.row2{background:#f9f9f9;} + +/*right align column data*/ +.row1 td, .row2 td{text-align:right;} +/*fix width for the titles*/ +.row1 th, .row2 th{width:44%;} +/*bolding*/ +.row1-hover, .row1-hover th, .row1-hover td, .row2-hover, .row2-hover td, tr.row2-hover th, +.highlight, .highlight th, .highlight td{ + font-weight:bold; +} +/*bg highlight*/ +tr.row1-hover, .row1 .highlight, .row1 .highlight *{background:#EBEBEB;} +tr.row2-hover, .row2 .highlight, .row2 .highlight *{background:#F1F1F1;} + +/*th styling*/ +.heading th.highlight{ + background: #fff; +} +/*add border to head column*/ +tr.heading{ border-bottom:1px solid #E1E9EE;} +tr.heading th{text-align:right;} +/*fix the width of a table cell - stops it shifting over */ +.complex_table td{width:27%;}
harperreed/twitteroauth-python
0e466938501240af7f1623c82159045faba3be56
added some info to the readme
diff --git a/README b/README index cba02c6..10deb93 100644 --- a/README +++ b/README @@ -1,48 +1,56 @@ Python Oauth client for Twitter --------- I built this so that i didn't have to keep looking for an oauth client for twitter to use in python. It is based off of the PHP work from abrah.am (http://github.com/poseurtech/twitteroauth/tree/master). It was very helpful. I am using the OAuth lib that is from google gdata. I figure it is a working client and is in production use - so it should be solid. You can find it at: http://gdata-python-client.googlecode.com/svn/trunk/src/gdata/oauth With a bit of modification this client should work with other publishers. btw, i am a python n00b. so feel free to help out. Thanks, harper - harper@nata2.org (email and xmpp) + +----------- +Links: + +Google Code Project: http://code.google.com/p/twitteroauth-python/ +Issue Tracker: http://code.google.com/p/twitteroauth-python/issues/list +Wiki: http://wiki.github.com/harperreed/twitteroauth-python + ----------- The example client is included in the client.py. It is: if __name__ == '__main__': consumer_key = '' consumer_secret = '' while not consumer_key: consumer_key = raw_input('Please enter consumer key: ') while not consumer_secret: consumer_secret = raw_input('Please enter consumer secret: ') auth_client = TwitterOAuthClient(consumer_key,consumer_secret) tok = auth_client.get_request_token() token = tok['oauth_token'] token_secret = tok['oauth_token_secret'] url = auth_client.get_authorize_url(token) webbrowser.open(url) print "Visit this URL to authorize your app: " + url response_token = raw_input('What is the oauth_token from twitter: ') response_client = TwitterOAuthClient(consumer_key, consumer_secret,token, token_secret) tok = response_client.get_access_token() print "Making signed request" #verify user access content = response_client.oauth_request('https://twitter.com/account/verify_credentials.json', method='POST') #make an update #content = response_client.oauth_request('https://twitter.com/statuses/update.xml', {'status':'Updated from a python oauth client. awesome.'}, method='POST') print content print 'Done.'
harperreed/twitteroauth-python
4272b448881ac3e7d4e94812694580083d936c89
changed some comments and what not on client.py. gave props to the right peeps
diff --git a/client.py b/client.py index d2cd029..17acdb4 100644 --- a/client.py +++ b/client.py @@ -1,148 +1,151 @@ ''' -Example consumer. This is not recommended for production. -Instead, you'll want to create your own subclass of OAuthClient -or find one that works with your web framework. +Python Oauth client for Twitter + +Used the SampleClient from the OAUTH.org example python client as basis. + +props to leahculver for making a very hard to use but in the end usable oauth lib. + ''' import httplib import urllib import time import webbrowser import oauth as oauth from urlparse import urlparse class TwitterOAuthClient(oauth.OAuthClient): api_root_url = 'https://twitter.com' #for testing 'http://term.ie' api_root_port = "80" #set api urls def request_token_url(self): return self.api_root_url + '/oauth/request_token' def authorize_url(self): return self.api_root_url + '/oauth/authorize' def access_token_url(self): return self.api_root_url + '/oauth/access_token' #oauth object def __init__(self, consumer_key, consumer_secret, oauth_token=None, oauth_token_secret=None): self.sha1_method = oauth.OAuthSignatureMethod_HMAC_SHA1() self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) if ((oauth_token != None) and (oauth_token_secret!=None)): self.token = oauth.OAuthConsumer(oauth_token, oauth_token_secret) else: self.token = None def oauth_request(self,url, args = {}, method=None): if (method==None): if args=={}: method = "GET" else: method = "POST" req = oauth.OAuthRequest.from_consumer_and_token(self.consumer, self.token, method, url, args) req.sign_request(self.sha1_method, self.consumer,self.token) if (method=="GET"): return self.http_wrapper(req.to_url()) elif (method == "POST"): return self.http_wrapper(req.get_normalized_http_url(),req.to_postdata()) # trying to make a more robust http wrapper. this is a failure ;) def http_wrapper_fucked(self, url, postdata=""): parsed_url = urlparse(url) connection_url = parsed_url.path+"?"+parsed_url.query hostname = parsed_url.hostname scheme = parsed_url.scheme headers = {'Content-Type' :'application/x-www-form-urlencoded'} if scheme=="https": connection = httplib.HTTPSConnection(hostname) else: connection = httplib.HTTPConnection(hostname) connection.request("POST", connection_url, body=postdata, headers=headers) connection_response = connection.getresponse() self.last_http_status = connection_response.status self.last_api_call= url response= connection_response.read() #this is barely working. (i think. mostly it is that everyone else is using httplib) def http_wrapper(self, url, postdata={}): try: if (postdata != {}): f = urllib.urlopen(url, postdata) else: f = urllib.urlopen(url) response = f.read() except: response = "" return response def get_request_token(self): response = self.oauth_request(self.request_token_url()) token = self.oauth_parse_response(response) try: self.token = oauth.OAuthConsumer(token['oauth_token'],token['oauth_token_secret']) return token except: raise oauth.OAuthError('Invalid oauth_token') def oauth_parse_response(self, response_string): r = {} for param in response_string.split("&"): pair = param.split("=") if (len(pair)!=2): break r[pair[0]]=pair[1] return r def get_authorize_url(self, token): return self.authorize_url() + '?oauth_token=' +token def get_access_token(self,token=None): r = self.oauth_request(self.access_token_url()) token = self.oauth_parse_response(r) self.token = oauth.OAuthConsumer(token['oauth_token'],token['oauth_token_secret']) return token def oauth_request(self, url, args={}, method=None): if (method==None): if args=={}: method = "GET" else: method = "POST" req = oauth.OAuthRequest.from_consumer_and_token(self.consumer, self.token, method, url, args) req.sign_request(self.sha1_method, self.consumer,self.token) if (method=="GET"): return self.http_wrapper(req.to_url()) elif (method == "POST"): return self.http_wrapper(req.get_normalized_http_url(),req.to_postdata()) if __name__ == '__main__': consumer_key = '' consumer_secret = '' while not consumer_key: consumer_key = raw_input('Please enter consumer key: ') while not consumer_secret: consumer_secret = raw_input('Please enter consumer secret: ') auth_client = TwitterOAuthClient(consumer_key,consumer_secret) tok = auth_client.get_request_token() token = tok['oauth_token'] token_secret = tok['oauth_token_secret'] url = auth_client.get_authorize_url(token) webbrowser.open(url) print "Visit this URL to authorize your app: " + url response_token = raw_input('What is the oauth_token from twitter: ') response_client = TwitterOAuthClient(consumer_key, consumer_secret,token, token_secret) tok = response_client.get_access_token() print "Making signed request" #verify user access content = response_client.oauth_request('https://twitter.com/account/verify_credentials.json', method='POST') #make an update #content = response_client.oauth_request('https://twitter.com/statuses/update.xml', {'status':'Updated from a python oauth client. awesome.'}, method='POST') print content print 'Done.'
nandayadav/ruby-processing-kitchen-sink
7e0c64f8e01009ae4ce319988773766f8b63af2f
playing with text displays
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index c9ca4aa..c9e592f 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,168 +1,173 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'shovan' +USER = 'jeresig' PROFILE_SIZE = 48 #Default size of profile image as returned by API class TwitterNode - def initialize(x, y, z, size, r, g, b) + def initialize(x, y, z, size, r, g, b, name) @x = x @y = y @z = z @size = size @r = r @g = g @b = b @theta = 0 @orbit_speed = rand * 0.02 + 0.01 + @name = name end def update @theta += @orbit_speed end def display $app.push_matrix $app.rotate(@theta) $app.translate(@x, @y, @z) $app.fill(@r, @g, @b) - $app.sphere(@size) + #$app.sphere(@size) + $app.text_size(@size/4) + $app.text(@name, @x, @y, @z) $app.pop_matrix end end class NetworkViewer < Processing::App load_library :control_panel load_library :opengl include_package 'processing.opengl' def setup @client = TwitterClient::DataFetcher.new control_panel do |c| c.button :friends c.button :followers c.button :rotate_canvas end #no_loop @results = [] @twitter_nodes = [] size 900, 900, OPENGL @bg_x, @bg_y, @bg_z = 100, 100, 100 @initial = true @x, @y, @z = nil - text_font create_font("Georgia", 12, true) + text_font create_font("Georgia", 24, true) + text_mode(MODEL) + text_align(CENTER) end def rotate_canvas @initial = false redraw end def follower_range(results) min, max = results.first.followers_count, results.first.followers_count results.each do |r| min = r.followers_count if r.followers_count < min max = r.followers_count if r.followers_count > max end min = 1 if min == 0 return max, min end def mean_count(results) sum = results.map(&:followers_count).inject(0){|sum, val| sum + val} sum.to_f / results.size.to_f end def build_nodes followers if @results.empty? min_x = 100 min_y = 100 - max_x = 300 - max_y = 300 + max_x = 200 + max_y = 200 camera#(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) max, min = follower_range(@results) #puts "Max: #{max}, min: #{min}" scaling_factor = 80.0 / mean_count(@results) #for now @results.each do |r| x = min_x + rand(max_x - min_x) #x = r.followers_count % 700 y = min_y + rand(max_y - min_y) #y = r.followers_count % 700 z = rand(100) m = r.profile_background_color.match /(..)(..)(..)/ size = scaling_factor * r.followers_count size = size > 80 ? 80 : size - @twitter_nodes << TwitterNode.new(x, y, z, size, m[0].hex, m[1].hex, m[2].hex) + @twitter_nodes << TwitterNode.new(x, y, z, size, m[0].hex, m[1].hex, m[2].hex, r.screen_name) end end def draw build_nodes if @twitter_nodes.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 push_matrix #light_specular(255, 255, 255) directional_light(255, 255, 204, -1, 0, -1) #emissive(1, 1, 1) translate(x_center, y_center, 0) no_stroke @twitter_nodes.each do |t| t.update t.display end pop_matrix end # def old_draw # friends if @results.empty? # background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph # x1, y1 = nil, nil # x_center = width/2 # y_center = height/2 # radius = 300 # segment_angle = 360.0/@results.size.to_f # puts "Segment angle: #{segment_angle}" # puts "Nodes: #{@results.size}" # image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 # @results.each_with_index do |result, index| # index += 1 # theta = radians(index*segment_angle) # x = (cos(theta) * radius) + x_center # y = (sin(theta) * radius) + y_center # image_url = result.profile_image_url # b = load_image(image_url) # #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API # b.resize(image_size, image_size) # image(b, x, y) # line(x_center, y_center, x, y) # end # end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end #Control Panel methods def friends fetch_data('friends') redraw end def friend_ids fetch_data('friend_ids') redraw end def followers fetch_data('followers') redraw end end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
7a56f1a52e3b48c406adb8473a25bbd893e4f79b
proper rotation and translation
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index ad0e0b9..c9ca4aa 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,167 +1,168 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'jeresig' +USER = 'shovan' PROFILE_SIZE = 48 #Default size of profile image as returned by API class TwitterNode def initialize(x, y, z, size, r, g, b) @x = x @y = y @z = z @size = size @r = r @g = g @b = b @theta = 0 @orbit_speed = rand * 0.02 + 0.01 end def update - # Increment the angle to rotate @theta += @orbit_speed end def display - # Before rotation and translation, the state of the matrix is saved with push_matrix. $app.push_matrix - # Rotate orbit $app.rotate(@theta) - # translate out @distance $app.translate(@x, @y, @z) $app.fill(@r, @g, @b) $app.sphere(@size) - # Once the planet is drawn, the matrix is restored with pop_matrix so that the next planet is not affected. $app.pop_matrix end end class NetworkViewer < Processing::App load_library :control_panel load_library :opengl include_package 'processing.opengl' def setup @client = TwitterClient::DataFetcher.new control_panel do |c| c.button :friends c.button :followers c.button :rotate_canvas end #no_loop @results = [] - size 800, 800, OPENGL + @twitter_nodes = [] + size 900, 900, OPENGL @bg_x, @bg_y, @bg_z = 100, 100, 100 @initial = true - @x, @y, @z = 10.0, 10.0, 1.0 + @x, @y, @z = nil text_font create_font("Georgia", 12, true) end def rotate_canvas @initial = false redraw end def follower_range(results) min, max = results.first.followers_count, results.first.followers_count results.each do |r| min = r.followers_count if r.followers_count < min max = r.followers_count if r.followers_count > max end min = 1 if min == 0 return max, min end def mean_count(results) sum = results.map(&:followers_count).inject(0){|sum, val| sum + val} sum.to_f / results.size.to_f end def build_nodes followers if @results.empty? - @twitter_nodes = [] + min_x = 100 min_y = 100 - max_x = 700 - max_y = 700 + max_x = 300 + max_y = 300 camera#(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) max, min = follower_range(@results) #puts "Max: #{max}, min: #{min}" scaling_factor = 80.0 / mean_count(@results) #for now @results.each do |r| - #x = min_x + rand(max_x - min_x) - x = r.followers_count % 700 - #y = min_y + rand(max_y - min_y) - y = r.followers_count % 700 - z = 0 - color = r.profile_background_color - m = color.match /(..)(..)(..)/ + x = min_x + rand(max_x - min_x) + #x = r.followers_count % 700 + y = min_y + rand(max_y - min_y) + #y = r.followers_count % 700 + z = rand(100) + m = r.profile_background_color.match /(..)(..)(..)/ size = scaling_factor * r.followers_count size = size > 80 ? 80 : size @twitter_nodes << TwitterNode.new(x, y, z, size, m[0].hex, m[1].hex, m[2].hex) end end def draw - build_nodes + build_nodes if @twitter_nodes.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 + push_matrix + #light_specular(255, 255, 255) + directional_light(255, 255, 204, -1, 0, -1) + #emissive(1, 1, 1) + translate(x_center, y_center, 0) + no_stroke - lights @twitter_nodes.each do |t| t.update t.display end + pop_matrix end # def old_draw # friends if @results.empty? # background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph # x1, y1 = nil, nil # x_center = width/2 # y_center = height/2 # radius = 300 # segment_angle = 360.0/@results.size.to_f # puts "Segment angle: #{segment_angle}" # puts "Nodes: #{@results.size}" # image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 # @results.each_with_index do |result, index| # index += 1 # theta = radians(index*segment_angle) # x = (cos(theta) * radius) + x_center # y = (sin(theta) * radius) + y_center # image_url = result.profile_image_url # b = load_image(image_url) # #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API # b.resize(image_size, image_size) # image(b, x, y) # line(x_center, y_center, x, y) # end # end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end #Control Panel methods def friends fetch_data('friends') redraw end def friend_ids fetch_data('friend_ids') redraw end def followers fetch_data('followers') redraw end end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
c2a45493e51896a33af2141b7f0e9304721dc487
refactored draw and translation logic inside TwitterNode class
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index dd4aa5f..ad0e0b9 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,142 +1,167 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'billmaher' +USER = 'jeresig' PROFILE_SIZE = 48 #Default size of profile image as returned by API +class TwitterNode + + def initialize(x, y, z, size, r, g, b) + @x = x + @y = y + @z = z + @size = size + @r = r + @g = g + @b = b + @theta = 0 + @orbit_speed = rand * 0.02 + 0.01 + end + + def update + # Increment the angle to rotate + @theta += @orbit_speed + end + + def display + # Before rotation and translation, the state of the matrix is saved with push_matrix. + $app.push_matrix + # Rotate orbit + $app.rotate(@theta) + # translate out @distance + $app.translate(@x, @y, @z) + $app.fill(@r, @g, @b) + $app.sphere(@size) + # Once the planet is drawn, the matrix is restored with pop_matrix so that the next planet is not affected. + $app.pop_matrix + end + +end + class NetworkViewer < Processing::App load_library :control_panel load_library :opengl include_package 'processing.opengl' def setup @client = TwitterClient::DataFetcher.new control_panel do |c| c.button :friends c.button :followers c.button :rotate_canvas end - no_loop + #no_loop @results = [] size 800, 800, OPENGL @bg_x, @bg_y, @bg_z = 100, 100, 100 @initial = true @x, @y, @z = 10.0, 10.0, 1.0 text_font create_font("Georgia", 12, true) end def rotate_canvas @initial = false redraw end def follower_range(results) min, max = results.first.followers_count, results.first.followers_count results.each do |r| min = r.followers_count if r.followers_count < min max = r.followers_count if r.followers_count > max end min = 1 if min == 0 return max, min end def mean_count(results) sum = results.map(&:followers_count).inject(0){|sum, val| sum + val} sum.to_f / results.size.to_f end - def draw - if @initial + def build_nodes followers if @results.empty? - background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph - x1, y1 = nil, nil - x_center = width/2 - y_center = height/2 - no_stroke - lights + @twitter_nodes = [] min_x = 100 min_y = 100 max_x = 700 max_y = 700 camera#(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) max, min = follower_range(@results) #puts "Max: #{max}, min: #{min}" scaling_factor = 80.0 / mean_count(@results) #for now - puts "Scalinf Factor: #{scaling_factor}" - @results.each do |r| - x = min_x + rand(max_x - min_x) - y = min_y + rand(max_y - min_y) - z = rand(100) - #z = 0 - push_matrix - translate(x, y, z) + @results.each do |r| + #x = min_x + rand(max_x - min_x) + x = r.followers_count % 700 + #y = min_y + rand(max_y - min_y) + y = r.followers_count % 700 + z = 0 color = r.profile_background_color - name = r.screen_name m = color.match /(..)(..)(..)/ - fill(m[1].hex, m[2].hex, m[3].hex) size = scaling_factor * r.followers_count size = size > 80 ? 80 : size - sphere(size) #if r.followers_count - #text(name, x, y, z) - pop_matrix + @twitter_nodes << TwitterNode.new(x, y, z, size, m[0].hex, m[1].hex, m[2].hex) end - #@initial = false - else - @x += 1.0 - @y += 1.0 - @z += 0.1 - #camera(@x, @y, @z, @x, @y, 0.0, 0.0, 0.0, 0.0) - sphere(rand(100)) - - end - #push_matrix - #rotate(1) - #pop_matrix end - def old_draw - friends if @results.empty? + def draw + build_nodes background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 - radius = 300 - segment_angle = 360.0/@results.size.to_f - puts "Segment angle: #{segment_angle}" - puts "Nodes: #{@results.size}" - image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 - @results.each_with_index do |result, index| - index += 1 - theta = radians(index*segment_angle) - x = (cos(theta) * radius) + x_center - y = (sin(theta) * radius) + y_center - image_url = result.profile_image_url - b = load_image(image_url) - #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API - b.resize(image_size, image_size) - image(b, x, y) - line(x_center, y_center, x, y) + no_stroke + lights + @twitter_nodes.each do |t| + t.update + t.display end end + # def old_draw + # friends if @results.empty? + # background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph + # x1, y1 = nil, nil + # x_center = width/2 + # y_center = height/2 + # radius = 300 + # segment_angle = 360.0/@results.size.to_f + # puts "Segment angle: #{segment_angle}" + # puts "Nodes: #{@results.size}" + # image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 + # @results.each_with_index do |result, index| + # index += 1 + # theta = radians(index*segment_angle) + # x = (cos(theta) * radius) + x_center + # y = (sin(theta) * radius) + y_center + # image_url = result.profile_image_url + # b = load_image(image_url) + # #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API + # b.resize(image_size, image_size) + # image(b, x, y) + # line(x_center, y_center, x, y) + # end + # end + def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end #Control Panel methods def friends fetch_data('friends') redraw end def friend_ids fetch_data('friend_ids') redraw end def followers fetch_data('followers') redraw end end + NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
c3117a7dff7bfe55b53b4ea33b1c1c3b1755ac2d
added scaling factor for sphere size to take into followers/friends count
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index 2a7fe2c..dd4aa5f 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,121 +1,142 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' USER = 'billmaher' PROFILE_SIZE = 48 #Default size of profile image as returned by API class NetworkViewer < Processing::App load_library :control_panel load_library :opengl include_package 'processing.opengl' def setup @client = TwitterClient::DataFetcher.new control_panel do |c| c.button :friends c.button :followers c.button :rotate_canvas end no_loop @results = [] size 800, 800, OPENGL @bg_x, @bg_y, @bg_z = 100, 100, 100 @initial = true @x, @y, @z = 10.0, 10.0, 1.0 text_font create_font("Georgia", 12, true) end def rotate_canvas @initial = false redraw end + def follower_range(results) + min, max = results.first.followers_count, results.first.followers_count + results.each do |r| + min = r.followers_count if r.followers_count < min + max = r.followers_count if r.followers_count > max + end + min = 1 if min == 0 + return max, min + end + + def mean_count(results) + sum = results.map(&:followers_count).inject(0){|sum, val| sum + val} + sum.to_f / results.size.to_f + end + def draw if @initial followers if @results.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 no_stroke lights min_x = 100 min_y = 100 max_x = 700 max_y = 700 camera#(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) + max, min = follower_range(@results) + #puts "Max: #{max}, min: #{min}" + scaling_factor = 80.0 / mean_count(@results) #for now + puts "Scalinf Factor: #{scaling_factor}" @results.each do |r| x = min_x + rand(max_x - min_x) y = min_y + rand(max_y - min_y) z = rand(100) #z = 0 push_matrix translate(x, y, z) color = r.profile_background_color name = r.screen_name m = color.match /(..)(..)(..)/ fill(m[1].hex, m[2].hex, m[3].hex) - sphere(rand(50)) + size = scaling_factor * r.followers_count + size = size > 80 ? 80 : size + sphere(size) #if r.followers_count #text(name, x, y, z) pop_matrix end #@initial = false else @x += 1.0 @y += 1.0 @z += 0.1 #camera(@x, @y, @z, @x, @y, 0.0, 0.0, 0.0, 0.0) sphere(rand(100)) end #push_matrix #rotate(1) #pop_matrix end def old_draw friends if @results.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 radius = 300 segment_angle = 360.0/@results.size.to_f puts "Segment angle: #{segment_angle}" puts "Nodes: #{@results.size}" image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 @results.each_with_index do |result, index| index += 1 theta = radians(index*segment_angle) x = (cos(theta) * radius) + x_center y = (sin(theta) * radius) + y_center image_url = result.profile_image_url b = load_image(image_url) #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API b.resize(image_size, image_size) image(b, x, y) line(x_center, y_center, x, y) end end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end #Control Panel methods def friends fetch_data('friends') redraw end def friend_ids fetch_data('friend_ids') redraw end def followers fetch_data('followers') redraw end end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
760ff87edff8ae72799a515eecc4bbc54af41011
hack to get twitter color scheme working nicely with processing
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index 84dae7e..2a7fe2c 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,107 +1,121 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'jeresig' +USER = 'billmaher' PROFILE_SIZE = 48 #Default size of profile image as returned by API class NetworkViewer < Processing::App load_library :control_panel load_library :opengl include_package 'processing.opengl' def setup @client = TwitterClient::DataFetcher.new control_panel do |c| c.button :friends c.button :followers c.button :rotate_canvas end no_loop @results = [] size 800, 800, OPENGL @bg_x, @bg_y, @bg_z = 100, 100, 100 @initial = true + @x, @y, @z = 10.0, 10.0, 1.0 + text_font create_font("Georgia", 12, true) end def rotate_canvas @initial = false redraw end def draw if @initial - friend_ids if @results.empty? + followers if @results.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 no_stroke lights min_x = 100 min_y = 100 max_x = 700 max_y = 700 - camera(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) - @results.size.times do + camera#(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) + @results.each do |r| x = min_x + rand(max_x - min_x) y = min_y + rand(max_y - min_y) z = rand(100) + #z = 0 push_matrix translate(x, y, z) - #fill(rand(255),rand(255),rand(255)) - sphere(rand(30)) + color = r.profile_background_color + name = r.screen_name + m = color.match /(..)(..)(..)/ + fill(m[1].hex, m[2].hex, m[3].hex) + sphere(rand(50)) + #text(name, x, y, z) pop_matrix end - else + #@initial = false + else + @x += 1.0 + @y += 1.0 + @z += 0.1 + #camera(@x, @y, @z, @x, @y, 0.0, 0.0, 0.0, 0.0) + sphere(rand(100)) + + end #push_matrix - rotate(45) + #rotate(1) #pop_matrix - end end def old_draw friends if @results.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 radius = 300 segment_angle = 360.0/@results.size.to_f puts "Segment angle: #{segment_angle}" puts "Nodes: #{@results.size}" image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 @results.each_with_index do |result, index| index += 1 theta = radians(index*segment_angle) x = (cos(theta) * radius) + x_center y = (sin(theta) * radius) + y_center image_url = result.profile_image_url b = load_image(image_url) #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API b.resize(image_size, image_size) image(b, x, y) line(x_center, y_center, x, y) end end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end #Control Panel methods def friends fetch_data('friends') redraw end def friend_ids fetch_data('friend_ids') redraw end def followers fetch_data('followers') redraw end end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
60490e8814b61beafe48d29ffe8007d1f2095eb3
tryig out different transformations
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index b98daf5..84dae7e 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,62 +1,107 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'nandayadav' +USER = 'jeresig' PROFILE_SIZE = 48 #Default size of profile image as returned by API class NetworkViewer < Processing::App load_library :control_panel + load_library :opengl + include_package 'processing.opengl' def setup @client = TwitterClient::DataFetcher.new control_panel do |c| c.button :friends c.button :followers + c.button :rotate_canvas end no_loop @results = [] - size 800, 800 + size 800, 800, OPENGL @bg_x, @bg_y, @bg_z = 100, 100, 100 + @initial = true + end + + def rotate_canvas + @initial = false + redraw end def draw + if @initial + friend_ids if @results.empty? + background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph + x1, y1 = nil, nil + x_center = width/2 + y_center = height/2 + no_stroke + lights + min_x = 100 + min_y = 100 + max_x = 700 + max_y = 700 + camera(300.0, 300.0, 1.0, 300.0, 300.0, 0.0, 0.0, 0.0, 0.0) + @results.size.times do + x = min_x + rand(max_x - min_x) + y = min_y + rand(max_y - min_y) + z = rand(100) + push_matrix + translate(x, y, z) + #fill(rand(255),rand(255),rand(255)) + sphere(rand(30)) + pop_matrix + end + else + #push_matrix + rotate(45) + #pop_matrix + end + end + + def old_draw friends if @results.empty? background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 radius = 300 segment_angle = 360.0/@results.size.to_f puts "Segment angle: #{segment_angle}" puts "Nodes: #{@results.size}" image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 @results.each_with_index do |result, index| index += 1 theta = radians(index*segment_angle) x = (cos(theta) * radius) + x_center y = (sin(theta) * radius) + y_center image_url = result.profile_image_url b = load_image(image_url) #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API b.resize(image_size, image_size) image(b, x, y) line(x_center, y_center, x, y) end end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end #Control Panel methods def friends fetch_data('friends') redraw end + def friend_ids + fetch_data('friend_ids') + redraw + end + def followers fetch_data('followers') redraw end end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
598101213202b21c8cb006e40550bc5b5263ded7
using resourceful for http stuff
diff --git a/google_social/lib/social_graph.rb b/google_social/lib/social_graph.rb index 41cbb39..d3fc06d 100644 --- a/google_social/lib/social_graph.rb +++ b/google_social/lib/social_graph.rb @@ -1,37 +1,37 @@ -require 'net/http' require 'rubygems' +require 'resourceful' require 'uri' require 'json' module SocialGraph URL = 'http://socialgraph.apis.google.com/' def lookup(params) raise "Enter params in hash format" unless params.is_a?(Hash) url = URL + "lookup" + build_query(params) get_json(url) end def otherme(params) raise "Enter params in hash format" unless params.is_a?(Hash) url = URL + "otherme" + build_query(params) get_json(url) end def testparse(params) end #Normal Get result loaded as Json hash private def get_json(url) - response = Net::HTTP.get(URI.parse(url)) - JSON::load(response) + response = Resourceful.get(URI.parse(url)) + JSON::load(response.body) end def build_query(hash) str = "?" hash.each{ |key, val| str += "#{key}=#{val}&" } str end end
nandayadav/ruby-processing-kitchen-sink
5b73fc78e8bea444cdb0dfb4bc40deb7d832fca3
google social graph api code
diff --git a/google_social/lib/social_graph.rb b/google_social/lib/social_graph.rb new file mode 100644 index 0000000..41cbb39 --- /dev/null +++ b/google_social/lib/social_graph.rb @@ -0,0 +1,37 @@ +require 'net/http' +require 'rubygems' +require 'uri' +require 'json' + +module SocialGraph + URL = 'http://socialgraph.apis.google.com/' + + def lookup(params) + raise "Enter params in hash format" unless params.is_a?(Hash) + url = URL + "lookup" + build_query(params) + get_json(url) + end + + def otherme(params) + raise "Enter params in hash format" unless params.is_a?(Hash) + url = URL + "otherme" + build_query(params) + get_json(url) + end + + def testparse(params) + end + + #Normal Get result loaded as Json hash + private + def get_json(url) + response = Net::HTTP.get(URI.parse(url)) + JSON::load(response) + end + + def build_query(hash) + str = "?" + hash.each{ |key, val| str += "#{key}=#{val}&" } + str + end + +end diff --git a/google_social/viewer.rb b/google_social/viewer.rb new file mode 100644 index 0000000..a0c8632 --- /dev/null +++ b/google_social/viewer.rb @@ -0,0 +1 @@ +#nothing yet \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
b324850095bbcdee9d50bd6672fc439704a1fe4b
added control panel, nodes in a circle with dynamic image size
diff --git a/twitter_visuals/.gitignore b/twitter_visuals/.gitignore deleted file mode 100644 index 418beaa..0000000 --- a/twitter_visuals/.gitignore +++ /dev/null @@ -1 +0,0 @@ -config/credentials.yml diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index 5f8f739..b98daf5 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,34 +1,62 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'shovan' +USER = 'nandayadav' +PROFILE_SIZE = 48 #Default size of profile image as returned by API + class NetworkViewer < Processing::App + load_library :control_panel def setup @client = TwitterClient::DataFetcher.new + control_panel do |c| + c.button :friends + c.button :followers + end no_loop @results = [] size 800, 800 + @bg_x, @bg_y, @bg_z = 100, 100, 100 end - def draw - fetch_data('friends') + friends if @results.empty? + background(@bg_x, @bg_y, @bg_z) #To wipe out existing graph x1, y1 = nil, nil x_center = width/2 y_center = height/2 - @results.each do |result| + radius = 300 + segment_angle = 360.0/@results.size.to_f + puts "Segment angle: #{segment_angle}" + puts "Nodes: #{@results.size}" + image_size = segment_angle*4.0 > PROFILE_SIZE ? PROFILE_SIZE : segment_angle*4.0 + @results.each_with_index do |result, index| + index += 1 + theta = radians(index*segment_angle) + x = (cos(theta) * radius) + x_center + y = (sin(theta) * radius) + y_center image_url = result.profile_image_url - b = loadImage(image_url) - x, y = rand(width - 100), rand(height - 100) + b = load_image(image_url) #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API - b.resize(40,40) + b.resize(image_size, image_size) image(b, x, y) line(x_center, y_center, x, y) end end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end + + #Control Panel methods + def friends + fetch_data('friends') + redraw + end + + def followers + fetch_data('followers') + redraw + end + end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
0982c48c30ce8f79109873f774a5d406b1e520ab
gitignore credentials
diff --git a/twitter_visuals/.gitignore b/twitter_visuals/.gitignore new file mode 100644 index 0000000..418beaa --- /dev/null +++ b/twitter_visuals/.gitignore @@ -0,0 +1 @@ +config/credentials.yml
nandayadav/ruby-processing-kitchen-sink
7fd2e48f860c03109cb6054a3a99e32da0be34f4
took our unnecessary inst vars, uniform image sizes, proper visualiaztion with a centralized node
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index 26244c5..5f8f739 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,29 +1,34 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' -USER = 'nandayadav' +USER = 'shovan' class NetworkViewer < Processing::App def setup @client = TwitterClient::DataFetcher.new no_loop @results = [] - @height, @width = 800, 800 - size @height, @width + size 800, 800 end def draw fetch_data('friends') + x1, y1 = nil, nil + x_center = width/2 + y_center = height/2 @results.each do |result| image_url = result.profile_image_url b = loadImage(image_url) - x, y = rand(@width - 100), rand(@height - 100) + x, y = rand(width - 100), rand(height - 100) + #Smaller images, also to nullify sporadic 'big' profile images returned by twitter API + b.resize(40,40) image(b, x, y) + line(x_center, y_center, x, y) end end def fetch_data(method = 'followers') @results = [] #reset @results = eval("@client.#{method}('#{USER}')") end end NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
afeb0c5ae87dd32f383908f820e9cb74c9bad0de
some minor tweaks
diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb index db3df0f..26244c5 100644 --- a/twitter_visuals/network_viewer.rb +++ b/twitter_visuals/network_viewer.rb @@ -1,29 +1,29 @@ #Social Graph visualization(followers/friends) for specific twitter profile require 'lib/twitter_api' - -class Viewer < Processing::App +USER = 'nandayadav' +class NetworkViewer < Processing::App def setup @client = TwitterClient::DataFetcher.new no_loop @results = [] @height, @width = 800, 800 size @height, @width end def draw - fetch_data#('friends') - @results.each_with_index do |result, index| + fetch_data('friends') + @results.each do |result| image_url = result.profile_image_url b = loadImage(image_url) x, y = rand(@width - 100), rand(@height - 100) image(b, x, y) end end def fetch_data(method = 'followers') @results = [] #reset - @results = eval("@client.#{method}('ConanOBrien')") + @results = eval("@client.#{method}('#{USER}')") end end -Viewer.new :title => "Social Graph" \ No newline at end of file +NetworkViewer.new :title => "Twitter Social Graph - #{USER}" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
e6fa566d0f378897e2a72a78a862c9e803fb81c8
added friends/followers visulization
diff --git a/README b/README index a7a70d1..6562ce3 100644 --- a/README +++ b/README @@ -1,25 +1,37 @@ Various small projects using different api data and ruby-processing for visuals #getting setup 1. I haven't got it working in a non-jruby environment, so I prefer to use just rvm and install jruby rvm install jruby 2. rvm jruby (to switch to jruby) 3. gem install ruby-processing 4. gem install twitter (twitter api) #twitter-visuals -- viewer.rb [visualize image profiles for latest tweet for a certain term) To run: rp5 run viewer.rb --jruby Currently its pretty generic, just shows image profiles for latest tweets for certain term Mouse clicks: - When mouse is pressed, api is hit continuously and new image profiles are rendered randomly around the click area - When mouse is released, the continuous rendering is stopped. - When mouse is pressed and moved around, images are rendered randomnly around that path. + -- network_viewer [visualize image profiles for friends/followers for a particular user] + To run: rp5 run network_viewer.rb --jruby + + + #TODO: (lots) + viewer - embed link url to actual tweet - display the tweet - better randomization of images + - use OAuth instead of HTTP auth + + network_viewer + - explore linking profile images + - add more weight(size) to profiles with highest followers?? rank?? + - explore adding links to profile images that redoes visualization for that profile diff --git a/twitter_visuals/config/credentials.yml b/twitter_visuals/config/credentials.yml new file mode 100644 index 0000000..b394a19 --- /dev/null +++ b/twitter_visuals/config/credentials.yml @@ -0,0 +1,5 @@ +email: + "put ur twitter email here" + +password: + "put ur password here" \ No newline at end of file diff --git a/twitter_visuals/lib/twitter_api.rb b/twitter_visuals/lib/twitter_api.rb index b738c29..c444d8f 100644 --- a/twitter_visuals/lib/twitter_api.rb +++ b/twitter_visuals/lib/twitter_api.rb @@ -1,21 +1,49 @@ require 'rubygems' -#Gem.clear_paths -#ENV['GEM_HOME'] = '/usr/lib/jruby-1.4.0/lib/ruby/gems/1.8' -#ENV['GEM_PATH'] = '/usr/lib/jruby-1.4.0/lib/ruby/gems/1.8' require 'twitter' module TwitterClient class DataFetcher - attr_accessor :search_results + def initialize(options = {}) @options = options @search_results = [] - @trend_results = [] end def search(tag) @search_results = Twitter::Search.new("##{tag}").fetch().results end + def friends(screen_name = nil) + authorize_and_base if @client.nil? + return @client.friends(:screen_name => screen_name) if screen_name && !screen_name.empty? + @client.friends + end + + def followers(screen_name = nil) + authorize_and_base if @client.nil? + return @client.followers(:screen_name => screen_name) if screen_name && !screen_name.empty? + @client.followers + end + + def follower_ids(screen_name = nil) + authorize_and_base if @client.nil? + return @client.follower_ids(:screen_name => screen_name) if screen_name && !screen_name.empty? + @client.follower_ids + end + + def friend_ids(screen_name = nil) + authorize_and_base if @client.nil? + return @client.friend_ids(:screen_name => screen_name) if screen_name && !screen_name.empty? + @client.friend_ids + end + + private + + def authorize_and_base + cred = YAML::load(File.open(File.dirname(__FILE__) + '/../config/credentials.yml')) + @httpauth ||= Twitter::HTTPAuth.new(cred['email'], cred['password']) + @client ||= Twitter::Base.new(@httpauth) + end + end end \ No newline at end of file diff --git a/twitter_visuals/network_viewer.rb b/twitter_visuals/network_viewer.rb new file mode 100644 index 0000000..db3df0f --- /dev/null +++ b/twitter_visuals/network_viewer.rb @@ -0,0 +1,29 @@ +#Social Graph visualization(followers/friends) for specific twitter profile +require 'lib/twitter_api' + +class Viewer < Processing::App + def setup + @client = TwitterClient::DataFetcher.new + no_loop + @results = [] + @height, @width = 800, 800 + size @height, @width + end + + + def draw + fetch_data#('friends') + @results.each_with_index do |result, index| + image_url = result.profile_image_url + b = loadImage(image_url) + x, y = rand(@width - 100), rand(@height - 100) + image(b, x, y) + end + end + + def fetch_data(method = 'followers') + @results = [] #reset + @results = eval("@client.#{method}('ConanOBrien')") + end +end +Viewer.new :title => "Social Graph" \ No newline at end of file
nandayadav/ruby-processing-kitchen-sink
755e96c0155816c2a878d53ea31548b1ab2d85f4
some cleanup
diff --git a/twitter_visuals/viewer.rb b/twitter_visuals/viewer.rb index 907881d..2b1dad8 100644 --- a/twitter_visuals/viewer.rb +++ b/twitter_visuals/viewer.rb @@ -1,120 +1,105 @@ require 'lib/twitter_api' class Viewer < Processing::App load_library :control_panel FADE_THRESHOLD = 3 def setup size 1000, 1000 @results = [] @rendered_images = [] control_panel do |c| - c.button :generate_stuff - c.menu(:options, ['none', 'blur', 'erode', 'gray','invert','opaque','dilate'], 'none') {|m| modify_image(m) } + c.button :re_draw + c.menu(:filter_options, ['none', 'blur', 'erode', 'gray','invert','opaque','dilate'], 'none') {|m| modify_image(m) } end no_loop @link = nil @client = TwitterClient::DataFetcher.new @terms = ['Nepal','Maradona','Kobe','Glen Beck','oscars'] @mode = nil @bg_x, @bg_y, @bg_z = 100, 100, 100 background(@bg_x, @bg_y, @bg_z) end def modify_image(mode) if ['none','other'].include?(mode) @mode = nil else @mode = mode.upcase end redraw end - def generate_stuff + def re_draw redraw end def draw - #rect(10,10,20,20) fetch_data x, y = mouse_x, mouse_y filter_old_images @results.each_with_index do |result, index| - #sleep 1 image_url = result.profile_image_url b = loadImage(image_url) if index.even? x += rand(80) y += rand(80) else x -= rand(80) y -= rand(80) end @link = result.source puts "Link: #{@link}" @rendered_images << {:image => b, :x => x, :y => y, :counter => 0} - # push_matrix - # case @mode - # when 'BLUR' - # b.filter(BLUR, 2) - # when 'ERODE' - # b.filter(ERODE) - # when 'DILATE' - # b.filter(DILATE) - # end image(b, x, y) - #pop_matrix end end #Replace image pixels with background pixels def fade_image(image) img = image[:image] x,y = image[:x], image[:y] dimension = (img.width*img.height) img.load_pixels - (0..dimension-1).each do |i| - img.pixels[i] = color(@bg_x, @bg_y, @bg_z) - end + (0..dimension-1).each{ |i| img.pixels[i] = color(@bg_x, @bg_y, @bg_z) } img.update_pixels image(img,x,y) end #Apply various image filters def filter_old_images @rendered_images.each do |i| img = i[:image] case @mode when 'ERODE' img.filter(ERODE) when 'DILATE' img.filter(DILATE) else img.filter(BLUR,4) end - #img.resize(img.width/2, img.height/2) image(img, i[:x], i[:y]) i[:counter] += 1 fade_image(i) if i[:counter] > FADE_THRESHOLD end end def fetch_data @results = [] @results = @client.search(@terms.sort_by{rand}.first) end def mouse_pressed loop end def mouse_released no_loop link(@link, "_new") end end Viewer.new :title => "Twitter Search - Nepal", :width => 1000, :height => 1000
nandayadav/ruby-processing-kitchen-sink
1117d1b5997264eb8d30a1d5f75f34e2d5b34a0e
better image fading
diff --git a/twitter_visuals/viewer.rb b/twitter_visuals/viewer.rb index e6d7da6..907881d 100644 --- a/twitter_visuals/viewer.rb +++ b/twitter_visuals/viewer.rb @@ -1,99 +1,120 @@ require 'lib/twitter_api' class Viewer < Processing::App load_library :control_panel + FADE_THRESHOLD = 3 def setup size 1000, 1000 @results = [] @rendered_images = [] control_panel do |c| c.button :generate_stuff c.menu(:options, ['none', 'blur', 'erode', 'gray','invert','opaque','dilate'], 'none') {|m| modify_image(m) } end no_loop @link = nil @client = TwitterClient::DataFetcher.new @terms = ['Nepal','Maradona','Kobe','Glen Beck','oscars'] @mode = nil + @bg_x, @bg_y, @bg_z = 100, 100, 100 + background(@bg_x, @bg_y, @bg_z) end def modify_image(mode) if ['none','other'].include?(mode) @mode = nil else @mode = mode.upcase end redraw end def generate_stuff redraw end def draw #rect(10,10,20,20) fetch_data x, y = mouse_x, mouse_y - blur_old_images + filter_old_images @results.each_with_index do |result, index| #sleep 1 image_url = result.profile_image_url b = loadImage(image_url) if index.even? x += rand(80) y += rand(80) else x -= rand(80) y -= rand(80) end @link = result.source puts "Link: #{@link}" - @rendered_images << {:image => b, :x => x, :y => y} + @rendered_images << {:image => b, :x => x, :y => y, :counter => 0} # push_matrix # case @mode # when 'BLUR' # b.filter(BLUR, 2) # when 'ERODE' # b.filter(ERODE) # when 'DILATE' # b.filter(DILATE) # end image(b, x, y) #pop_matrix end end - def blur_old_images - @rendered_images.each do |img| + #Replace image pixels with background pixels + def fade_image(image) + img = image[:image] + x,y = image[:x], image[:y] + dimension = (img.width*img.height) + img.load_pixels + (0..dimension-1).each do |i| + img.pixels[i] = color(@bg_x, @bg_y, @bg_z) + end + img.update_pixels + image(img,x,y) + end + + #Apply various image filters + def filter_old_images + @rendered_images.each do |i| + img = i[:image] case @mode when 'ERODE' - img[:image].filter(ERODE) + img.filter(ERODE) when 'DILATE' - img[:image].filter(DILATE) + img.filter(DILATE) else - img[:image].filter(BLUR,2) + img.filter(BLUR,4) end - image(img[:image], img[:x], img[:y]) + #img.resize(img.width/2, img.height/2) + image(img, i[:x], i[:y]) + i[:counter] += 1 + fade_image(i) if i[:counter] > FADE_THRESHOLD end end def fetch_data @results = [] @results = @client.search(@terms.sort_by{rand}.first) end def mouse_pressed loop end def mouse_released no_loop link(@link, "_new") end end Viewer.new :title => "Twitter Search - Nepal", :width => 1000, :height => 1000
nandayadav/ruby-processing-kitchen-sink
b70b3d54199cc48ec45355d5f109463dfd5ef5a2
fixed image manipulation
diff --git a/twitter_visuals/viewer.rb b/twitter_visuals/viewer.rb index 91f9df3..e6d7da6 100644 --- a/twitter_visuals/viewer.rb +++ b/twitter_visuals/viewer.rb @@ -1,92 +1,99 @@ require 'lib/twitter_api' class Viewer < Processing::App load_library :control_panel def setup size 1000, 1000 @results = [] @rendered_images = [] control_panel do |c| c.button :generate_stuff c.menu(:options, ['none', 'blur', 'erode', 'gray','invert','opaque','dilate'], 'none') {|m| modify_image(m) } end no_loop @link = nil @client = TwitterClient::DataFetcher.new @terms = ['Nepal','Maradona','Kobe','Glen Beck','oscars'] @mode = nil end def modify_image(mode) if ['none','other'].include?(mode) @mode = nil else @mode = mode.upcase end redraw end def generate_stuff redraw end def draw #rect(10,10,20,20) fetch_data x, y = mouse_x, mouse_y + blur_old_images @results.each_with_index do |result, index| #sleep 1 image_url = result.profile_image_url b = loadImage(image_url) if index.even? x += rand(80) y += rand(80) else x -= rand(80) y -= rand(80) end @link = result.source puts "Link: #{@link}" - @rendered_images << b - push_matrix + @rendered_images << {:image => b, :x => x, :y => y} + # push_matrix + # case @mode + # when 'BLUR' + # b.filter(BLUR, 2) + # when 'ERODE' + # b.filter(ERODE) + # when 'DILATE' + # b.filter(DILATE) + # end image(b, x, y) - case @mode - when 'BLUR' - filter(BLUR, 2) - when 'ERODE' - filter(ERODE) - when 'DILATE' - filter(DILATE) - end - pop_matrix + #pop_matrix end - #blur_old_images + end def blur_old_images - push_matrix @rendered_images.each do |img| - filter(BLUR,2) + case @mode + when 'ERODE' + img[:image].filter(ERODE) + when 'DILATE' + img[:image].filter(DILATE) + else + img[:image].filter(BLUR,2) + end + image(img[:image], img[:x], img[:y]) end - pop_matrix end def fetch_data @results = [] @results = @client.search(@terms.sort_by{rand}.first) end def mouse_pressed loop end def mouse_released no_loop link(@link, "_new") end end Viewer.new :title => "Twitter Search - Nepal", :width => 1000, :height => 1000
nandayadav/ruby-processing-kitchen-sink
f9b313edf65ba24322d2760952adbd5de7633616
added basic control panel with image filtering capability
diff --git a/twitter_visuals/viewer.rb b/twitter_visuals/viewer.rb index 4f1dbfb..91f9df3 100644 --- a/twitter_visuals/viewer.rb +++ b/twitter_visuals/viewer.rb @@ -1,46 +1,92 @@ require 'lib/twitter_api' class Viewer < Processing::App - + load_library :control_panel def setup size 1000, 1000 @results = [] + @rendered_images = [] + control_panel do |c| + c.button :generate_stuff + c.menu(:options, ['none', 'blur', 'erode', 'gray','invert','opaque','dilate'], 'none') {|m| modify_image(m) } + end no_loop + @link = nil + @client = TwitterClient::DataFetcher.new + @terms = ['Nepal','Maradona','Kobe','Glen Beck','oscars'] + @mode = nil + end + + def modify_image(mode) + if ['none','other'].include?(mode) + @mode = nil + else + @mode = mode.upcase + end + redraw + end + + + def generate_stuff + redraw end def draw #rect(10,10,20,20) fetch_data x, y = mouse_x, mouse_y @results.each_with_index do |result, index| + #sleep 1 image_url = result.profile_image_url b = loadImage(image_url) if index.even? x += rand(80) y += rand(80) else x -= rand(80) y -= rand(80) end - #link(result.source, "_new") + @link = result.source + puts "Link: #{@link}" + + @rendered_images << b + push_matrix image(b, x, y) + case @mode + when 'BLUR' + filter(BLUR, 2) + when 'ERODE' + filter(ERODE) + when 'DILATE' + filter(DILATE) + end + pop_matrix + end + #blur_old_images + end + + def blur_old_images + push_matrix + @rendered_images.each do |img| + filter(BLUR,2) end + pop_matrix end def fetch_data - client = TwitterClient::DataFetcher.new - terms = ['Nepal','Maradona','Kobe','Glen Beck','oscars'] - @results = client.search(terms.sort_by{rand}.first) + @results = [] + @results = @client.search(@terms.sort_by{rand}.first) end def mouse_pressed loop end def mouse_released no_loop + link(@link, "_new") end end Viewer.new :title => "Twitter Search - Nepal", :width => 1000, :height => 1000
nandayadav/ruby-processing-kitchen-sink
608f0128ba2eb7724a65ea14cfe085377abacd87
added jruby flag in readme
diff --git a/README b/README index 8c3bee2..a7a70d1 100644 --- a/README +++ b/README @@ -1,25 +1,25 @@ Various small projects using different api data and ruby-processing for visuals #getting setup 1. I haven't got it working in a non-jruby environment, so I prefer to use just rvm and install jruby rvm install jruby 2. rvm jruby (to switch to jruby) 3. gem install ruby-processing 4. gem install twitter (twitter api) #twitter-visuals -- viewer.rb [visualize image profiles for latest tweet for a certain term) - To run: rp5 run viewer.rb + To run: rp5 run viewer.rb --jruby Currently its pretty generic, just shows image profiles for latest tweets for certain term Mouse clicks: - When mouse is pressed, api is hit continuously and new image profiles are rendered randomly around the click area - When mouse is released, the continuous rendering is stopped. - When mouse is pressed and moved around, images are rendered randomnly around that path. #TODO: (lots) - embed link url to actual tweet - display the tweet - better randomization of images
nandayadav/ruby-processing-kitchen-sink
26c1570cbd482b6b4bee3a87f962f1ef072af462
added mouseclicked/released events
diff --git a/README b/README index e69de29..b34b384 100644 --- a/README +++ b/README @@ -0,0 +1,2 @@ +Various small projects using different api data and ruby-processing for visuals + diff --git a/twitter_visuals/viewer.rb b/twitter_visuals/viewer.rb index 7b96024..4f1dbfb 100644 --- a/twitter_visuals/viewer.rb +++ b/twitter_visuals/viewer.rb @@ -1,33 +1,46 @@ require 'lib/twitter_api' class Viewer < Processing::App - #load_library :opengl - #include_package 'processing.opengl' + def setup - size 1000, 1000#, OPENGL + size 1000, 1000 @results = [] no_loop end def draw - rect(10,10,20,20) + #rect(10,10,20,20) fetch_data - x, y = 0, 0 - @results.each do |result| + x, y = mouse_x, mouse_y + @results.each_with_index do |result, index| image_url = result.profile_image_url b = loadImage(image_url) - x += 50 - y += 50 - link(result.source, "_new") + if index.even? + x += rand(80) + y += rand(80) + else + x -= rand(80) + y -= rand(80) + end + #link(result.source, "_new") image(b, x, y) end end def fetch_data client = TwitterClient::DataFetcher.new - @results = client.search("nepal") + terms = ['Nepal','Maradona','Kobe','Glen Beck','oscars'] + @results = client.search(terms.sort_by{rand}.first) + end + + def mouse_pressed + loop + end + + def mouse_released + no_loop end end -Viewer.new :title => "3D Visualization", :width => 1000, :height => 1000 +Viewer.new :title => "Twitter Search - Nepal", :width => 1000, :height => 1000
nandayadav/ruby-processing-kitchen-sink
ad040d1119bad8d772096f0fcc332a04fb689e8b
twitter visuals
diff --git a/twitter_visuals/lib/twitter_api.rb b/twitter_visuals/lib/twitter_api.rb new file mode 100644 index 0000000..b738c29 --- /dev/null +++ b/twitter_visuals/lib/twitter_api.rb @@ -0,0 +1,21 @@ +require 'rubygems' +#Gem.clear_paths +#ENV['GEM_HOME'] = '/usr/lib/jruby-1.4.0/lib/ruby/gems/1.8' +#ENV['GEM_PATH'] = '/usr/lib/jruby-1.4.0/lib/ruby/gems/1.8' +require 'twitter' + +module TwitterClient + class DataFetcher + attr_accessor :search_results + def initialize(options = {}) + @options = options + @search_results = [] + @trend_results = [] + end + + def search(tag) + @search_results = Twitter::Search.new("##{tag}").fetch().results + end + + end +end \ No newline at end of file diff --git a/twitter_visuals/viewer.rb b/twitter_visuals/viewer.rb new file mode 100644 index 0000000..7b96024 --- /dev/null +++ b/twitter_visuals/viewer.rb @@ -0,0 +1,33 @@ +require 'lib/twitter_api' + +class Viewer < Processing::App + #load_library :opengl + #include_package 'processing.opengl' + def setup + size 1000, 1000#, OPENGL + @results = [] + no_loop + end + + def draw + rect(10,10,20,20) + fetch_data + x, y = 0, 0 + @results.each do |result| + image_url = result.profile_image_url + b = loadImage(image_url) + x += 50 + y += 50 + link(result.source, "_new") + image(b, x, y) + end + end + + def fetch_data + client = TwitterClient::DataFetcher.new + @results = client.search("nepal") + end + + +end +Viewer.new :title => "3D Visualization", :width => 1000, :height => 1000
yeco/SimplePong
692a30b3924a43b832f92a2a509172a37ce8c0be
Fixed chunked looping
diff --git a/SimplePong.as b/SimplePong.as index 81e182b..e4e5b88 100644 --- a/SimplePong.as +++ b/SimplePong.as @@ -1,102 +1,102 @@ /** * SimplePong * -* Quite simple pong game +* Quite simple Brain Teaser pong game * * @author Yëco * * */ package { import flash.display.MovieClip; import flash.display.Stage; import flash.display.StageQuality; import flash.display.Sprite; public class SimplePong extends MovieClip { public var velocity = { x: -10, y: 10 }; public var player1 = new Sprite(); public var player2 = new Sprite(); public var ball = new Sprite(); public function SimplePong() { stage.align = "TL"; stage.scaleMode = "noScale"; addChild(player1); addChild(player2); addChild(ball); // drawing the squares draw(player1, 40, 80); draw(player2, 40, 80); draw(ball, 20, 20); // Make stuff happen addEventListener("enterFrame", loop); } /** * Animates and loops the ball * @private loop * @param {Object} e Listener Event * @return null */ private function loop(e) { ball.x += velocity.x; ball.y += velocity.y; player2.x = stage.stageWidth; player1.y = mouseY; player2.y = stage.stageHeight - mouseY; if (ball.y < 10 || ball.y > stage.stageHeight - 10) velocity.y = -velocity.y; if ((ball.hitTestObject(player1) && ball.x > 20) || (ball.hitTestObject(player2) && ball.x < stage.stageWidth - 20)) velocity.x = -velocity.x; if (ball.x < -10 || ball.x > stage.stageWidth + 10) { ball.x = stage.stageWidth * .5; ball.y = stage.stageHeight * .5; velocity.x = -velocity.x; } } /** * Draws squares * @private Draw * @param {MovieClip} t Target MovieClip * @param {Number} w Square width * @param {Number} h Square height * @return Null */ private function draw(t, w, h) { t.graphics.beginFill(0xFFFFFF, 1); t.graphics.drawRect( - w * .5, -h * .5, w, h); t.graphics.endFill(); } } }
yeco/SimplePong
f3ca6fc3a6ceb1161427d9cc5ce9df9de1430591
Fixed minor formatting issues
diff --git a/SimplePong.as b/SimplePong.as index 4bd6d62..81e182b 100644 --- a/SimplePong.as +++ b/SimplePong.as @@ -1,102 +1,102 @@ /** * SimplePong * * Quite simple pong game * * @author Yëco * * */ package { import flash.display.MovieClip; import flash.display.Stage; import flash.display.StageQuality; import flash.display.Sprite; public class SimplePong extends MovieClip { public var velocity = { x: -10, y: 10 }; public var player1 = new Sprite(); public var player2 = new Sprite(); public var ball = new Sprite(); public function SimplePong() { stage.align = "TL"; stage.scaleMode = "noScale"; addChild(player1); addChild(player2); addChild(ball); // drawing the squares draw(player1, 40, 80); draw(player2, 40, 80); draw(ball, 20, 20); // Make stuff happen addEventListener("enterFrame", loop); } /** * Animates and loops the ball * @private loop * @param {Object} e Listener Event * @return null */ private function loop(e) { ball.x += velocity.x; ball.y += velocity.y; player2.x = stage.stageWidth; player1.y = mouseY; player2.y = stage.stageHeight - mouseY; if (ball.y < 10 || ball.y > stage.stageHeight - 10) velocity.y = -velocity.y; if ((ball.hitTestObject(player1) && ball.x > 20) || (ball.hitTestObject(player2) && ball.x < stage.stageWidth - 20)) velocity.x = -velocity.x; if (ball.x < -10 || ball.x > stage.stageWidth + 10) { ball.x = stage.stageWidth * .5; ball.y = stage.stageHeight * .5; velocity.x = -velocity.x; } } /** - * Draws squares - * @private Draw - * @param {MovieClip} t Target MovieClip - * @param {Number} w Square width - * @param {Number} h Square height - * @return Null - */ + * Draws squares + * @private Draw + * @param {MovieClip} t Target MovieClip + * @param {Number} w Square width + * @param {Number} h Square height + * @return Null + */ private function draw(t, w, h) { t.graphics.beginFill(0xFFFFFF, 1); t.graphics.drawRect( - w * .5, -h * .5, w, h); t.graphics.endFill(); } } }
yeco/SimplePong
5460c0e8fe23401fa5ec612174a02872fe392cdd
Fixed minor formatting issues
diff --git a/SimplePong.as b/SimplePong.as index 44b5b30..4bd6d62 100644 --- a/SimplePong.as +++ b/SimplePong.as @@ -1,69 +1,102 @@ -package{ +/** +* SimplePong +* +* Quite simple pong game +* +* @author Yëco +* +* */ + + +package { + import flash.display.MovieClip; import flash.display.Stage; import flash.display.StageQuality; - import flash.display.Sprite; - + import flash.display.Sprite; + public class SimplePong extends MovieClip -{ - public var velocity = {x:-10,y:10}; - public var player1 = new Sprite(); - public var player2 = new Sprite(); - public var ball = new Sprite(); - - public function SimplePong() { - stage.align = "TL"; - stage.scaleMode = "noScale"; + public var velocity = { + x: -10, + y: 10 + }; - addChild(player1); - addChild(player2); + public var player1 = new Sprite(); + public var player2 = new Sprite(); + public var ball = new Sprite(); - addChild(ball); + public function SimplePong() + { + stage.align = "TL"; + stage.scaleMode = "noScale"; - // drawing the squares - draw ( player1, 40, 80); - draw ( player2, 40, 80); - draw ( ball, 20, 20); + addChild(player1); + addChild(player2); + addChild(ball); - addEventListener("enterFrame",loop); - - - } - // magic loop - private function loop(e) - { - ball.x += velocity.x; - ball.y += velocity.y; - player2.x = stage.stageWidth; + // drawing the squares + draw(player1, 40, 80); + draw(player2, 40, 80); + draw(ball, 20, 20); - player1.y = mouseY; - player2.y = stage.stageHeight - mouseY; + // Make stuff happen + addEventListener("enterFrame", loop); - if (ball.y < 10 || ball.y > stage.stageHeight - 10) - velocity.y = -velocity.y; - if ( ( ball.hitTestObject(player1) && ball.x > 20 ) || ( ball.hitTestObject(player2) && ball.x < stage.stageWidth - 20 ) ) - velocity.x = -velocity.x; + } - if (ball.x < -10 || ball.x > stage.stageWidth + 10) - { - ball.x = stage.stageWidth * .5; - ball.y = stage.stageHeight * .5; - velocity.x = -velocity.x; - } - } - // square drawing function - private function draw(t,w,h) - { - t.graphics.beginFill( 0xFFFFFF, 1 ); - t.graphics.drawRect( -w*.5, -h*.5, w, h ); - t.graphics.endFill(); - } + /** + * Animates and loops the ball + * @private loop + * @param {Object} e Listener Event + * @return null + */ -} + private function loop(e) + { + ball.x += velocity.x; + ball.y += velocity.y; + + player2.x = stage.stageWidth; + + player1.y = mouseY; + player2.y = stage.stageHeight - mouseY; + + if (ball.y < 10 || ball.y > stage.stageHeight - 10) + velocity.y = -velocity.y; + + if ((ball.hitTestObject(player1) && ball.x > 20) || (ball.hitTestObject(player2) && ball.x < stage.stageWidth - 20)) + velocity.x = -velocity.x; + + if (ball.x < -10 || ball.x > stage.stageWidth + 10) + { + ball.x = stage.stageWidth * .5; + ball.y = stage.stageHeight * .5; + velocity.x = -velocity.x; + } + } + + + /** + * Draws squares + * @private Draw + * @param {MovieClip} t Target MovieClip + * @param {Number} w Square width + * @param {Number} h Square height + * @return Null + */ + + private function draw(t, w, h) + { + t.graphics.beginFill(0xFFFFFF, 1); + t.graphics.drawRect( - w * .5, -h * .5, w, h); + t.graphics.endFill(); + } + + } }
yeco/SimplePong
802047e4a1e222fc9b7e6e8dc657348f9376856a
adding game code
diff --git a/SimplePong.as b/SimplePong.as new file mode 100644 index 0000000..44b5b30 --- /dev/null +++ b/SimplePong.as @@ -0,0 +1,69 @@ +package{ + import flash.display.MovieClip; + import flash.display.Stage; + import flash.display.StageQuality; + import flash.display.Sprite; + + public class SimplePong extends MovieClip + +{ + public var velocity = {x:-10,y:10}; + public var player1 = new Sprite(); + public var player2 = new Sprite(); + public var ball = new Sprite(); + + public function SimplePong() + { + stage.align = "TL"; + stage.scaleMode = "noScale"; + + addChild(player1); + addChild(player2); + + addChild(ball); + + // drawing the squares + draw ( player1, 40, 80); + draw ( player2, 40, 80); + draw ( ball, 20, 20); + + addEventListener("enterFrame",loop); + + + } + // magic loop + private function loop(e) + { + ball.x += velocity.x; + ball.y += velocity.y; + + player2.x = stage.stageWidth; + + player1.y = mouseY; + player2.y = stage.stageHeight - mouseY; + + if (ball.y < 10 || ball.y > stage.stageHeight - 10) + velocity.y = -velocity.y; + + if ( ( ball.hitTestObject(player1) && ball.x > 20 ) || ( ball.hitTestObject(player2) && ball.x < stage.stageWidth - 20 ) ) + velocity.x = -velocity.x; + + if (ball.x < -10 || ball.x > stage.stageWidth + 10) + { + ball.x = stage.stageWidth * .5; + ball.y = stage.stageHeight * .5; + velocity.x = -velocity.x; + } + } + + // square drawing function + private function draw(t,w,h) + { + t.graphics.beginFill( 0xFFFFFF, 1 ); + t.graphics.drawRect( -w*.5, -h*.5, w, h ); + t.graphics.endFill(); + } + +} + +} diff --git a/SimplePong.fla b/SimplePong.fla new file mode 100644 index 0000000..2e258a3 Binary files /dev/null and b/SimplePong.fla differ diff --git a/SimplePong.swf b/SimplePong.swf new file mode 100644 index 0000000..7a77763 Binary files /dev/null and b/SimplePong.swf differ
toomuchcookies/Python-Geometry
0e0cbd4a9dc613af67b41312f4b9adafc4058c83
added Moritz and last modified
diff --git a/elements.py b/elements.py index 52b4bad..172acad 100644 --- a/elements.py +++ b/elements.py @@ -1,517 +1,518 @@ # -*- coding: utf-8 -*- """ Created: 2011-01-26 -Authors: Omar Abo-Namous, Andreas Poesch +Last Modified: 2011-02-14 +Authors: Omar Abo-Namous, Andreas Poesch, Moritz Krauss """ from math import pi, sqrt, acos, cos, sin import numpy as np import numbers import scipy.linalg as la precision_epsilon = 6 ## precision 10^-(precision_epsilon) is considered zero (e.g. for matching points) class Point: def __init__(self, x, y, z): """ initializing constructor x,y,z -- point coordinates or, respictively, vector subelements """ self.x = float(x) self.y = float(y) self.z = float(z) def abs(self): """ float a = absolute length of vector ||v|| """ return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) def dist(self, other): """ float d = distance self point to other point ||other - self|| other -- another Point """ temp = other - self return temp.abs() def normalized(self): """ Point n = self normalized returns a normalized (length 1.0) vector with same direction as self """ if self.abs() == 0.0: raise ValueError, 'Cannot normalize Null-vector' N = self / self.abs(); return N def cross(self, other): """ Point c = self x other other -- another Point """ return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def dot(self, other): """ float d = self * other other -- another point """ return (self.x*other.x + self.y*other.y + self.z*other.z) def transform(self, T): """ Point t = T * self, T -- transformation matrix (expected to be a 4x4 matrix) """ nx = T[0,0] * self.x + T[0,1] * self.y + T[0,2] * self.z + T[0,3] ny = T[1,0] * self.x + T[1,1] * self.y + T[1,2] * self.z + T[1,3] nz = T[2,0] * self.x + T[2,1] * self.y + T[2,2] * self.z + T[2,3] nh = T[3,0] * self.x + T[3,1] * self.y + T[3,2] * self.z + T[3,3] return Point(nx/nh, ny/nh ,nz/nh) def transformNoTranslation(self, T): """ Point t = T * self, T -- transformation matrix (expected to be a 4x4 matrix) The translation part (4th column vector is omitted) """ nx = T[0,0] * self.x + T[0,1] * self.y + T[0,2] * self.z ny = T[1,0] * self.x + T[1,1] * self.y + T[1,2] * self.z nz = T[2,0] * self.x + T[2,1] * self.y + T[2,2] * self.z return Point(nx, ny ,nz) def near(self, other): """ BOOL return true if self is approximately (global precision setting) other """ if round(self.dist(other), precision_epsilon) == 0.0: return True else: return False def __eq__(self,other): """ BOOL equals true when self == other other -- point to compare with """ if self.x==other.x and self.y==other.y and self.z==other.z: return True else: return False def __ne__(self,other): """ BOOL equals not true when self != other other -- point to compare with """ if self==other: return false else: return true def __sub__(self,other): """ Point difference = self - other other -- point/vector to substract """ return Point(self.x - other.x, self.y - other.y, self.z - other.z) def __add__(self,other): """ Point sum = self + other other -- point/vector to add """ return Point(self.x + other.x, self.y + other.y, self.z + other.z) def __neg__(self): """ Point n = -self inverse of self """ return Point(-self.x, -self.y, -self.z) def __mul__(self, other): """ m = self * other (scale) other -- float/int to multiply with """ if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __rmul__(self, other): """ Point rm = self * other other -- float/int to multiply with """ if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __div__(self, other): """ Point d = self / other other -- float/int to divide by """ if type(other) == float or type(other) == int: return Point(self.x/other, self.y/other, self.z/other) else: raise TypeError, 'The arguments passed must be Numerical' def __gt__(self, other): """ return true if ||self|| > ||other|| """ if isinstance(other, Point): return (self.abs() > other.abs()) elif type(other) == numbers.Real: return (self.abs() > other) def __lt__(self, other): """ return true if ||self|| < ||other|| """ if isinstance(other, Point): return (self.abs() < other.abs()) elif type(other) == numbers.Real: return (self.abs() < other) def __repr__(self): """ Printable output values """ return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" def __getitem__(self, other): """ """ values = {0:self.x,1:self.y,2:self.z} return values.get(other) def aslist(self): """ return elements in a list """ return [self.x, self.y, self.z] def asarray(self): """ return elements as an array """ return np.array([self.x,self.y,self.z]) class Line: def __init__(self, P, vec=Point(0,0,0)): """ initializing constructor P -- either list of two or more points where first element is point contained by line, second element is directional vector vec -- if P is just a single point (not a list of points) then vec shall represent the line's directional vector, defaults to (0,0,0) The normal vector vec is normalized in length """ if type(P) == list and len(P) > 1: if isinstance(P[0],Point) and isinstance(P[1],Point): self.P = P[0] self.vec = P[1] - P[0] else: raise TypeError, 'Line expects a list of two Points or a Point a directional Point' elif isinstance(P,Point) and isinstance(vec, Point) and vec.abs() > 0: self.P = P self.vec = vec else: raise TypeError, 'Line expects a {list of two Points} or {a Point a directional vector}' veclen = float(self.vec.abs()) if (veclen == 0): raise ValueError, 'directional vector is NULL vector' self.vec = self.vec / veclen #normalize directional vector def findnearestPoint(self, to=Point(0.,0.,0.)): """ return point of self (line) that is closest possible to 'to' if point is not on line then the point of line that is closest to point (in eucledian space) is returned to -- point to examine """ P = self.P vec = self.vec u = float(vec.dot(to - P))/float(vec.dot(vec)) return (P + (u*vec)) def dist(self, other): """ distance: line (self) to point (other) """ if isinstance(other,Point): P = self.findnearestPoint(other) return P.dist(other) else: raise TypeError, 'Line.dist expects a Point as parameter' def __repr__(self): """ return printable string of object """ return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" def stretchIntersect(self, P0, P1): """ intersect self (Line) and a line L through P0 and P1 with L = P0 + alpha * (P1 - P0) and return the value of alpha of intersection point or two lines closest points on L and the closest point on self """ A = self.P - P0 B = self.vec C = P1 - P0 print B.cross(C) angle = (B.cross(C)).abs() if round(angle, precision_epsilon) != 0.0: ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) ma = float(ma) mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) mb = float(mb) Pa = self.P + (self.vec * ma) Pb = P0 + (C * mb) return [Pa, Pb, mb] else: return None #lines are parallel: no intersection def lineintersect(self,other): """ calculate point of intersection for two lines intersection is considered valid with an allowance of the global precision parameter returns Pa = point on self that is closest to other Pb = point on other that is closest to self if Pa.near(Pb) --> lines do intersect if lines are parallel: returning None """ A = self.P-other.P B = self.vec C = other.vec # Check for parallel lines cp12 = B.cross(C) absCp12 = cp12.abs() if round(absCp12, precision_epsilon) != 0.0: ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) ma = float(ma) mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) mb = float(mb) Pa = self.P + (self.vec * ma) Pb = other.P + (other.vec * mb) return [Pa, Pb] else: return None def intersect(self, other): """ intersect with line or plane the appropriate fn is sub-called """ if isinstance(other,Plane): return other.lineintersect(self) elif isinstance(other,Line): return self.lineintersect(other) else: return None def rotatearound(self,points,theta): """ rotate points around self with the angle theta Assume points is a Point or a list of Points """ theta = pi*theta/180 if isinstance(points,Point): points = [points] # Translate so axis is at origin for i in range(len(points)): points[i] = points[i] - self.P # Matrix common factors c = cos(theta) t = (1 - cos(theta)) s = sin(theta) X = self.vec.x Y = self.vec.y Z = self.vec.z # Matrix 'M' d11 = t*X**2 + c d12 = t*X*Y - s*Z d13 = t*X*Z + s*Y d21 = t*X*Y + s*Z d22 = t*Y**2 + c d23 = t*Y*Z - s*X d31 = t*X*Z - s*Y d32 = t*Y*Z + s*X d33 = t*Z**2 + c # |p.x| # Matrix 'M'*|p.y| # |p.z| rpoints = [] for i in range(len(points)): nx = d11*points[i].x + d12*points[i].y + d13*points[i].z ny = d21*points[i].x + d22*points[i].y + d23*points[i].z nz = d31*points[i].x + d32*points[i].y + d33*points[i].z rpoints.append(Point(nx,ny,nz)+self.P) return rpoints def transform(self, T): """ Line t = T * self, T -- transformation matrix (expected to be a 4x4 matrix) The Point self.P is transformed normally, the directional vector self.vec is rotated and finally normalized but NOT moved """ self.P = self.P.transform(T) self.vect = self.vect.transformNoTranslation(T).normalized() return Point(t[0,0],t[1,0],t[2,0]) class Plane: def __init__(self, P=Point(0,0,0), P2=None, P3=None, D=0): """ initializing constructor plane can be defined from: -- three points in space: list P with at least 3 points (first three taken) or three points P, P2, P3 -- list P of ints/reald numbers (= normal vector coords) and distance D -- P as normal vector with D as distance from origin """ if type(P) == list and len(P) > 2: # P == list print 'plane from list' if isinstance(P[0], Point): #list of points --> fromPoints self.fromPoints(P[0], P[1], P[2]) elif type(other) == float or type(other) == int: #list of numbers --> fromND self.fromND(Point(P[0], P[1], P[2]), D) else: raise TypeError, 'Invalid parameter list to Plane constructor' elif isinstance(P,Point) and P2 == None: #normalvector as Point and D #print 'plane from nd' self.fromND(P, D) elif isinstance(P, Point) and isinstance(P2, Point) and isinstance(P3, Point): #print 'plane points' self.fromPoints(P, P2, P3) #three points, D irrelevant elif isinstance(P, Point) and isinstance(P2, Point): #print 'plane pn' self.fromPointNorm(P, P2) elif isinstance(P, Point) and isinstance(P2, Line): #print 'plane pl' self.fromPointLine(P, P2) else: raise TypeError, 'unknown initializers' def __repr__(self): """ string representing plane in readable version """ return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" def fromPoints(self, p1, p2, p3): """ describing parameters = define plane by three points p1, p2, p3 p1, p2, p3 -- each one points in 3-space representing a point from plane collinear points will raise an error as the plane would not be defined disambigously """ if isinstance(p1, Point) and isinstance(p2, Point) and isinstance(p3, Point): N = (p2-p1).cross(p3-p1) N = N.normalized() #will throw an error if points are collinear D = (-N).dot(p1) self.N = N self.D = D else: raise TypeError, 'Plane.fromPoints expects three points as params' def fromND(self, Norm, Dist = 0): """ load plane from normal vector (will be normalized) and distance to origin """ if not isinstance(Norm, Point): raise TypeError, 'Plane.fromND expects normal vector as of type Point' self.N = Norm.normalized() self.D = Dist def fromPointNorm(self, P, Norm): """ define plane by a contained point and the normal direction """ if Norm.abs() == 0: raise ValueError, 'Plane normal must not be a null-vector' self.N = Norm.normalized() self.D = (-self.N).dot(P) def fromPointLine(self, P, L): """ define plane by a contained point and the normal direction """ vect2 = P - L.P #the second directional vector is from point to line.pos norm = vect2.cross(L.vec) self.fromPointNorm(P, norm) def dist(self, other): """ float dist = distance from self(plane) to other (point) """ if isinstance(other, Point): #return float (self.N.dot(other - self.D*self.N)/self.N.abs()) return float (self.N.dot(other - self.D*self.N)) #n is already normalized, so self.N.abs === 1.0 else: raise TypeError ,'can only calculate distance from Plane to Point' return None def transform(self, T, pivot = Point(0,0,0)): """ transform plane by some transformation matrix the normalvector will be kept normalized/renormalized under all circumstances (except invalid T) the pivot point (e.g. for fixed-point for rotation) can be specified and defaults to the origin of the coordinate system """ if not isinstance (pivot, Point): raise TypeError, 'Pivot point must be a point' pointOnSelf = self.N * self.D origin = pointOnSelf - pivot origin = origin.transformed(T) pointOnSelf = origin + pivot norm = self.N.transformNoTranslation(T).normalized() self.fromPointNorm(pointOnSelf, norm) def planeintersect(self, other): """ returns line of intersection of this plane and another None is returned if planes are parallel 20110207 NEW VERSION: M. Krauss """ N1 = self.N N2 = other.N D1 = self.D D2 = other.D if (N1.cross(N2)).abs() == 0: # Planes are parallel return None else: v = N1.cross(N2) b = np.array([[D1],[D2]]) p = Point(0,0,0) try: # intersection with the plane x=0 A = np.array([[N1.y , N1.z],[N2.y , N2.z]]) x = la.solve(A,b) p = Point(0,x[0],x[1]) return Line(p, v) except: try: # intersection with the plane y=0 A = np.array([[N1.x , N1.z],[N2.x , N2.z]]) x = la.solve(A,b) p = Point(x[0],0,x[1]) return Line(p, v) except:
toomuchcookies/Python-Geometry
2eba716b45fd143d910eb565a07be01c3e625f3e
rotatearound axis
diff --git a/elements.py b/elements.py index d9b6190..52b4bad 100644 --- a/elements.py +++ b/elements.py @@ -1,559 +1,594 @@ # -*- coding: utf-8 -*- """ Created: 2011-01-26 Authors: Omar Abo-Namous, Andreas Poesch """ from math import pi, sqrt, acos, cos, sin import numpy as np import numbers import scipy.linalg as la precision_epsilon = 6 ## precision 10^-(precision_epsilon) is considered zero (e.g. for matching points) class Point: def __init__(self, x, y, z): """ initializing constructor x,y,z -- point coordinates or, respictively, vector subelements """ self.x = float(x) self.y = float(y) self.z = float(z) def abs(self): """ float a = absolute length of vector ||v|| """ return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) def dist(self, other): """ float d = distance self point to other point ||other - self|| other -- another Point """ temp = other - self return temp.abs() def normalized(self): """ Point n = self normalized returns a normalized (length 1.0) vector with same direction as self """ if self.abs() == 0.0: raise ValueError, 'Cannot normalize Null-vector' N = self / self.abs(); return N def cross(self, other): """ Point c = self x other other -- another Point """ return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def dot(self, other): """ float d = self * other other -- another point """ return (self.x*other.x + self.y*other.y + self.z*other.z) def transform(self, T): """ Point t = T * self, T -- transformation matrix (expected to be a 4x4 matrix) """ nx = T[0,0] * self.x + T[0,1] * self.y + T[0,2] * self.z + T[0,3] ny = T[1,0] * self.x + T[1,1] * self.y + T[1,2] * self.z + T[1,3] nz = T[2,0] * self.x + T[2,1] * self.y + T[2,2] * self.z + T[2,3] nh = T[3,0] * self.x + T[3,1] * self.y + T[3,2] * self.z + T[3,3] return Point(nx/nh, ny/nh ,nz/nh) def transformNoTranslation(self, T): """ Point t = T * self, T -- transformation matrix (expected to be a 4x4 matrix) The translation part (4th column vector is omitted) """ nx = T[0,0] * self.x + T[0,1] * self.y + T[0,2] * self.z ny = T[1,0] * self.x + T[1,1] * self.y + T[1,2] * self.z nz = T[2,0] * self.x + T[2,1] * self.y + T[2,2] * self.z return Point(nx, ny ,nz) def near(self, other): """ BOOL return true if self is approximately (global precision setting) other """ if round(self.dist(other), precision_epsilon) == 0.0: return True else: return False def __eq__(self,other): """ BOOL equals true when self == other other -- point to compare with """ if self.x==other.x and self.y==other.y and self.z==other.z: return True else: return False def __ne__(self,other): """ BOOL equals not true when self != other other -- point to compare with """ if self==other: return false else: return true def __sub__(self,other): """ Point difference = self - other other -- point/vector to substract """ return Point(self.x - other.x, self.y - other.y, self.z - other.z) def __add__(self,other): """ Point sum = self + other other -- point/vector to add """ return Point(self.x + other.x, self.y + other.y, self.z + other.z) def __neg__(self): """ Point n = -self inverse of self """ return Point(-self.x, -self.y, -self.z) def __mul__(self, other): """ m = self * other (scale) other -- float/int to multiply with """ if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __rmul__(self, other): """ Point rm = self * other other -- float/int to multiply with """ if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __div__(self, other): """ Point d = self / other other -- float/int to divide by """ if type(other) == float or type(other) == int: return Point(self.x/other, self.y/other, self.z/other) else: raise TypeError, 'The arguments passed must be Numerical' def __gt__(self, other): """ return true if ||self|| > ||other|| """ if isinstance(other, Point): return (self.abs() > other.abs()) elif type(other) == numbers.Real: return (self.abs() > other) def __lt__(self, other): """ return true if ||self|| < ||other|| """ if isinstance(other, Point): return (self.abs() < other.abs()) elif type(other) == numbers.Real: return (self.abs() < other) def __repr__(self): """ Printable output values """ return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" def __getitem__(self, other): """ """ values = {0:self.x,1:self.y,2:self.z} return values.get(other) def aslist(self): """ return elements in a list """ return [self.x, self.y, self.z] def asarray(self): """ return elements as an array """ return np.array([self.x,self.y,self.z]) class Line: def __init__(self, P, vec=Point(0,0,0)): """ initializing constructor P -- either list of two or more points where first element is point contained by line, second element is directional vector vec -- if P is just a single point (not a list of points) then vec shall represent the line's directional vector, defaults to (0,0,0) The normal vector vec is normalized in length """ if type(P) == list and len(P) > 1: if isinstance(P[0],Point) and isinstance(P[1],Point): self.P = P[0] self.vec = P[1] - P[0] else: raise TypeError, 'Line expects a list of two Points or a Point a directional Point' elif isinstance(P,Point) and isinstance(vec, Point) and vec.abs() > 0: self.P = P self.vec = vec else: raise TypeError, 'Line expects a {list of two Points} or {a Point a directional vector}' veclen = float(self.vec.abs()) if (veclen == 0): raise ValueError, 'directional vector is NULL vector' self.vec = self.vec / veclen #normalize directional vector def findnearestPoint(self, to=Point(0.,0.,0.)): """ return point of self (line) that is closest possible to 'to' if point is not on line then the point of line that is closest to point (in eucledian space) is returned to -- point to examine """ P = self.P vec = self.vec u = float(vec.dot(to - P))/float(vec.dot(vec)) return (P + (u*vec)) def dist(self, other): """ distance: line (self) to point (other) """ if isinstance(other,Point): P = self.findnearestPoint(other) return P.dist(other) else: raise TypeError, 'Line.dist expects a Point as parameter' def __repr__(self): """ return printable string of object """ return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" def stretchIntersect(self, P0, P1): """ intersect self (Line) and a line L through P0 and P1 with L = P0 + alpha * (P1 - P0) and return the value of alpha of intersection point or two lines closest points on L and the closest point on self """ A = self.P - P0 B = self.vec C = P1 - P0 print B.cross(C) angle = (B.cross(C)).abs() if round(angle, precision_epsilon) != 0.0: ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) ma = float(ma) mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) mb = float(mb) Pa = self.P + (self.vec * ma) Pb = P0 + (C * mb) return [Pa, Pb, mb] else: return None #lines are parallel: no intersection def lineintersect(self,other): """ calculate point of intersection for two lines intersection is considered valid with an allowance of the global precision parameter returns Pa = point on self that is closest to other Pb = point on other that is closest to self if Pa.near(Pb) --> lines do intersect if lines are parallel: returning None """ A = self.P-other.P B = self.vec C = other.vec # Check for parallel lines cp12 = B.cross(C) absCp12 = cp12.abs() if round(absCp12, precision_epsilon) != 0.0: ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) ma = float(ma) mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) mb = float(mb) Pa = self.P + (self.vec * ma) Pb = other.P + (other.vec * mb) return [Pa, Pb] else: return None def intersect(self, other): """ intersect with line or plane the appropriate fn is sub-called """ if isinstance(other,Plane): return other.lineintersect(self) elif isinstance(other,Line): return self.lineintersect(other) else: return None + + def rotatearound(self,points,theta): + """ rotate points around self with the angle theta + + Assume points is a Point or a list of Points + """ + theta = pi*theta/180 + if isinstance(points,Point): + points = [points] + # Translate so axis is at origin + for i in range(len(points)): + points[i] = points[i] - self.P + # Matrix common factors + c = cos(theta) + t = (1 - cos(theta)) + s = sin(theta) + X = self.vec.x + Y = self.vec.y + Z = self.vec.z + # Matrix 'M' + d11 = t*X**2 + c + d12 = t*X*Y - s*Z + d13 = t*X*Z + s*Y + d21 = t*X*Y + s*Z + d22 = t*Y**2 + c + d23 = t*Y*Z - s*X + d31 = t*X*Z - s*Y + d32 = t*Y*Z + s*X + d33 = t*Z**2 + c + + # |p.x| + # Matrix 'M'*|p.y| + # |p.z| + rpoints = [] + for i in range(len(points)): + nx = d11*points[i].x + d12*points[i].y + d13*points[i].z + ny = d21*points[i].x + d22*points[i].y + d23*points[i].z + nz = d31*points[i].x + d32*points[i].y + d33*points[i].z + rpoints.append(Point(nx,ny,nz)+self.P) + return rpoints def transform(self, T): """ Line t = T * self, T -- transformation matrix (expected to be a 4x4 matrix) The Point self.P is transformed normally, the directional vector self.vec is rotated and finally normalized but NOT moved """ self.P = self.P.transform(T) self.vect = self.vect.transformNoTranslation(T).normalized() return Point(t[0,0],t[1,0],t[2,0]) class Plane: def __init__(self, P=Point(0,0,0), P2=None, P3=None, D=0): """ initializing constructor plane can be defined from: -- three points in space: list P with at least 3 points (first three taken) or three points P, P2, P3 -- list P of ints/reald numbers (= normal vector coords) and distance D -- P as normal vector with D as distance from origin """ if type(P) == list and len(P) > 2: # P == list print 'plane from list' if isinstance(P[0], Point): #list of points --> fromPoints self.fromPoints(P[0], P[1], P[2]) elif type(other) == float or type(other) == int: #list of numbers --> fromND self.fromND(Point(P[0], P[1], P[2]), D) else: raise TypeError, 'Invalid parameter list to Plane constructor' elif isinstance(P,Point) and P2 == None: #normalvector as Point and D #print 'plane from nd' self.fromND(P, D) elif isinstance(P, Point) and isinstance(P2, Point) and isinstance(P3, Point): #print 'plane points' self.fromPoints(P, P2, P3) #three points, D irrelevant elif isinstance(P, Point) and isinstance(P2, Point): #print 'plane pn' self.fromPointNorm(P, P2) elif isinstance(P, Point) and isinstance(P2, Line): #print 'plane pl' self.fromPointLine(P, P2) else: raise TypeError, 'unknown initializers' def __repr__(self): """ string representing plane in readable version """ return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" def fromPoints(self, p1, p2, p3): """ describing parameters = define plane by three points p1, p2, p3 p1, p2, p3 -- each one points in 3-space representing a point from plane collinear points will raise an error as the plane would not be defined disambigously """ if isinstance(p1, Point) and isinstance(p2, Point) and isinstance(p3, Point): N = (p2-p1).cross(p3-p1) N = N.normalized() #will throw an error if points are collinear D = (-N).dot(p1) self.N = N self.D = D else: raise TypeError, 'Plane.fromPoints expects three points as params' def fromND(self, Norm, Dist = 0): """ load plane from normal vector (will be normalized) and distance to origin """ if not isinstance(Norm, Point): raise TypeError, 'Plane.fromND expects normal vector as of type Point' self.N = Norm.normalized() self.D = Dist def fromPointNorm(self, P, Norm): """ define plane by a contained point and the normal direction """ if Norm.abs() == 0: raise ValueError, 'Plane normal must not be a null-vector' self.N = Norm.normalized() self.D = (-self.N).dot(P) def fromPointLine(self, P, L): """ define plane by a contained point and the normal direction """ vect2 = P - L.P #the second directional vector is from point to line.pos norm = vect2.cross(L.vec) self.fromPointNorm(P, norm) def dist(self, other): """ float dist = distance from self(plane) to other (point) """ if isinstance(other, Point): #return float (self.N.dot(other - self.D*self.N)/self.N.abs()) return float (self.N.dot(other - self.D*self.N)) #n is already normalized, so self.N.abs === 1.0 else: raise TypeError ,'can only calculate distance from Plane to Point' return None def transform(self, T, pivot = Point(0,0,0)): """ transform plane by some transformation matrix the normalvector will be kept normalized/renormalized under all circumstances (except invalid T) the pivot point (e.g. for fixed-point for rotation) can be specified and defaults to the origin of the coordinate system """ if not isinstance (pivot, Point): raise TypeError, 'Pivot point must be a point' pointOnSelf = self.N * self.D origin = pointOnSelf - pivot origin = origin.transformed(T) pointOnSelf = origin + pivot norm = self.N.transformNoTranslation(T).normalized() self.fromPointNorm(pointOnSelf, norm) - - def planeintersect(self, other): """ returns line of intersection of this plane and another None is returned if planes are parallel 20110207 NEW VERSION: M. Krauss """ N1 = self.N N2 = other.N D1 = self.D D2 = other.D if (N1.cross(N2)).abs() == 0: # Planes are parallel return None else: v = N1.cross(N2) b = np.array([[D1],[D2]]) p = Point(0,0,0) try: # intersection with the plane x=0 A = np.array([[N1.y , N1.z],[N2.y , N2.z]]) x = la.solve(A,b) p = Point(0,x[0],x[1]) return Line(p, v) except: try: # intersection with the plane y=0 A = np.array([[N1.x , N1.z],[N2.x , N2.z]]) x = la.solve(A,b) p = Point(x[0],0,x[1]) return Line(p, v) except: # intersection with the plane z=0 A = np.array([[N1.x , N1.y],[N2.x , N2.y]]) x = la.solve(A,b) p = Point(x[0],x[1],0) return Line(p, v) - - - def lineintersect(self,other): """ Point p = intersection of self (Plane) and other (Line) """ N = self.N D = self.D P = other.P vec = other.vec u1 = float(N.dot(D*N - P)) u2 = float(N.dot(vec)) #print u1,u2 u = u1 / u2 return P + u * vec def intersect(self, other): """ pseudo-overloaded intersection fn for planes and lines, will call appropriate members planeintersect/lineintersect """ if isinstance(other,Plane): return self.planeintersect(other) elif isinstance(other,Line): return self.lineintersect(other) else: return None def projection(self, other): """ Point X = projection of Point other to plane = closest point to other on self = intersection of line through other and perpendicular to self with self """ if isinstance(other,Point): return self.lineintersect(Line(other,vec=self.N)) else: raise TypeError, 'can only project Points' return None def getpoints(self, x_range, y_range): """ get some points lying on plane """ a = self.N[0] b = self.N[1] c = self.N[2] d = self.D xs = np.arange(x_range[0],x_range[1],(x_range[1]-x_range[0])/2) ys = np.arange(y_range[0],y_range[1],(y_range[1]-y_range[0])/2) xP = np.zeros((len(xs),len(ys)), dtype=float) yP = np.zeros((len(xs),len(ys)), dtype=float) zP = np.zeros((len(xs),len(ys)), dtype=float) for x in range(len(xs)): for y in range(len(ys)): xP[x,y] = xs[x] yP[x,y] = ys[y] zP[x,y] = (-a*xs[x]-b*ys[y]-d)/c return xP,yP,zP def getcoordinatesystem(self): """ return axis unit vectors for plane coordinate system where z1 is normal vector """ ZeroPoint = float(self.D) * self.N z1 = self.N x1Point = self.projection(Point(1,0,0)) if x1Point == Point(0,0,0): x1Point = self.projection(Point(0,1,0)) x1 = x1Point - ZeroPoint x1 = x1 / x1.abs() y1 = z1.cross(x1) return [ZeroPoint,x1,y1,z1] if __name__ == '__main__': p1 = Point(1,1,0) A = np.array([[2., 0, 0, 0], [0,1, 0, 0], [0, 0, 6, -5], [0,0,0,1]]) p2 = p1.transform(A) - \ No newline at end of file +
toomuchcookies/Python-Geometry
f58919bc72d4ce3bbceb249816b7853dac48303c
Version ?
diff --git a/elements.py b/elements.py new file mode 100644 index 0000000..d9b6190 --- /dev/null +++ b/elements.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- + +""" +Created: 2011-01-26 +Authors: Omar Abo-Namous, Andreas Poesch +""" + + +from math import pi, sqrt, acos, cos, sin +import numpy as np +import numbers +import scipy.linalg as la + +precision_epsilon = 6 ## precision 10^-(precision_epsilon) is considered zero (e.g. for matching points) + +class Point: + def __init__(self, x, y, z): + """ initializing constructor + x,y,z -- point coordinates or, respictively, vector subelements + """ + self.x = float(x) + self.y = float(y) + self.z = float(z) + + def abs(self): + """ float a = absolute length of vector ||v|| + + """ + return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) + + def dist(self, other): + """ float d = distance self point to other point ||other - self|| + + other -- another Point + """ + temp = other - self + return temp.abs() + + def normalized(self): + """ Point n = self normalized + + returns a normalized (length 1.0) vector with same direction as self + """ + if self.abs() == 0.0: + raise ValueError, 'Cannot normalize Null-vector' + + N = self / self.abs(); + return N + + + def cross(self, other): + """ Point c = self x other + + other -- another Point + """ + return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) + + def dot(self, other): + """ float d = self * other + + other -- another point + """ + return (self.x*other.x + self.y*other.y + self.z*other.z) + + def transform(self, T): + """ Point t = T * self, + + T -- transformation matrix (expected to be a 4x4 matrix) + """ + nx = T[0,0] * self.x + T[0,1] * self.y + T[0,2] * self.z + T[0,3] + ny = T[1,0] * self.x + T[1,1] * self.y + T[1,2] * self.z + T[1,3] + nz = T[2,0] * self.x + T[2,1] * self.y + T[2,2] * self.z + T[2,3] + nh = T[3,0] * self.x + T[3,1] * self.y + T[3,2] * self.z + T[3,3] + + return Point(nx/nh, ny/nh ,nz/nh) + + def transformNoTranslation(self, T): + """ Point t = T * self, + + T -- transformation matrix (expected to be a 4x4 matrix) + + The translation part (4th column vector is omitted) + """ + nx = T[0,0] * self.x + T[0,1] * self.y + T[0,2] * self.z + ny = T[1,0] * self.x + T[1,1] * self.y + T[1,2] * self.z + nz = T[2,0] * self.x + T[2,1] * self.y + T[2,2] * self.z + + return Point(nx, ny ,nz) + + def near(self, other): + """ BOOL return true if self is approximately (global precision setting) other + """ + if round(self.dist(other), precision_epsilon) == 0.0: + return True + else: + return False + + def __eq__(self,other): + """ BOOL equals + true when self == other + + other -- point to compare with + """ + if self.x==other.x and self.y==other.y and self.z==other.z: + return True + else: + return False + + def __ne__(self,other): + """ BOOL equals not + true when self != other + + other -- point to compare with + """ + if self==other: + return false + else: + return true + + def __sub__(self,other): + """ Point difference = self - other + + other -- point/vector to substract + """ + return Point(self.x - other.x, self.y - other.y, self.z - other.z) + + def __add__(self,other): + """ Point sum = self + other + + other -- point/vector to add + """ + return Point(self.x + other.x, self.y + other.y, self.z + other.z) + + def __neg__(self): + """ Point n = -self + inverse of self + """ + return Point(-self.x, -self.y, -self.z) + + def __mul__(self, other): + """ m = self * other (scale) + + other -- float/int to multiply with + """ + if type(other) == float or type(other) == int: + return Point(self.x * other, self.y * other, self.z * other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __rmul__(self, other): + """ Point rm = self * other + + other -- float/int to multiply with + """ + if type(other) == float or type(other) == int: + return Point(self.x * other, self.y * other, self.z * other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __div__(self, other): + """ Point d = self / other + + other -- float/int to divide by + """ + if type(other) == float or type(other) == int: + return Point(self.x/other, self.y/other, self.z/other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __gt__(self, other): + """ return true if ||self|| > ||other|| + """ + if isinstance(other, Point): + return (self.abs() > other.abs()) + elif type(other) == numbers.Real: + return (self.abs() > other) + + def __lt__(self, other): + """ return true if ||self|| < ||other|| + """ + if isinstance(other, Point): + return (self.abs() < other.abs()) + elif type(other) == numbers.Real: + return (self.abs() < other) + + def __repr__(self): + """ Printable output values + """ + return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" + + def __getitem__(self, other): + """ + + """ + values = {0:self.x,1:self.y,2:self.z} + return values.get(other) + + def aslist(self): + """ return elements in a list + """ + return [self.x, self.y, self.z] + + def asarray(self): + """ return elements as an array + """ + return np.array([self.x,self.y,self.z]) + + +class Line: + def __init__(self, P, vec=Point(0,0,0)): + """ initializing constructor + + P -- either list of two or more points where first element is point contained by line, second element is directional vector + vec -- if P is just a single point (not a list of points) then vec shall represent the line's directional vector, defaults to (0,0,0) + + The normal vector vec is normalized in length + """ + if type(P) == list and len(P) > 1: + if isinstance(P[0],Point) and isinstance(P[1],Point): + self.P = P[0] + self.vec = P[1] - P[0] + else: + raise TypeError, 'Line expects a list of two Points or a Point a directional Point' + elif isinstance(P,Point) and isinstance(vec, Point) and vec.abs() > 0: + self.P = P + self.vec = vec + else: + raise TypeError, 'Line expects a {list of two Points} or {a Point a directional vector}' + + veclen = float(self.vec.abs()) + if (veclen == 0): + raise ValueError, 'directional vector is NULL vector' + self.vec = self.vec / veclen #normalize directional vector + + def findnearestPoint(self, to=Point(0.,0.,0.)): + """ return point of self (line) that is closest possible to 'to' + if point is not on line then the point of line that is closest to point (in eucledian space) is returned + + to -- point to examine + """ + P = self.P + vec = self.vec + u = float(vec.dot(to - P))/float(vec.dot(vec)) + return (P + (u*vec)) + + def dist(self, other): + """ distance: line (self) to point (other) + """ + if isinstance(other,Point): + P = self.findnearestPoint(other) + return P.dist(other) + else: + raise TypeError, 'Line.dist expects a Point as parameter' + + def __repr__(self): + """ return printable string of object + """ + return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" + + def stretchIntersect(self, P0, P1): + """ intersect self (Line) and a line L through P0 and P1 + with L = P0 + alpha * (P1 - P0) and return the + value of alpha of intersection point or two lines closest points on L + and the closest point on self + + """ + A = self.P - P0 + B = self.vec + C = P1 - P0 + + print B.cross(C) + angle = (B.cross(C)).abs() + + if round(angle, precision_epsilon) != 0.0: + ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ + ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) + ma = float(ma) + mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) + mb = float(mb) + Pa = self.P + (self.vec * ma) + Pb = P0 + (C * mb) + return [Pa, Pb, mb] + else: + return None #lines are parallel: no intersection + + + + def lineintersect(self,other): + """ calculate point of intersection for two lines + intersection is considered valid with an allowance of the global precision parameter + + returns Pa = point on self that is closest to other + Pb = point on other that is closest to self + + if Pa.near(Pb) --> lines do intersect + + if lines are parallel: returning None + """ + A = self.P-other.P + B = self.vec + C = other.vec + # Check for parallel lines + cp12 = B.cross(C) + absCp12 = cp12.abs() + if round(absCp12, precision_epsilon) != 0.0: + ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ + ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) + ma = float(ma) + mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) + mb = float(mb) + Pa = self.P + (self.vec * ma) + Pb = other.P + (other.vec * mb) + return [Pa, Pb] + else: + return None + + def intersect(self, other): + """ intersect with line or plane + the appropriate fn is sub-called + """ + if isinstance(other,Plane): + return other.lineintersect(self) + elif isinstance(other,Line): + return self.lineintersect(other) + else: + return None + + def transform(self, T): + """ Line t = T * self, + + T -- transformation matrix (expected to be a 4x4 matrix) + The Point self.P is transformed normally, the + directional vector self.vec is rotated and finally normalized + but NOT moved + """ + self.P = self.P.transform(T) + self.vect = self.vect.transformNoTranslation(T).normalized() + return Point(t[0,0],t[1,0],t[2,0]) + +class Plane: + def __init__(self, P=Point(0,0,0), P2=None, P3=None, D=0): + """ initializing constructor + + plane can be defined from: + -- three points in space: list P with at least 3 points (first three taken) or three points P, P2, P3 + -- list P of ints/reald numbers (= normal vector coords) and distance D + -- P as normal vector with D as distance from origin + """ + if type(P) == list and len(P) > 2: # P == list + print 'plane from list' + if isinstance(P[0], Point): #list of points --> fromPoints + self.fromPoints(P[0], P[1], P[2]) + elif type(other) == float or type(other) == int: #list of numbers --> fromND + self.fromND(Point(P[0], P[1], P[2]), D) + else: + raise TypeError, 'Invalid parameter list to Plane constructor' + elif isinstance(P,Point) and P2 == None: #normalvector as Point and D + #print 'plane from nd' + self.fromND(P, D) + elif isinstance(P, Point) and isinstance(P2, Point) and isinstance(P3, Point): + #print 'plane points' + self.fromPoints(P, P2, P3) #three points, D irrelevant + elif isinstance(P, Point) and isinstance(P2, Point): + #print 'plane pn' + self.fromPointNorm(P, P2) + elif isinstance(P, Point) and isinstance(P2, Line): + #print 'plane pl' + self.fromPointLine(P, P2) + else: + raise TypeError, 'unknown initializers' + + def __repr__(self): + """ string representing plane in readable version + """ + return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" + + def fromPoints(self, p1, p2, p3): + """ describing parameters = define plane by three points p1, p2, p3 + + p1, p2, p3 -- each one points in 3-space representing a point from plane + collinear points will raise an error as the plane would not be defined disambigously + """ + if isinstance(p1, Point) and isinstance(p2, Point) and isinstance(p3, Point): + N = (p2-p1).cross(p3-p1) + N = N.normalized() #will throw an error if points are collinear + D = (-N).dot(p1) + self.N = N + self.D = D + else: + raise TypeError, 'Plane.fromPoints expects three points as params' + + def fromND(self, Norm, Dist = 0): + """ load plane from normal vector (will be normalized) and distance to origin + """ + if not isinstance(Norm, Point): + raise TypeError, 'Plane.fromND expects normal vector as of type Point' + self.N = Norm.normalized() + self.D = Dist + + def fromPointNorm(self, P, Norm): + """ define plane by a contained point and the normal direction + """ + if Norm.abs() == 0: + raise ValueError, 'Plane normal must not be a null-vector' + self.N = Norm.normalized() + self.D = (-self.N).dot(P) + + def fromPointLine(self, P, L): + """ define plane by a contained point and the normal direction + """ + vect2 = P - L.P #the second directional vector is from point to line.pos + norm = vect2.cross(L.vec) + + self.fromPointNorm(P, norm) + + def dist(self, other): + """ float dist = distance from self(plane) to other (point) + + """ + if isinstance(other, Point): + #return float (self.N.dot(other - self.D*self.N)/self.N.abs()) + return float (self.N.dot(other - self.D*self.N)) #n is already normalized, so self.N.abs === 1.0 + else: + raise TypeError ,'can only calculate distance from Plane to Point' + return None + + def transform(self, T, pivot = Point(0,0,0)): + """ transform plane by some transformation matrix + + the normalvector will be kept normalized/renormalized under all + circumstances (except invalid T) + + the pivot point (e.g. for fixed-point for rotation) can be specified and + defaults to the origin of the coordinate system + """ + if not isinstance (pivot, Point): + raise TypeError, 'Pivot point must be a point' + + pointOnSelf = self.N * self.D + origin = pointOnSelf - pivot + origin = origin.transformed(T) + pointOnSelf = origin + pivot + + norm = self.N.transformNoTranslation(T).normalized() + + self.fromPointNorm(pointOnSelf, norm) + + + + def planeintersect(self, other): + """ returns line of intersection of this plane and another + None is returned if planes are parallel + 20110207 NEW VERSION: M. Krauss + """ + N1 = self.N + N2 = other.N + D1 = self.D + D2 = other.D + if (N1.cross(N2)).abs() == 0: + # Planes are parallel + return None + else: + v = N1.cross(N2) + b = np.array([[D1],[D2]]) + p = Point(0,0,0) + try: + # intersection with the plane x=0 + A = np.array([[N1.y , N1.z],[N2.y , N2.z]]) + x = la.solve(A,b) + p = Point(0,x[0],x[1]) + return Line(p, v) + except: + try: + # intersection with the plane y=0 + A = np.array([[N1.x , N1.z],[N2.x , N2.z]]) + x = la.solve(A,b) + p = Point(x[0],0,x[1]) + return Line(p, v) + except: + # intersection with the plane z=0 + A = np.array([[N1.x , N1.y],[N2.x , N2.y]]) + x = la.solve(A,b) + p = Point(x[0],x[1],0) + return Line(p, v) + + + + + def lineintersect(self,other): + """ Point p = intersection of self (Plane) and other (Line) + """ + N = self.N + D = self.D + P = other.P + vec = other.vec + u1 = float(N.dot(D*N - P)) + u2 = float(N.dot(vec)) + #print u1,u2 + u = u1 / u2 + return P + u * vec + + def intersect(self, other): + """ pseudo-overloaded intersection fn for planes and lines, will call appropriate members planeintersect/lineintersect + """ + if isinstance(other,Plane): + return self.planeintersect(other) + elif isinstance(other,Line): + return self.lineintersect(other) + else: + return None + + def projection(self, other): + """ Point X = projection of Point other to plane = closest point to other on self = intersection of line through other and perpendicular to self with self + """ + if isinstance(other,Point): + return self.lineintersect(Line(other,vec=self.N)) + else: + raise TypeError, 'can only project Points' + return None + + def getpoints(self, x_range, y_range): + """ get some points lying on plane + """ + a = self.N[0] + b = self.N[1] + c = self.N[2] + d = self.D + xs = np.arange(x_range[0],x_range[1],(x_range[1]-x_range[0])/2) + ys = np.arange(y_range[0],y_range[1],(y_range[1]-y_range[0])/2) + xP = np.zeros((len(xs),len(ys)), dtype=float) + yP = np.zeros((len(xs),len(ys)), dtype=float) + zP = np.zeros((len(xs),len(ys)), dtype=float) + for x in range(len(xs)): + for y in range(len(ys)): + xP[x,y] = xs[x] + yP[x,y] = ys[y] + zP[x,y] = (-a*xs[x]-b*ys[y]-d)/c + return xP,yP,zP + + def getcoordinatesystem(self): + """ return axis unit vectors for plane coordinate system where z1 is normal vector + + """ + ZeroPoint = float(self.D) * self.N + z1 = self.N + x1Point = self.projection(Point(1,0,0)) + if x1Point == Point(0,0,0): + x1Point = self.projection(Point(0,1,0)) + x1 = x1Point - ZeroPoint + x1 = x1 / x1.abs() + y1 = z1.cross(x1) + return [ZeroPoint,x1,y1,z1] + +if __name__ == '__main__': + p1 = Point(1,1,0) + A = np.array([[2., 0, 0, 0], [0,1, 0, 0], [0, 0, 6, -5], [0,0,0,1]]) + p2 = p1.transform(A) + + \ No newline at end of file
toomuchcookies/Python-Geometry
dc4cd97d5c6b9a3951bd370bc695bf8f2ba09d28
More functions, and some formating.
diff --git a/elements.py b/elements.py index c5d859b..261ee0a 100644 --- a/elements.py +++ b/elements.py @@ -1,195 +1,275 @@ from math import pi, sqrt, acos, cos, sin import numpy as np +import numbers class Point: - def __init__(self, x, y, z): - self.x = x - self.y = y - self.z = z - - def abs(self): - return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) - - def dist(self, other): - temp = other - self - return sqrt(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z) - - def cross(self, other): - return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) - - def dot(self, other): - return (self.x*other.x + self.y*other.y + self.z*other.z) - - def transform(self, T): - t = [[self.x], [self.y], [self.z], [1]] - t = T*t - return Point(t[0,0],t[1,0],t[2,0]) - - def aslist(self): - return [self.x, self.y, self.z] - - def __sub__(self,other): - return Point(self.x - other.x, self.y - other.y, self.z - other.z) - - def __add__(self,other): - return Point(self.x + other.x, self.y + other.y, self.z + other.z) - - def __neg__(self): - return Point(-self.x, -self.y, -self.z) - - def __mul__(self, other): - if type(other) == float or type(other) == int: - return Point(self.x * other, self.y * other, self.z * other) - else: - raise TypeError, 'The arguments passed must be Numerical' - - def __rmul__(self, other): - if type(other) == float or type(other) == int: - return Point(self.x * other, self.y * other, self.z * other) - else: - raise TypeError, 'The arguments passed must be Numerical' - - def __div__(self, other): - if type(other) == float or type(other) == int: - return Point(self.x/other, self.y/other, self.z/other) - else: - raise TypeError, 'The arguments passed must be Numerical' - - def __gt__(self, other): - if isinstance(other, Point): - return (self.abs() > other.abs()) - elif type(other) == numbers.Real: - return (self.abs() > other) - - def __lt__(self, other): - if isinstance(other, Point): - return (self.abs() < other.abs()) - elif type(other) == numbers.Real: - return (self.abs() < other) - - def __repr__(self): - return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" + def __init__(self, x, y, z): + self.x = float(x) + self.y = float(y) + self.z = float(z) + + def abs(self): + return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) + + def dist(self, other): + temp = other - self + return sqrt(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z) + + def cross(self, other): + return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) + + def dot(self, other): + return (self.x*other.x + self.y*other.y + self.z*other.z) + + def transform(self, T): + t = [[self.x], [self.y], [self.z], [1]] + t = T*t + return Point(t[0,0],t[1,0],t[2,0]) + + def __eq__(self,other): + if self.x==other.x and self.y==other.y and self.z==other.z: + return True + else: + return False + + def __ne__(self,other): + if self==other: + return false + else: + return true + + def __sub__(self,other): + return Point(self.x - other.x, self.y - other.y, self.z - other.z) + + def __add__(self,other): + return Point(self.x + other.x, self.y + other.y, self.z + other.z) + + def __neg__(self): + return Point(-self.x, -self.y, -self.z) + + def __mul__(self, other): + if type(other) == float or type(other) == int: + return Point(self.x * other, self.y * other, self.z * other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __rmul__(self, other): + if type(other) == float or type(other) == int: + return Point(self.x * other, self.y * other, self.z * other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __div__(self, other): + if type(other) == float or type(other) == int: + return Point(self.x/other, self.y/other, self.z/other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __gt__(self, other): + if isinstance(other, Point): + return (self.abs() > other.abs()) + elif type(other) == numbers.Real: + return (self.abs() > other) + + def __lt__(self, other): + if isinstance(other, Point): + return (self.abs() < other.abs()) + elif type(other) == numbers.Real: + return (self.abs() < other) + + def __repr__(self): + return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" + + def __getitem__(self, other): + values = {0:self.x,1:self.y,2:self.z} + return values.get(other) + + def aslist(self): + return [self.x, self.y, self.z] + + def asarray(self): + return np.array([self.x,self.y,self.z]) + class Line: - def __init__(self, P, vec=Point(0,0,0)): - if type(P) == list and len(P) > 1: - if isinstance(P[0],Point) and isinstance(P[1],Point): - self.P = P[0] - P2 = P[1] - self.vec = P2 - self.P - else: - raise TypeError, 'Line expects a list of two Points or a Point a directional Point' - elif isinstance(P,Point) and vec.abs() > 0: - self.P = P - self.vec = vec - else: - print P, vec - raise TypeError, 'Line expects a list of two Points or a Point a directional Point' - self.P = self.findnearestPoint() - self.vec = self.vec / self.vec.abs() - - def findnearestPoint(self, to=Point(0,0,0)): - P = self.P - vec = self.vec - u = vec.dot(to - P)/vec.dot(vec) - return (P + u*vec) - - def __repr__(self): - return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" - - def intersect(self, other): - if isinstance(other,Plane): - return other.lineintersect(self) - else: - return None -# elif isinstance(other,Line): -# return self.lineintersect(other) + def __init__(self, P, vec=Point(0,0,0)): + if type(P) == list and len(P) > 1: + if isinstance(P[0],Point) and isinstance(P[1],Point): + self.P = P[0] + P2 = P[1] + self.vec = P2 - self.P + else: + raise TypeError, 'Line expects a list of two Points or a Point a directional Point' + elif isinstance(P,Point) and vec.abs() > 0: + self.P = P + self.vec = vec + else: + raise TypeError, 'Line expects a list of two Points or a Point a directional Point' + self.vec = self.vec / float(self.vec.abs()) + self.P = self.findnearestPoint() + + def findnearestPoint(self, to=Point(0.,0.,0.)): + P = self.P + vec = self.vec + u = float(vec.dot(to - P))/float(vec.dot(vec)) + return (P + (u*vec)) + + def __repr__(self): + return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" + + def lineintersect(self,other): + A = self.P-other.P + B = self.vec + C = other.vec + # Check for parallel lines + self.cp12 = B.cross(C) + self._cp12_ = self.cp12.abs() + if round(self._cp12_, 6) != 0.0: + ma = ((A.dot(C)*C.dot(B)) - (A.dot(B)*C.dot(C)))/ \ + ((B.dot(B)*C.dot(C)) - (C.dot(B)*C.dot(B))) + ma = float(ma) + mb = (ma*C.dot(B) + A.dot(C))/ C.dot(C) + mb = float(mb) + Pa = self.P + (self.vec * ma) + Pb = other.P + (other.vec * mb) + return [Pa, Pb, (Pa+Pb)/2] + else: + return None + + def intersect(self, other): + if isinstance(other,Plane): + return other.lineintersect(self) + elif isinstance(other,Line): + return self.lineintersect(other) + else: + return None class Plane: - def __init__(self, N, D=0): - if isinstance(N,Point): - self.N = N - self.D = D - else: - raise TypeError, 'The arguments passed to Plane must be POINT' - - def __init__(self, P1, P2, P3): - def chk_type(p_list): - ret_list = [] - for p in p_list: - if isinstance(p, Point): - ret_list.append(p) - elif type(p) == list and len(p) > 2: - p = Point(p[0],p[1],p[2]) - ret_list.append(p) - else: - ret_list.append(None) - return ret_list - - [P1, P2, P3] = chk_type([P1, P2, P3]) - if None not in [P1, P2, P3]: - self.N, self.D = self.plane_def(P1, P2, P3) - else: - raise TypeError, 'The arguments passed to Plane must be POINT' - - def __repr__(self): - return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" - - def plane_def(self, p1, p2, p3): - N = (p2-p1).cross(p3-p1) - D = (-N).dot(p1) - return N, D - - def planeintersect(self, other): - N1 = self.N - N2 = other.N - D1 = self.D - D2 = other.D - if (N1.cross(N2)).abs() == 0: - # Planes are parallel - return None - else: - det = N1.dot(N1) * N2.dot(N2) - (N1.dot(N2))**2 - c1 = D1 * N2.dot(N2) - D2 * N1.dot(N2) / det - c2 = D2 * N1.dot(N1) - D1 * N1.dot(N2) / det - return Line((c1 * N1) + (c2 * N2), N1.cross(N2)) - - def lineintersect(self,other): - N = self.N - D = self.D - P = other.P - vec = other.vec - u1 = N.dot(P) + D - u2 = N.dot(vec) - u = u1 / u2 - return P + u * vec - - def intersect(self, other): - if isinstance(other,Plane): - return self.planeintersect(other) - elif isinstance(other,Line): - return self.lineintersect(other) + def __init__(self, P=Point(0,0,0), P2=None, P3=None, D=0): + def chk_type(p_list): + ret_list = [] + for p in p_list: + if isinstance(p, Point): + ret_list.append(p) + elif type(p) == list and len(p) > 2: + n = Point(p[0],p[1],p[2]) + ret_list.append(n) + elif type(p) == int or type(p) == float or type(p) == np.float32 or type(p) == np.float64: + ret_list.append(p) + else: + ret_list.append(None) + return ret_list + + [P, P2, P3, D] = chk_type([P, P2, P3, D]) + if isinstance(P,Point) and isinstance(P2,Point) and isinstance(P3,Point): + self.N, self.D = self.plane_def(P, P2, P3) + elif isinstance(P,Point): + self.N = P + self.D = D + else: + raise TypeError, 'The arguments passed to Plane must be POINT' + + def __repr__(self): + return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" + + def plane_def(self, p1, p2, p3): + N = (p2-p1).cross(p3-p1) + D = (-N).dot(p1) + return N, D + + def dist(self, other): + if isinstance(other, Point): + return self.N.dot(other - self.D*self.N)/self.N.abs() + else: + return None + + def planeintersect(self, other): + N1 = self.N + N2 = other.N + D1 = self.D + D2 = other.D + if (N1.cross(N2)).abs() == 0: + # Planes are parallel + return None + else: + det = N1.dot(N1) * N2.dot(N2) - (N1.dot(N2))**2 + c1 = D1 * N2.dot(N2) - D2 * N1.dot(N2) / det + c2 = D2 * N1.dot(N1) - D1 * N1.dot(N2) / det + return Line((c1 * N1) + (c2 * N2), N1.cross(N2)) + + def lineintersect(self,other): + N = self.N + D = self.D + P = other.P + vec = other.vec + u1 = float(N.dot(D*N - P)) + u2 = float(N.dot(vec)) + #print u1,u2 + u = u1 / u2 + return P + u * vec + def intersect(self, other): + if isinstance(other,Plane): + return self.planeintersect(other) + elif isinstance(other,Line): + return self.lineintersect(other) + else: + return None + + def projection(self, other): + if isinstance(other,Point): + return self.lineintersect(Line(other,vec=self.N)) + else: + return None + + def getpoints(self, x_range, y_range): + a = self.N[0] + b = self.N[1] + c = self.N[2] + d = self.D + xs = np.arange(x_range[0],x_range[1],(x_range[1]-x_range[0])/2) + ys = np.arange(y_range[0],y_range[1],(y_range[1]-y_range[0])/2) + xP = np.zeros((len(xs),len(ys)), dtype=float) + yP = np.zeros((len(xs),len(ys)), dtype=float) + zP = np.zeros((len(xs),len(ys)), dtype=float) + for x in range(len(xs)): + for y in range(len(ys)): + xP[x,y] = xs[x] + yP[x,y] = ys[y] + zP[x,y] = (-a*xs[x]-b*ys[y]-d)/c + return xP,yP,zP + + def getcoordinatesystem(self): + ZeroPoint = float(self.D) * self.N + z1 = self.N + x1Point = self.projection(Point(1,0,0)) + if x1Point == Point(0,0,0): + x1Point = self.projection(Point(0,1,0)) + x1 = x1Point - ZeroPoint + x1 = x1 / x1.abs() + y1 = z1.cross(x1) + return [ZeroPoint,x1,y1,z1] + if __name__ == '__main__': - p1 = Point(1,1,0) - p2 = Point(1,0,0) - p3 = Point(0,1,0) + p1 = Point(1,1,0) + p2 = Point(1,0,0) + p3 = Point(0,1,0) - p4 = Point(0,0,1) - p5 = Point(0,1,1) - p6 = Point(0,1,0) + p4 = Point(0,0,1) + p5 = Point(0,1,1) + p6 = Point(0,1,0) - p7 = Point(0,0,1) - p8 = Point(1,0,1) - p9 = Point(1,0,0) + p7 = Point(0,0,1) + p8 = Point(1,0,1) + p9 = Point(1,0,0) - plane1 = Plane(p1,p2,[0,1,0]) - plane2 = Plane(p4,p5,p6) - plane3 = Plane(p7,p8,p9) + plane1 = Plane(p1,p2,[0,1,0]) + plane2 = Plane(p4,p5,p6) + plane3 = Plane(p7,p8,p9) - line1 = plane1.intersect(plane2) - point1 = plane3.intersect(line1) + line1 = plane1.intersect(plane2) + point1 = plane3.intersect(line1) - print plane1 - print line1 - print point1 + print plane1 + print line1 + print point1
toomuchcookies/Python-Geometry
435dde1ead78613021865ed46fad28bbfde52435
renaming
diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..a32045d --- /dev/null +++ b/__init__.py @@ -0,0 +1 @@ +__all__ = ["elements"] diff --git a/geometry.py b/elements.py similarity index 100% rename from geometry.py rename to elements.py
toomuchcookies/Python-Geometry
0194cbda96618cb0f80e5ca47551d7a61ad75243
Point.aslist() und Verbesserung des Point.transform()
diff --git a/geometry.py b/geometry.py index b9e1921..c5d859b 100644 --- a/geometry.py +++ b/geometry.py @@ -1,191 +1,195 @@ from math import pi, sqrt, acos, cos, sin import numpy as np class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def abs(self): return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) def dist(self, other): temp = other - self return sqrt(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z) def cross(self, other): return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def dot(self, other): return (self.x*other.x + self.y*other.y + self.z*other.z) def transform(self, T): - t = [self.x, self.y, self.z, 1] - return T*t + t = [[self.x], [self.y], [self.z], [1]] + t = T*t + return Point(t[0,0],t[1,0],t[2,0]) + + def aslist(self): + return [self.x, self.y, self.z] def __sub__(self,other): return Point(self.x - other.x, self.y - other.y, self.z - other.z) def __add__(self,other): return Point(self.x + other.x, self.y + other.y, self.z + other.z) def __neg__(self): return Point(-self.x, -self.y, -self.z) def __mul__(self, other): if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __rmul__(self, other): if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __div__(self, other): if type(other) == float or type(other) == int: return Point(self.x/other, self.y/other, self.z/other) else: raise TypeError, 'The arguments passed must be Numerical' def __gt__(self, other): if isinstance(other, Point): return (self.abs() > other.abs()) elif type(other) == numbers.Real: return (self.abs() > other) def __lt__(self, other): if isinstance(other, Point): return (self.abs() < other.abs()) elif type(other) == numbers.Real: return (self.abs() < other) def __repr__(self): return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" class Line: def __init__(self, P, vec=Point(0,0,0)): if type(P) == list and len(P) > 1: if isinstance(P[0],Point) and isinstance(P[1],Point): self.P = P[0] P2 = P[1] self.vec = P2 - self.P else: raise TypeError, 'Line expects a list of two Points or a Point a directional Point' elif isinstance(P,Point) and vec.abs() > 0: self.P = P self.vec = vec else: print P, vec raise TypeError, 'Line expects a list of two Points or a Point a directional Point' self.P = self.findnearestPoint() self.vec = self.vec / self.vec.abs() def findnearestPoint(self, to=Point(0,0,0)): P = self.P vec = self.vec u = vec.dot(to - P)/vec.dot(vec) return (P + u*vec) def __repr__(self): return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" def intersect(self, other): if isinstance(other,Plane): return other.lineintersect(self) else: return None # elif isinstance(other,Line): # return self.lineintersect(other) class Plane: def __init__(self, N, D=0): if isinstance(N,Point): self.N = N self.D = D else: raise TypeError, 'The arguments passed to Plane must be POINT' def __init__(self, P1, P2, P3): def chk_type(p_list): ret_list = [] for p in p_list: if isinstance(p, Point): ret_list.append(p) elif type(p) == list and len(p) > 2: p = Point(p[0],p[1],p[2]) ret_list.append(p) else: ret_list.append(None) return ret_list [P1, P2, P3] = chk_type([P1, P2, P3]) if None not in [P1, P2, P3]: self.N, self.D = self.plane_def(P1, P2, P3) else: raise TypeError, 'The arguments passed to Plane must be POINT' def __repr__(self): return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" def plane_def(self, p1, p2, p3): N = (p2-p1).cross(p3-p1) D = (-N).dot(p1) return N, D def planeintersect(self, other): N1 = self.N N2 = other.N D1 = self.D D2 = other.D if (N1.cross(N2)).abs() == 0: # Planes are parallel return None else: det = N1.dot(N1) * N2.dot(N2) - (N1.dot(N2))**2 c1 = D1 * N2.dot(N2) - D2 * N1.dot(N2) / det c2 = D2 * N1.dot(N1) - D1 * N1.dot(N2) / det return Line((c1 * N1) + (c2 * N2), N1.cross(N2)) def lineintersect(self,other): N = self.N D = self.D P = other.P vec = other.vec u1 = N.dot(P) + D u2 = N.dot(vec) u = u1 / u2 return P + u * vec def intersect(self, other): if isinstance(other,Plane): return self.planeintersect(other) elif isinstance(other,Line): return self.lineintersect(other) if __name__ == '__main__': p1 = Point(1,1,0) p2 = Point(1,0,0) p3 = Point(0,1,0) p4 = Point(0,0,1) p5 = Point(0,1,1) p6 = Point(0,1,0) p7 = Point(0,0,1) p8 = Point(1,0,1) p9 = Point(1,0,0) plane1 = Plane(p1,p2,[0,1,0]) plane2 = Plane(p4,p5,p6) plane3 = Plane(p7,p8,p9) line1 = plane1.intersect(plane2) point1 = plane3.intersect(line1) print plane1 print line1 print point1
toomuchcookies/Python-Geometry
7399d89f0ca88038dd374e1d85626170b2f771bc
Point.transform(T) eingebaut.
diff --git a/geometry.py b/geometry.py index 94ef559..b9e1921 100644 --- a/geometry.py +++ b/geometry.py @@ -1,187 +1,191 @@ from math import pi, sqrt, acos, cos, sin +import numpy as np class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def abs(self): return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) def dist(self, other): temp = other - self return sqrt(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z) def cross(self, other): return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def dot(self, other): return (self.x*other.x + self.y*other.y + self.z*other.z) + + def transform(self, T): + t = [self.x, self.y, self.z, 1] + return T*t def __sub__(self,other): return Point(self.x - other.x, self.y - other.y, self.z - other.z) def __add__(self,other): return Point(self.x + other.x, self.y + other.y, self.z + other.z) def __neg__(self): return Point(-self.x, -self.y, -self.z) def __mul__(self, other): if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __rmul__(self, other): if type(other) == float or type(other) == int: return Point(self.x * other, self.y * other, self.z * other) else: raise TypeError, 'The arguments passed must be Numerical' def __div__(self, other): if type(other) == float or type(other) == int: return Point(self.x/other, self.y/other, self.z/other) else: raise TypeError, 'The arguments passed must be Numerical' def __gt__(self, other): if isinstance(other, Point): return (self.abs() > other.abs()) elif type(other) == numbers.Real: return (self.abs() > other) def __lt__(self, other): if isinstance(other, Point): return (self.abs() < other.abs()) elif type(other) == numbers.Real: return (self.abs() < other) def __repr__(self): return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" class Line: def __init__(self, P, vec=Point(0,0,0)): if type(P) == list and len(P) > 1: if isinstance(P[0],Point) and isinstance(P[1],Point): self.P = P[0] P2 = P[1] self.vec = P2 - self.P else: raise TypeError, 'Line expects a list of two Points or a Point a directional Point' elif isinstance(P,Point) and vec.abs() > 0: self.P = P self.vec = vec else: print P, vec raise TypeError, 'Line expects a list of two Points or a Point a directional Point' self.P = self.findnearestPoint() self.vec = self.vec / self.vec.abs() def findnearestPoint(self, to=Point(0,0,0)): P = self.P vec = self.vec u = vec.dot(to - P)/vec.dot(vec) return (P + u*vec) - def __repr__(self): return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" def intersect(self, other): if isinstance(other,Plane): return other.lineintersect(self) else: return None # elif isinstance(other,Line): # return self.lineintersect(other) class Plane: def __init__(self, N, D=0): if isinstance(N,Point): self.N = N self.D = D else: raise TypeError, 'The arguments passed to Plane must be POINT' def __init__(self, P1, P2, P3): def chk_type(p_list): ret_list = [] for p in p_list: if isinstance(p, Point): ret_list.append(p) elif type(p) == list and len(p) > 2: p = Point(p[0],p[1],p[2]) ret_list.append(p) else: ret_list.append(None) return ret_list [P1, P2, P3] = chk_type([P1, P2, P3]) if None not in [P1, P2, P3]: self.N, self.D = self.plane_def(P1, P2, P3) else: raise TypeError, 'The arguments passed to Plane must be POINT' def __repr__(self): return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" def plane_def(self, p1, p2, p3): N = (p2-p1).cross(p3-p1) D = (-N).dot(p1) return N, D def planeintersect(self, other): N1 = self.N N2 = other.N D1 = self.D D2 = other.D if (N1.cross(N2)).abs() == 0: # Planes are parallel return None else: det = N1.dot(N1) * N2.dot(N2) - (N1.dot(N2))**2 c1 = D1 * N2.dot(N2) - D2 * N1.dot(N2) / det c2 = D2 * N1.dot(N1) - D1 * N1.dot(N2) / det return Line((c1 * N1) + (c2 * N2), N1.cross(N2)) def lineintersect(self,other): N = self.N D = self.D P = other.P vec = other.vec u1 = N.dot(P) + D u2 = N.dot(vec) u = u1 / u2 return P + u * vec def intersect(self, other): if isinstance(other,Plane): return self.planeintersect(other) elif isinstance(other,Line): return self.lineintersect(other) if __name__ == '__main__': p1 = Point(1,1,0) p2 = Point(1,0,0) p3 = Point(0,1,0) p4 = Point(0,0,1) p5 = Point(0,1,1) p6 = Point(0,1,0) p7 = Point(0,0,1) p8 = Point(1,0,1) p9 = Point(1,0,0) plane1 = Plane(p1,p2,[0,1,0]) plane2 = Plane(p4,p5,p6) plane3 = Plane(p7,p8,p9) line1 = plane1.intersect(plane2) point1 = plane3.intersect(line1) print plane1 print line1 print point1
toomuchcookies/Python-Geometry
26d902714de197e3ed8f2dd3b6aeaa88b560321b
Initial functioning geometry.py
diff --git a/geometry.py b/geometry.py new file mode 100644 index 0000000..94ef559 --- /dev/null +++ b/geometry.py @@ -0,0 +1,187 @@ +from math import pi, sqrt, acos, cos, sin + +class Point: + def __init__(self, x, y, z): + self.x = x + self.y = y + self.z = z + + def abs(self): + return sqrt(self.x*self.x + self.y*self.y + self.z*self.z) + + def dist(self, other): + temp = other - self + return sqrt(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z) + + def cross(self, other): + return Point(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) + + def dot(self, other): + return (self.x*other.x + self.y*other.y + self.z*other.z) + + def __sub__(self,other): + return Point(self.x - other.x, self.y - other.y, self.z - other.z) + + def __add__(self,other): + return Point(self.x + other.x, self.y + other.y, self.z + other.z) + + def __neg__(self): + return Point(-self.x, -self.y, -self.z) + + def __mul__(self, other): + if type(other) == float or type(other) == int: + return Point(self.x * other, self.y * other, self.z * other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __rmul__(self, other): + if type(other) == float or type(other) == int: + return Point(self.x * other, self.y * other, self.z * other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __div__(self, other): + if type(other) == float or type(other) == int: + return Point(self.x/other, self.y/other, self.z/other) + else: + raise TypeError, 'The arguments passed must be Numerical' + + def __gt__(self, other): + if isinstance(other, Point): + return (self.abs() > other.abs()) + elif type(other) == numbers.Real: + return (self.abs() > other) + + def __lt__(self, other): + if isinstance(other, Point): + return (self.abs() < other.abs()) + elif type(other) == numbers.Real: + return (self.abs() < other) + + def __repr__(self): + return "Point(" + repr(self.x) + ", " + repr(self.y) + ", " + repr(self.z) + ")" + +class Line: + def __init__(self, P, vec=Point(0,0,0)): + if type(P) == list and len(P) > 1: + if isinstance(P[0],Point) and isinstance(P[1],Point): + self.P = P[0] + P2 = P[1] + self.vec = P2 - self.P + else: + raise TypeError, 'Line expects a list of two Points or a Point a directional Point' + elif isinstance(P,Point) and vec.abs() > 0: + self.P = P + self.vec = vec + else: + print P, vec + raise TypeError, 'Line expects a list of two Points or a Point a directional Point' + self.P = self.findnearestPoint() + self.vec = self.vec / self.vec.abs() + + def findnearestPoint(self, to=Point(0,0,0)): + P = self.P + vec = self.vec + u = vec.dot(to - P)/vec.dot(vec) + return (P + u*vec) + + + def __repr__(self): + return "Line(" + repr(self.P) + ", " + repr(self.vec) + ")" + + def intersect(self, other): + if isinstance(other,Plane): + return other.lineintersect(self) + else: + return None +# elif isinstance(other,Line): +# return self.lineintersect(other) + +class Plane: + def __init__(self, N, D=0): + if isinstance(N,Point): + self.N = N + self.D = D + else: + raise TypeError, 'The arguments passed to Plane must be POINT' + + def __init__(self, P1, P2, P3): + def chk_type(p_list): + ret_list = [] + for p in p_list: + if isinstance(p, Point): + ret_list.append(p) + elif type(p) == list and len(p) > 2: + p = Point(p[0],p[1],p[2]) + ret_list.append(p) + else: + ret_list.append(None) + return ret_list + + [P1, P2, P3] = chk_type([P1, P2, P3]) + if None not in [P1, P2, P3]: + self.N, self.D = self.plane_def(P1, P2, P3) + else: + raise TypeError, 'The arguments passed to Plane must be POINT' + + def __repr__(self): + return "Plane(" + repr(self.N) + ", " + repr(self.D) + ")" + + def plane_def(self, p1, p2, p3): + N = (p2-p1).cross(p3-p1) + D = (-N).dot(p1) + return N, D + + def planeintersect(self, other): + N1 = self.N + N2 = other.N + D1 = self.D + D2 = other.D + if (N1.cross(N2)).abs() == 0: + # Planes are parallel + return None + else: + det = N1.dot(N1) * N2.dot(N2) - (N1.dot(N2))**2 + c1 = D1 * N2.dot(N2) - D2 * N1.dot(N2) / det + c2 = D2 * N1.dot(N1) - D1 * N1.dot(N2) / det + return Line((c1 * N1) + (c2 * N2), N1.cross(N2)) + + def lineintersect(self,other): + N = self.N + D = self.D + P = other.P + vec = other.vec + u1 = N.dot(P) + D + u2 = N.dot(vec) + u = u1 / u2 + return P + u * vec + + def intersect(self, other): + if isinstance(other,Plane): + return self.planeintersect(other) + elif isinstance(other,Line): + return self.lineintersect(other) + +if __name__ == '__main__': + p1 = Point(1,1,0) + p2 = Point(1,0,0) + p3 = Point(0,1,0) + + p4 = Point(0,0,1) + p5 = Point(0,1,1) + p6 = Point(0,1,0) + + p7 = Point(0,0,1) + p8 = Point(1,0,1) + p9 = Point(1,0,0) + + plane1 = Plane(p1,p2,[0,1,0]) + plane2 = Plane(p4,p5,p6) + plane3 = Plane(p7,p8,p9) + + line1 = plane1.intersect(plane2) + point1 = plane3.intersect(line1) + + print plane1 + print line1 + print point1
aproxacs/twitter-bot
fbb6c8aa74cd00a599005e8fe627b5f3ee29688a
bug fix : user option is shared
diff --git a/lib/twitter_bot/worker.rb b/lib/twitter_bot/worker.rb index 20234e7..6b36471 100644 --- a/lib/twitter_bot/worker.rb +++ b/lib/twitter_bot/worker.rb @@ -1,150 +1,150 @@ module TwitterBot class Worker def initialize(conn, options) @conn = conn @options = options @msg_queue = {} load_users end def handle_message(session, sender, message) user = find_user(sender) case message when /^!oauth/ session.say """ \ Please connect to #{user.request_token.authorize_url} and complete the authentication. \ After completing authentication, twitter will show you 6 digit numbers. This is a PIN code. Please let me know these 6 digit PIN code with !pin command. EXAMPLE : !pin 432433 """ when /^!pin/ message =~ /^!pin\s+(\d{6})/ digits = $1 user.complete_oauth(digits) if user.authorized? save_users msg = "Good! Success to sign in Twitter! Have fun with me!" else msg = "Sorry. Fail to sign in Twitter. Maybe the PIN number was wrong." end session.say msg when /^!show/ msg = "Twitter State : #{user.authorized? ? 'Authorized' : 'Not authorized'}\n" session.say msg when /^!\s/ message =~ /^!\s+(.*)/ text = $1 unless user.authorized? session.say """\ Sorry, You are not authorized in twitter yet. Twitter and I are using OAuth protocol to safely get your authorization. Please type !oauth command and start authorization. """ return end if text and not text.empty? user.update_twitter(text) session.say "OK! success to write #{text} on Twitter" else session.say "Sorry, Wrong Format! \n EXAMPLE] ! some text" end when /^!help/i session.say help_str else session.say "I'm Twitter Bot. \nType !help to see what you can do with me." end end def msg_queue_of(email) @msg_queue[email] ||= [] end def offline?(email) contact = @conn.contactlists["FL"][email] contact ? contact.status.code == "FLN" : true end def check_twitter users.each do |email, user| next unless user.authorized? if offline?(email) user.update_since_id TwitterBot.debug "==> #{email} if offline..." next end user.twitter_updates.each do |msg| TwitterBot.debug "==> Add New Message to #{email} : #{msg}" msg_queue_of(email) << msg end create_session(email) if msg_queue_of(email).size > 0 end end def create_session(email) if @conn.chatsessions[email] TwitterBot.debug "==> Force clear session : #{email}" begin @conn.chatsessions[email].close rescue Exception end @conn.remove_session(email) end TwitterBot.debug "==> Request to start new Chat Session : #{email}" @conn.start_chat(email, email) end def has_user?(tag) not users[tag].nil? end protected def users @users ||= {} end def load_users filename = @options[:data_file] TwitterBot.debug "=> Loading users from #{filename}" user_data = File.exist?(filename) ? YAML.load_file(filename) : {} user_data.each do |email, data| TwitterBot.debug "=> Loading user #{email}" users[email] = User.new(email, data.merge(@options[:twitter])) end end def save_users TwitterBot.debug "=> Saving users" user_data = {} users.each do |email, user| user_data[email] = user.to_hash end File.open( @options[:data_file], 'w' ) do |out| YAML.dump( user_data, out ) end end def find_user(email) - users[email] ||= User.new(email, @options[:twitter]) + users[email] ||= User.new(email, @options[:twitter].clone) end def help_str """\ I am Twitter Bot. I will deliver your timeline updates immediately. To use me, you need authorization. Please start authorization with !oauth command. Authorization is required just one time. Commands : - !oauth : Starts OAuth authorization to use Twitter. EXAMPLE : !oauth - !pin PIN_NUMBER : Enter PIN number that twitter gives to complete OAuth authorization. EXAMPLE : !pin 232334 - !show : Shows user's state - ! TEXT: Write TEXT on Twitter EXAMPLE : ! This text will be in my timeline. - !help : Shows help """ end end end
aproxacs/twitter-bot
f3023d630454be46dd9c1461e93a87e3125cfaa5
daemonize is now possible, README added
diff --git a/README b/README index f7c13d8..fe21c8f 100644 --- a/README +++ b/README @@ -1,2 +1,73 @@ == twitter_bot +* homepage : http://github.com/aproxacs/twitter-bot + +== DESCRIPTIONS +Twitter bot is a MSN messenger bot interacting with Twitter. +It observes Twitter's timeline updates, and notifies new updates with msn messenger. +You can also update twitter with msn messenger. + +== DEMO & USE +Here is a working twitter bot ID : twitterbot@live.co.kr. +Just add twitterbot@live.co.kr as a friend of msn messenger. +=== Authorization +You need a authorization to update and get timeline of twitter. Twitter supports OAuth authentication and Twitter bot uses it. To see what OAuth, refer to http://apiwiki.twitter.com/OAuth-FAQ. The step to completing authentication is simple. +1. Type !oauth command. +Then the bot reply you with a url. Connect to the url and finish the authentication. After completing authenticataion, twitter will show you a 6 digit numbers. These numbers are PIN code. +2. Type !pin PIN. +For example, !pin 423432. That's it. + +To see my authorization state, type !show command. +To see help, type !help command. + + +== INSTALL +You don't need to install it to use Twitter bot. There is working bot : twitterbot@live.co.kr. + +However if you make up your mind to use Twitter bot for a personal perpose, the following will be a guide for you. +First of all, you need ruby and several gems.(see REQUIREMENTS) + +# Install ruby + +# Install gems +* sudo gem install activesupport twitter eventmachine daemons + +# Download twitter bot from github(http://github.com/aproxacs/twitter-bot) +* git clone git://github.com/aproxacs/twitter-bot.git + +# Set up a configuration(see CONFIGURATION) +# msn id and password and twitter consumer key and secret are required. + +# Start as a daemon(see START & STOP) +* cd DIR/lib +* ruby twibot_ctl.rb start + +== REQUIREMENTS +* ruby 1.8.6 +* activesupport +* twitter +* eventmachine +* daemons + +== CONFIGURATION +msn: + id: "MSN_ID_OF_BOT" # msn id for bot + password: "PASSWORD" +twitter: + ckey: "CONSUMER_KEY" # cosumer key + csecret: "CONSUMER_SECRET" +interval: 60 # optional, interval(second) to check twitter timeline +debug: false # optional +data_file: # optional, filename to store user's data +log_file: # optional, log filename + + +== START & STOP +# start as a daemon +* ruby twibot_ctl.rb start + +# stop +* ruby twibot_ctl.rb stop + +# restart +* ruby twibot_ctl.rb restart diff --git a/lib/twibot.rb b/lib/twibot.rb index f90b002..883f8b1 100644 --- a/lib/twibot.rb +++ b/lib/twibot.rb @@ -1,18 +1,20 @@ #!/usr/bin/ruby +$: << File.dirname(__FILE__) + require 'twitter_bot' CONFIG_FILE = File.join(File.dirname(__FILE__), "..", "config","settings.yml") unless File.exist?(CONFIG_FILE) puts "Configuration file #{CONFIG_FILE} does not exist... exit" exit end configs = { "data_file" => File.join(File.dirname(__FILE__), "..", "config","data.yml"), "log_file" => File.join(File.dirname(__FILE__), "..", "log","twitter_bot.log"), "interval" => 60, "debug" => true }.merge(YAML.load_file(CONFIG_FILE)) TwitterBot.start(configs) diff --git a/lib/twitter_bot.rb b/lib/twitter_bot.rb index 8eb63e0..1f5a6bb 100644 --- a/lib/twitter_bot.rb +++ b/lib/twitter_bot.rb @@ -1,45 +1,42 @@ %w(rubygems activesupport eventmachine twitter yaml).each {|l| require l} require 'msn/msn' require 'twitter_bot/worker' require 'twitter_bot/msn_hanler' require 'twitter_bot/user' module TwitterBot def self.start(options = {}) @options = self.deep_symbolize_keys(options) set_log(@options[:log_file]) MsnHandler.new(@options).start end mattr_accessor :log def self.info msg - p msg self.log.info msg if self.log end def self.error msg - p msg self.log.error msg if self.log end def self.debug msg - p msg self.log.debug msg if self.log and self.debug? end def self.deep_symbolize_keys(hash) hash.inject({}) { |result, (key, value)| value = deep_symbolize_keys(value) if value.is_a? Hash result[(key.to_sym rescue key) || key] = value result } end private def self.set_log(filename) FileUtils.mkdir_p(File.dirname(filename)) self.log = Logger.new(filename) end def self.debug? @options[:debug] end end diff --git a/lib/twitter_bot/msn_hanler.rb b/lib/twitter_bot/msn_hanler.rb index 174dd8a..16a044d 100644 --- a/lib/twitter_bot/msn_hanler.rb +++ b/lib/twitter_bot/msn_hanler.rb @@ -1,77 +1,77 @@ module TwitterBot class MsnHandler def initialize(options = {}) @options = options self end def start TwitterBot.info "== Starting Twitter Bot ==" create_conn do |conn| conn.new_chat_session = lambda do |tag, session| TwitterBot.info "=> new chat session created with tag '#{tag}'!" - # session.debuglog = nil + session.debuglog = nil if @options[:debug] == false session.message_received = lambda do |sender, message| TwitterBot.info "=> #{sender} says: #{message}" begin worker.handle_message(session, sender, message) rescue Exception => e TwitterBot.error e.backtrace.join("\n") TwitterBot.error e end end session.session_started = lambda do TwitterBot.debug "=> Session started : #{tag}" return unless worker.has_user? tag TwitterBot.debug "=> #{tag} : has #{worker.msg_queue_of(tag).size} messages" worker.msg_queue_of(tag).each do |msg| TwitterBot.info "=> Send msg to #{tag} : #{msg}" session.say msg end worker.msg_queue_of(tag).clear TwitterBot.debug "=> Close session : #{tag}" session.close end session.start end end.start keep_alive end protected def worker @worker ||= Worker.new(@conn, @options) end def create_conn msn = @options[:msn] @conn = MSNConnection.new(msn[:id], msn[:password]) @conn.signed_in = lambda { @conn.change_nickname "Twitter Bot" } - # @conn.debuglog = nil + @conn.debuglog = nil if @options[:debug] == false yield @conn if block_given? @conn end def keep_alive interval = @options[:interval].to_i EventMachine::run do EventMachine::add_periodic_timer(interval) do @conn.send_ping begin worker.check_twitter rescue Exception => e TwitterBot.error e.backtrace.join("\n") TwitterBot.error e end end end end end -end \ No newline at end of file +end diff --git a/lib/twitter_bot/worker.rb b/lib/twitter_bot/worker.rb index 8985973..20234e7 100644 --- a/lib/twitter_bot/worker.rb +++ b/lib/twitter_bot/worker.rb @@ -1,149 +1,150 @@ module TwitterBot class Worker def initialize(conn, options) @conn = conn @options = options @msg_queue = {} load_users end def handle_message(session, sender, message) user = find_user(sender) case message when /^!oauth/ session.say """ \ -Please connect to #{user.request_token.authorize_url} and complete the authorization. \ -After completing authorization, twitter will show you 6 digit numbers. This is a PIN code. +Please connect to #{user.request_token.authorize_url} and complete the authentication. \ +After completing authentication, twitter will show you 6 digit numbers. This is a PIN code. Please let me know these 6 digit PIN code with !pin command. EXAMPLE : !pin 432433 """ when /^!pin/ message =~ /^!pin\s+(\d{6})/ digits = $1 user.complete_oauth(digits) if user.authorized? save_users msg = "Good! Success to sign in Twitter! Have fun with me!" else msg = "Sorry. Fail to sign in Twitter. Maybe the PIN number was wrong." end session.say msg when /^!show/ msg = "Twitter State : #{user.authorized? ? 'Authorized' : 'Not authorized'}\n" session.say msg when /^!\s/ message =~ /^!\s+(.*)/ text = $1 unless user.authorized? session.say """\ Sorry, You are not authorized in twitter yet. Twitter and I are using OAuth protocol to safely get your authorization. Please type !oauth command and start authorization. """ return end if text and not text.empty? user.update_twitter(text) session.say "OK! success to write #{text} on Twitter" else session.say "Sorry, Wrong Format! \n EXAMPLE] ! some text" end when /^!help/i session.say help_str else session.say "I'm Twitter Bot. \nType !help to see what you can do with me." end end def msg_queue_of(email) @msg_queue[email] ||= [] end def offline?(email) contact = @conn.contactlists["FL"][email] contact ? contact.status.code == "FLN" : true end def check_twitter users.each do |email, user| next unless user.authorized? if offline?(email) user.update_since_id TwitterBot.debug "==> #{email} if offline..." next end user.twitter_updates.each do |msg| TwitterBot.debug "==> Add New Message to #{email} : #{msg}" msg_queue_of(email) << msg end create_session(email) if msg_queue_of(email).size > 0 end end def create_session(email) if @conn.chatsessions[email] TwitterBot.debug "==> Force clear session : #{email}" begin @conn.chatsessions[email].close rescue Exception end @conn.remove_session(email) end TwitterBot.debug "==> Request to start new Chat Session : #{email}" @conn.start_chat(email, email) end def has_user?(tag) not users[tag].nil? end protected def users @users ||= {} end def load_users filename = @options[:data_file] TwitterBot.debug "=> Loading users from #{filename}" user_data = File.exist?(filename) ? YAML.load_file(filename) : {} user_data.each do |email, data| TwitterBot.debug "=> Loading user #{email}" users[email] = User.new(email, data.merge(@options[:twitter])) end end def save_users TwitterBot.debug "=> Saving users" user_data = {} users.each do |email, user| user_data[email] = user.to_hash end File.open( @options[:data_file], 'w' ) do |out| YAML.dump( user_data, out ) end end def find_user(email) users[email] ||= User.new(email, @options[:twitter]) end def help_str """\ I am Twitter Bot. -I will deliver your timeline update immediately. -You can also update your twitter with ! command. +I will deliver your timeline updates immediately. To use me, you need authorization. Please start authorization with !oauth command. Authorization is required just one time. Commands : - !oauth : Starts OAuth authorization to use Twitter. + EXAMPLE : !oauth - !pin PIN_NUMBER : Enter PIN number that twitter gives to complete OAuth authorization. + EXAMPLE : !pin 232334 - !show : Shows user's state - ! TEXT: Write TEXT on Twitter - EXAMPLE] ! some text + EXAMPLE : ! This text will be in my timeline. - !help : Shows help """ end end end
aproxacs/twitter-bot
7eb1ef0b45fb6887bf7d6cad1ec739bf3b104269
daemonize is now possible, README added
diff --git a/lib/twibot_ctl.rb b/lib/twibot_ctl.rb new file mode 100644 index 0000000..c487b02 --- /dev/null +++ b/lib/twibot_ctl.rb @@ -0,0 +1,5 @@ +require 'rubygems' +require 'daemons' + +Daemons.run('twibot.rb') +
wyhaines/ey-cloud-recipes
fec5f6bd870471a6ccb5ff424e6daebd5bff0b24
Varnish recipe
diff --git a/cookbooks/varnish/recipes/default.rb b/cookbooks/varnish/recipes/default.rb new file mode 100644 index 0000000..cdc1a7c --- /dev/null +++ b/cookbooks/varnish/recipes/default.rb @@ -0,0 +1,118 @@ +# +# Cookbook Name:: varnish +# Recipe:: default +# + +require 'etc' + +# This needs to be in keywords: www-servers/varnish ~x86 +package "varnish" do + action :install +end + + +##### +# +# These are generic tuning parameters for each instance size. You may want to +# tune them if they prove inadequate. +# +##### + +CACHE_DIR = '/var/lib/varnish' +size = `curl -s http://instance-data.ec2.internal/latest/meta-data/instance-type` +case size +when /m1.small/ # 1.7G RAM, 1 ECU, 32-bit, 1 core + THREAD_POOLS=1 + THREAD_POOL_MAX=1000 + OVERFLOW_MAX=2000 + CACHE="file,#{CACHE_DIR},100GB" +when /m1.large/ # 7.5G RAM, 4 ECU, 64-bit, 2 cores + THREAD_POOLS=2 + THREAD_POOL_MAX=2000 + OVERFLOW_MAX=4000 + CACHE="file,#{CACHE_DIR},100GB" +when /m1.xlarge/ # 15G RAM, 8 ECU, 64-bit, 4 cores + THREAD_POOLS=4 + THREAD_POOL_MAX=4000 + OVERFLOW_MAX=8000 + CACHE="file,#{CACHE_DIR},100GB" +when /c1.medium/ # 1.7G RAM, 5 ECU, 32-bit, 2 cores + THREAD_POOLS=2 + THREAD_POOL_MAX=2000 + OVERFLOW_MAX=4000 + CACHE="file,#{CACHE_DIR},100GB" +when /c1.xlarge/ # 7G RAM, 20 ECU, 64-bit, 8 cores + THREAD_POOLS=8 + THREAD_POOL_MAX=8000 # This might be too much. + OVERFLOW_MAX=16000 + CACHE="file,#{CACHE_DIR},100GB" +when /m2.xlarge/ # 17.1G RAM, 6.5 ECU, 64-bit, 2 cores + THREAD_POOLS=2 + THREAD_POOL_MAX=2000 + OVERFLOW_MAX=4000 + CACHE="file,#{CACHE_DIR},100GB" +when /m2.2xlarge/ # 34.2G RAM, 13 ECU, 64-bit, 4 cores + THREAD_POOLS=4 + THREAD_POOL_MAX=4000 + OVERFLOW_MAX=8000 + CACHE="file,#{CACHE_DIR},100GB" +when /m2.4xlarge/ # 68.4G RAM, 26 ECU, 64-bit, 8 cores + THREAD_POOLS=8 + THREAD_POOL_MAX=8000 # This might be too much. + OVERFLOW_MAX=16000 + CACHE="file,#{CACHE_DIR},100GB" +else # This shouldn't happen, but do something rational if it does. + THREAD_POOLS=1 + THREAD_POOL_MAX=2000 + OVERFLOW_MAX=2000 + CACHE="file,#{CACHE_DIR},100GB" +end + + +# Install the varnish monit file. +template '/etc/monit.d/varnishd.monitrc' do + owner node[:owner_name] + group node[:owner_name] + source 'varnishd.monitrc.erb' + variables({ + :thread_pools => THREAD_POOLS, + :thread_pool_max => THREAD_POOL_MAX, + :overflow_max => OVERFLOW_MAX, + :cache => CACHE + }) +end + + +# Make sure the cache directory exists. +unless FileTest.exist? CACHE_DIR + user = Etc::getpwnam(node[:owner_name]) + File.mkdir(CACHE_DIR) + File.chown(user.uid,user.gid,CACHE_DIR) +end + + +# Edit nginx config to change it off of port 80; we may or may not want the recipe to do this? +# The idea is that for the typical simple deployment, nginx will be listening in some config to port 80. +# We want to change that to port 81, so that the default varnish config can listen on port 80 and forward to 81. + +execute "Edit the config files inline to change nginx from listening on port 80 to listening on port 81" do + command %Q{ + perl -p -i -e's{listen 81;}{listen 80;}' /etc/nginx/servers/*.conf + } +end + +# Restart nginx + +execute "Restart nginx" do + command %Q{ + /etc/init.d/nginx restart + } +end + +# Start/restart varnish + +execute "Start varnish" do + command %Q{ + monit restart varnish_80 + } +end diff --git a/cookbooks/varnish/templates/default/varnish.monitrc.erb b/cookbooks/varnish/templates/default/varnish.monitrc.erb new file mode 100644 index 0000000..315fd22 --- /dev/null +++ b/cookbooks/varnish/templates/default/varnish.monitrc.erb @@ -0,0 +1,4 @@ +check process varnish_80 + with pidfile /var/run/varnish/varnish.80.pid + start program = /usr/sbin/varnishd -a :80 -T 127.0.0.1:6082 -s <%= @cache %> -f /etc/varnish/default.vcl -u nobody -g nobody -p obj_workspace=4096 -p sess_workspace=262144 -p listen_depth=2048 -p overflow_max=<%= @overflow_max %> -p ping_interval=2 -p log_hashstring=off -h classic,5000009 -p thread_pool_max=<%= @thread_pool_max %> -p lru_interval=60 -p esi_syntax=0x00000003 -p sess_timeout=10 -p thread_pools=<%= @thread_pools %> -p thread_pool_min=100 -p shm_workspace=32768 -p srcadd_ttl=0 -p thread_pool_add_delay=1 + stop program = /usr/bin/varnishadm -T 127.0.0.1:6082 stop
wyhaines/ey-cloud-recipes
8e5aaaf4472630dcf01aaa70d7c9e2bd1281bcb4
JRuby recipes.
diff --git a/cookbooks/jruby/recipes/default.rb b/cookbooks/jruby/recipes/default.rb new file mode 100644 index 0000000..cbf5bfa --- /dev/null +++ b/cookbooks/jruby/recipes/default.rb @@ -0,0 +1,89 @@ +# +# Cookbook Name:: jruby +# Recipe:: default +# + +package "dev-java/sun-jdk" do + action :install +end + +package "dev-java/jruby-bin" do + action :install +end + +execute "install-glassfish" do + command "/usr/bin/jruby -S gem install glassfish" +end + +##### +# +# Edit this to point to YOUR app's directory +# +##### + +APP_DIRECTORY = '/data/hello_world/current' + +##### +# +# These are generic tuning parameters for each instance size; you may want to further tune them for +# your application's specific needs if they prove inadequate. +# In particular, if you have a thread-safe application, you will _definitely_ only want a single +# runtime. +# +##### + +size = `curl -s http://instance-data.ec2.internal/latest/meta-data/instance-type` +case size +when /m1.small/ # 1.7G RAM, 1 ECU, 32-bit + JVM_CONFIG = '-server -Xmx1g -Xms1g -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC' + JRUBY_RUNTIME_POOL_INITIAL = 1 + JRUBY_RUNTIME_POOL_MIN = 1 + JRUBY_RUNTIME_POOL_MAX = 1 +when /m1.large/ # 1.7G RAM, 5 ECU, 32-bit + JVM_CONFIG = '-server -Xmx1g -Xms1g -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC' + JRUBY_RUNTIME_POOL_INITIAL = 1 + JRUBY_RUNTIME_POOL_MIN = 1 + JRUBY_RUNTIME_POOL_MAX = 5 +when /m1.xlarge/ # 7.5G RAM, 4 ECU, 64-bit + JVM_CONFIG = '-server -Xmx2.5g -Xms2.5g -XX:MaxPermSize=378m -XX:PermSize=378m =XX:NewRatio=2' + JRUBY_RUNTIME_POOL_INITIAL = 1 + JRUBY_RUNTIME_POOL_MIN = 1 + JRUBY_RUNTIME_POOL_MAX = 5 +when /c1.medium/ # 15G RAM, 8 ECU, 64-bit + JVM_CONFIG = '-server -Xmx2.5g -Xms2.5g -XX:MaxPermSize=378m -XX:PermSize=378m =XX:NewRatio=2' + JRUBY_RUNTIME_POOL_INITIAL = 1 + JRUBY_RUNTIME_POOL_MIN = 1 + JRUBY_RUNTIME_POOL_MAX = 8 +when /c1.xlarge/ # 7.5G RAM, 20 ECU, 64-bit + JVM_CONFIG = '-server -Xmx2.5g -Xms2.5g -XX:MaxPermSize=378m -XX:PermSize=378m =XX:NewRatio=2' + JRUBY_RUNTIME_POOL_INITIAL = 1 + JRUBY_RUNTIME_POOL_MIN = 1 + JRUBY_RUNTIME_POOL_MAX = 20 +else # This shouldn't happen, but do something rational if it does. + JVM_CONFIG = '-server -Xmx1g -Xms1g -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC' + JRUBY_RUNTIME_POOL_INITIAL = 1 + JRUBY_RUNTIME_POOL_MIN = 1 + JRUBY_RUNTIME_POOL_MAX = 1 +end + +template File.join([APP_DIRECTORY],'config','glassfish.yml') do + owner node[:owner_name] + group node[:owner_name] + source 'glassfish.yml.erb' + variables({ + :environment => 'development', + :port => 3000, + :contextroot => '/', + :log_level => 3, + :jruby_runtime_pool_initial => JRUBY_RUNTIME_POOL_INITIAL, + :jruby_runtime_pool_min => JRUBY_RUNTIME_POOL_MIN, + :jruby_runtime_pool_max => JRUBY_RUNTIME_POOL_MAX, + :daemon_enable => 'true', + :jvm_options => JVM_CONFIG + }) +end + +execute "ensure-glassfish-is-running" do + command "/usr/bin/jruby -S glassfish --config /data/hello_world/current/config/glassfish.yml /data/hello_world/current" + not_if "pgrep glassfish" +end diff --git a/cookbooks/jruby/templates/default/glassfish.yml.erb b/cookbooks/jruby/templates/default/glassfish.yml.erb new file mode 100644 index 0000000..c90ef9b --- /dev/null +++ b/cookbooks/jruby/templates/default/glassfish.yml.erb @@ -0,0 +1,95 @@ +# +# GlassFish configuration. +# +# Please read the comments for each configuration settings before modifying. +# + +# application environment. Default value development +environment: <%= @environment %> + + +# HTTP configuration +http: + + # port + port: <%= @port %> + + # context root. The default value is '/' + contextroot: <%= @contextroot %> + + +#Logging configuration +log: + + # Log file location. Default log file is log/<environment>.log. For + # example, if you are running in development environment, then the log + # file would be log/development.log. + # + # The log-file value must be either an absolute path or relative to your + # application directory. + + #log-file: + + # Logging level. Log level 0 to 7. 0:OFF, 1:SEVERE, 2:WARNING, + # 3:INFO (default), 4:FINE, 5:FINER, 6:FINEST, 7:ALL. + log-level: <%= @log_level %> + +# +# Runtime configuration +# If you are using Rails ver < 2.1.x, you should configure the JRuby runtime +# pool for increased scalability. +jruby-runtime-pool: + + # Initial number of jruby runtimes that Glassfish starts with. It defaults + # to one. It also represents the lowest value that Glassfish will use for + # the maximum and the highest value that Glassfish will accept for the + # minimum. As of this time, setting this number too high may cause + # undesirable behavior. Default value is . + initial: <%= @jruby_runtime_pool_initial %> + + # Minimum number of jruby runtimes that will be available in the pool. + # It defaults to one. The pool will always be at least this large, but + # may well be larger than this. Default value is 1. + min: <%= @jruby_runtime_pool_min %> + + + # Maximum number of jruby runtimes that may be available in the pool. + # It defaults to two. The pool will not neccessarily be this large. + # Values that are too high may result in OutOfMemory errors, either in + # the heap or in the PermGen. Default value is 1. + max: <%= @jruby_runtime_pool_max %> + +daemon: + # Run GlassFish as a daemon. GlassFish may not run as a daemon process + # on all platforms. Default value is false. + enable: <%= @daemon_enable %> + + # File where the process id of GlassFish is saved when run as daemon. + # The location must be either an absolute path or relative to your + # application directory. + # default PID file is tmp/pids/glassfish-<PID>.pid + + #pid: + + # Like JRuby GlassFish gem runs on Java Virtual Machine. You can pass + # JVM properties using 'jvm-options' property. The JVM options must be + # SPACE seprated. + # 'jvm-options. property can ONLY be used only in daemon + # mode. The numbers below are to give an ideas. The numbers in your case + # would vary based on the hardware capabilities of machine you are + # running. See what is a server class machine + # http://java.sun.com/javase/6/docs/technotes/guides/vm/server-class.html + + # GlassFish gem runs with these default options + # + #jvm-options: -server -Xmx512m -XX:MaxPermSize=192m -XX:NewRatio=2 -XX:+DisableExplicitGC -Dhk2.file.directory.changeIntervalTimer=6000 + + # Values below are given for a Sun Fire x4100, 4x Dual Core Opteron, 8G + # mem machine. You may like to changes these values according to the + # hardware you plan to run your application on. For details see + # JVM ergonomics document, + # http://java.sun.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html + # + #jvm-options: -server -Xmx2500m -Xms64m -XX:PermSize=256m -XX:MaxPermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC -Dhk2.file.directory.changeIntervalTimer=6000 + + jvm-options: <%= @jvm_options %>
wyhaines/ey-cloud-recipes
8fefe23decb249bda08d2dae151aa33569183ca7
Remove integrity cookbook
diff --git a/cookbooks/integrity/libraries/if_app_needs_recipe.rb b/cookbooks/integrity/libraries/if_app_needs_recipe.rb deleted file mode 100644 index a43175f..0000000 --- a/cookbooks/integrity/libraries/if_app_needs_recipe.rb +++ /dev/null @@ -1,25 +0,0 @@ -class Chef - class Recipe - def if_app_needs_recipe(recipe, &block) - index = 0 - node[:applications].map{|k,v| [k,v] }.sort_by {|a,b| a }.each do |name, app_data| - if app_data[:recipes].detect { |r| r == recipe } - Chef::Log.info("Applying Recipe: #{recipe}") - block.call(name, app_data, index) - index += 1 - end - end - end - - def any_app_needs_recipe?(recipe) - needs = false - node[:applications].each do |name, app_data| - if app_data[:recipes].detect { |r| r == recipe } - needs = true - end - end - needs - end - - end -end \ No newline at end of file diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb deleted file mode 100644 index 01a7918..0000000 --- a/cookbooks/integrity/recipes/default.rb +++ /dev/null @@ -1,64 +0,0 @@ -# -# Cookbook Name:: integrity -# Recipe:: default -# -# Copyright 2009, Engine Yard, Inc. -# -# All rights reserved - Do Not Redistribute -# - -require 'digest/sha1' - -gem_package 'foca-integrity-email' do - action :install - source "http://gems.github.com" -end - -gem_package 'foca-sinatra-ditties' do - action :install - source "http://gems.github.com" -end - -gem_package 'do_sqlite3' do - action :install -end - -gem_package 'integrity' do - action :install - version '0.1.9.0' -end - - -node[:applications].each do |app,data| - - - - execute "install integrity" do - command "integrity install --passenger /data/#{app}/current" - end - - template "/data/#{app}/current/config.ru" do - owner node[:owner_name] - group node[:owner_name] - mode 0655 - source "config.ru.erb" - end - - template "/data/#{app}/current/config.yml" do - owner node[:owner_name] - group node[:owner_name] - mode 0655 - source "config.yml.erb" - variables({ - :app => app, - :domain => data[:vhosts].first[:name], - }) - end - -end - - -execute "restart-apache" do - command "/etc/init.d/apache2 restart" - action :run -end \ No newline at end of file diff --git a/cookbooks/integrity/templates/default/config.ru.erb b/cookbooks/integrity/templates/default/config.ru.erb deleted file mode 100644 index 1d8f085..0000000 --- a/cookbooks/integrity/templates/default/config.ru.erb +++ /dev/null @@ -1,19 +0,0 @@ -require "rubygems" -require "integrity" - -# If you want to add any notifiers, install the gems and then require them here -# For example, to enable the Email notifier: install the gem (from github: -# -# sudo gem install -s http://gems.github.com foca-integrity-email -# -# And then uncomment the following line: -# -# require "notifier/email" - -# Load configuration and initialize Integrity -Integrity.new(File.dirname(__FILE__) + "/config.yml") - -# You probably don't want to edit anything below -Integrity::App.set :environment, ENV["RACK_ENV"] || :production - -run Integrity::App \ No newline at end of file diff --git a/cookbooks/integrity/templates/default/config.yml.erb b/cookbooks/integrity/templates/default/config.yml.erb deleted file mode 100644 index cf41c5c..0000000 --- a/cookbooks/integrity/templates/default/config.yml.erb +++ /dev/null @@ -1,41 +0,0 @@ -# Domain where integrity will be running from. This is used to have -# nice URLs in your notifications. -# For example: -# http://builder.integrityapp.com -:base_uri: <%= @domain %> - -# This should be a complete connection string to your database. -# -# Examples: -# * `mysql://user:password@localhost/integrity` -# * `postgres://<:password@localhost/integrity` -# * `sqlite3:///home/integrity/db/integrity.sqlite` -# -# Note: -# * The appropriate data_objects adapter must be installed (`do_mysql`, etc) -# * You must create the `integrity` database on localhost, of course. -:database_uri: sqlite3:///data/<%= @app %>/current/integrity.db - -# This is where your project's code will be checked out to. Make sure it's -# writable by the user that runs Integrity. -:export_directory: /data/<%= @app %>/current/builds - -# Path to the integrity log file -:log: /data/<%= @app %>/current/log/integrity.log - -# Enable or disable HTTP authentication for the app. BE AWARE that if you -# disable this anyone can delete and alter projects, so do it only if your -# app is running in a controlled environment (ie, behind your company's -# firewall.) -:use_basic_auth: false - -# When `use_basic_auth` is true, the admin's username for HTTP authentication. -:admin_username: <%= @node[:owner_name] %> - -# When `use_basic_auth` is true, the admin's password. Usually saved as a -# SHA1 hash. See the next option. -:admin_password: <%= Digest::SHA1.hexdigest(@node[:owner_pass]) %> - -# If this is true, then whenever we authenticate the admin user, will hash -# it using SHA1. If not, we'll assume the provided password is in plain text. -:hash_admin_password: true \ No newline at end of file diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 040399f..576faec 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,14 +1,11 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe # require_recipe "couchdb" -# uncomment to turn your instance into an integrity CI server -#require_recipe "integrity" - # uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance # require_recipe "mbari-ruby" \ No newline at end of file
wyhaines/ey-cloud-recipes
2e4ffb51580728f8f56acc784c830af451641430
mbari ruby ptch recipes jow works fine just uncomment it to run
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index ac25586..040399f 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,14 +1,14 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe # require_recipe "couchdb" # uncomment to turn your instance into an integrity CI server #require_recipe "integrity" # uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance -require_recipe "mbari-ruby" \ No newline at end of file +# require_recipe "mbari-ruby" \ No newline at end of file
wyhaines/ey-cloud-recipes
b6282a1642ac7ff41eb615f8bdedb056bd731eec
fix versioning for ruby interp
diff --git a/cookbooks/mbari-ruby/recipes/default.rb b/cookbooks/mbari-ruby/recipes/default.rb index 56209d3..2d01174 100644 --- a/cookbooks/mbari-ruby/recipes/default.rb +++ b/cookbooks/mbari-ruby/recipes/default.rb @@ -1,37 +1,38 @@ # # Cookbook Name:: mbari-ruby # Recipe:: default # directory "/etc/portage/package.keywords" do owner 'root' group 'root' mode 0775 recursive true end execute "add mbari keywords" do command %Q{ echo "=dev-lang/ruby-1.8.6_p287-r2" >> /etc/portage/package.keywords/local } not_if "cat /etc/portage/package.keywords/local | grep '=dev-lang/ruby-1.8.6_p287-r2'" end directory "/etc/portage/package.use" do owner 'root' group 'root' mode 0775 recursive true end execute "add mbari use flags" do command %Q{ echo "dev-lang/ruby mbari" >> /etc/portage/package.use/local } not_if "cat /etc/portage/package.use/local | grep 'dev-lang/ruby mbari'" end -package "dev-lang/ruby-1.8.6_p287-r2" do +package "dev-lang/ruby" do + version "1.8.6_p287-r2" action :install end \ No newline at end of file
wyhaines/ey-cloud-recipes
02dbdff117f96c7a2da0b325dd7a4f597b52a0d7
e mbari-ruby
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 1cb97d8..ac25586 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,11 +1,14 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe # require_recipe "couchdb" # uncomment to turn your instance into an integrity CI server -#require_recipe "integrity" \ No newline at end of file +#require_recipe "integrity" + +# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance +require_recipe "mbari-ruby" \ No newline at end of file
wyhaines/ey-cloud-recipes
13bbf36c3fd6d0b03ef256fa34aadfc5360f198e
adding mbari ruby patch build recipes
diff --git a/cookbooks/mbari-ruby/recipes/default.rb b/cookbooks/mbari-ruby/recipes/default.rb new file mode 100644 index 0000000..56209d3 --- /dev/null +++ b/cookbooks/mbari-ruby/recipes/default.rb @@ -0,0 +1,37 @@ +# +# Cookbook Name:: mbari-ruby +# Recipe:: default +# + + +directory "/etc/portage/package.keywords" do + owner 'root' + group 'root' + mode 0775 + recursive true +end + +execute "add mbari keywords" do + command %Q{ + echo "=dev-lang/ruby-1.8.6_p287-r2" >> /etc/portage/package.keywords/local + } + not_if "cat /etc/portage/package.keywords/local | grep '=dev-lang/ruby-1.8.6_p287-r2'" +end + +directory "/etc/portage/package.use" do + owner 'root' + group 'root' + mode 0775 + recursive true +end + +execute "add mbari use flags" do + command %Q{ + echo "dev-lang/ruby mbari" >> /etc/portage/package.use/local + } + not_if "cat /etc/portage/package.use/local | grep 'dev-lang/ruby mbari'" +end + +package "dev-lang/ruby-1.8.6_p287-r2" do + action :install +end \ No newline at end of file
wyhaines/ey-cloud-recipes
bf7dd83164ccae2e963e4707bab50aedc964b500
integrity works
diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb index d9f1219..01a7918 100644 --- a/cookbooks/integrity/recipes/default.rb +++ b/cookbooks/integrity/recipes/default.rb @@ -1,64 +1,64 @@ # # Cookbook Name:: integrity # Recipe:: default # # Copyright 2009, Engine Yard, Inc. # # All rights reserved - Do Not Redistribute # - require 'digest/sha1' - - gem_package 'foca-integrity-email' do - action :install - source "http://gems.github.com" - end - - gem_package 'foca-sinatra-ditties' do - action :install - source "http://gems.github.com" - end - - gem_package 'do_sqlite3' do - action :install - end - - gem_package 'integrity' do - action :install - version '0.1.9.0' - end - - -Chef::Log.info('apps: ' + node[:applications].inspect) +require 'digest/sha1' +gem_package 'foca-integrity-email' do + action :install + source "http://gems.github.com" +end - Chef::Log.info("owner: #{node[:owner_name]} pass: #{node[:owner_pass]}") +gem_package 'foca-sinatra-ditties' do + action :install + source "http://gems.github.com" +end + +gem_package 'do_sqlite3' do + action :install +end + +gem_package 'integrity' do + action :install + version '0.1.9.0' +end + node[:applications].each do |app,data| execute "install integrity" do command "integrity install --passenger /data/#{app}/current" end template "/data/#{app}/current/config.ru" do owner node[:owner_name] group node[:owner_name] mode 0655 source "config.ru.erb" end template "/data/#{app}/current/config.yml" do owner node[:owner_name] group node[:owner_name] mode 0655 source "config.yml.erb" variables({ :app => app, :domain => data[:vhosts].first[:name], }) end end + +execute "restart-apache" do + command "/etc/init.d/apache2 restart" + action :run +end \ No newline at end of file diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 15a6a2a..1cb97d8 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,9 +1,11 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe # require_recipe "couchdb" -require_recipe "integrity" \ No newline at end of file + +# uncomment to turn your instance into an integrity CI server +#require_recipe "integrity" \ No newline at end of file
wyhaines/ey-cloud-recipes
62de9093c0cf4614af94e9c61356bb3d68a366bb
another fix
diff --git a/cookbooks/main/attributes/recipe.rb b/cookbooks/main/attributes/recipe.rb index 11e0a50..9d52e2c 100644 --- a/cookbooks/main/attributes/recipe.rb +++ b/cookbooks/main/attributes/recipe.rb @@ -1 +1,3 @@ -recipes('main') \ No newline at end of file +recipes('main') +owner_name(@attribute[:users].first[:username]) +owner_pass(@attribute[:users].first[:password]) \ No newline at end of file
wyhaines/ey-cloud-recipes
26ce729ccd6d2543ed9c425961ca662e40b41e34
another fix
diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb index a8a3acf..d9f1219 100644 --- a/cookbooks/integrity/recipes/default.rb +++ b/cookbooks/integrity/recipes/default.rb @@ -1,56 +1,64 @@ # # Cookbook Name:: integrity # Recipe:: default # # Copyright 2009, Engine Yard, Inc. # # All rights reserved - Do Not Redistribute # require 'digest/sha1' gem_package 'foca-integrity-email' do action :install source "http://gems.github.com" end gem_package 'foca-sinatra-ditties' do action :install source "http://gems.github.com" end gem_package 'do_sqlite3' do action :install end gem_package 'integrity' do action :install version '0.1.9.0' end + +Chef::Log.info('apps: ' + node[:applications].inspect) + + + Chef::Log.info("owner: #{node[:owner_name]} pass: #{node[:owner_pass]}") + node[:applications].each do |app,data| + + execute "install integrity" do command "integrity install --passenger /data/#{app}/current" end template "/data/#{app}/current/config.ru" do owner node[:owner_name] group node[:owner_name] mode 0655 source "config.ru.erb" end template "/data/#{app}/current/config.yml" do owner node[:owner_name] group node[:owner_name] mode 0655 source "config.yml.erb" variables({ :app => app, :domain => data[:vhosts].first[:name], }) end end
wyhaines/ey-cloud-recipes
d9e5de7f88c7e528ce05f2b5540e787f1ee757e2
integrity
diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb index 703380d..a8a3acf 100644 --- a/cookbooks/integrity/recipes/default.rb +++ b/cookbooks/integrity/recipes/default.rb @@ -1,60 +1,56 @@ # # Cookbook Name:: integrity # Recipe:: default # # Copyright 2009, Engine Yard, Inc. # # All rights reserved - Do Not Redistribute # -if any_app_needs_recipe?('integrity') - require 'digest/sha1' gem_package 'foca-integrity-email' do action :install source "http://gems.github.com" end gem_package 'foca-sinatra-ditties' do action :install source "http://gems.github.com" end gem_package 'do_sqlite3' do action :install end gem_package 'integrity' do action :install version '0.1.9.0' end -end - -if_app_needs_recipe("integrity") do |app,data,index| +node[:applications].each do |app,data| execute "install integrity" do command "integrity install --passenger /data/#{app}/current" end template "/data/#{app}/current/config.ru" do owner node[:owner_name] group node[:owner_name] mode 0655 source "config.ru.erb" end template "/data/#{app}/current/config.yml" do owner node[:owner_name] group node[:owner_name] mode 0655 source "config.yml.erb" variables({ :app => app, :domain => data[:vhosts].first[:name], }) end end
wyhaines/ey-cloud-recipes
890c6f64a51da12d441f36f389bba5647762c3a2
integrity
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 9350d61..15a6a2a 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,8 +1,9 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe -# require_recipe "couchdb" \ No newline at end of file +# require_recipe "couchdb" +require_recipe "integrity" \ No newline at end of file
wyhaines/ey-cloud-recipes
9bb3e2e1d21defefff9d276f525e9b63f4e98b82
adding intergrity recipe
diff --git a/cookbooks/integrity/libraries/if_app_needs_recipe.rb b/cookbooks/integrity/libraries/if_app_needs_recipe.rb new file mode 100644 index 0000000..a43175f --- /dev/null +++ b/cookbooks/integrity/libraries/if_app_needs_recipe.rb @@ -0,0 +1,25 @@ +class Chef + class Recipe + def if_app_needs_recipe(recipe, &block) + index = 0 + node[:applications].map{|k,v| [k,v] }.sort_by {|a,b| a }.each do |name, app_data| + if app_data[:recipes].detect { |r| r == recipe } + Chef::Log.info("Applying Recipe: #{recipe}") + block.call(name, app_data, index) + index += 1 + end + end + end + + def any_app_needs_recipe?(recipe) + needs = false + node[:applications].each do |name, app_data| + if app_data[:recipes].detect { |r| r == recipe } + needs = true + end + end + needs + end + + end +end \ No newline at end of file diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb new file mode 100644 index 0000000..703380d --- /dev/null +++ b/cookbooks/integrity/recipes/default.rb @@ -0,0 +1,60 @@ +# +# Cookbook Name:: integrity +# Recipe:: default +# +# Copyright 2009, Engine Yard, Inc. +# +# All rights reserved - Do Not Redistribute +# + +if any_app_needs_recipe?('integrity') + + require 'digest/sha1' + + gem_package 'foca-integrity-email' do + action :install + source "http://gems.github.com" + end + + gem_package 'foca-sinatra-ditties' do + action :install + source "http://gems.github.com" + end + + gem_package 'do_sqlite3' do + action :install + end + + gem_package 'integrity' do + action :install + version '0.1.9.0' + end + +end + +if_app_needs_recipe("integrity") do |app,data,index| + + execute "install integrity" do + command "integrity install --passenger /data/#{app}/current" + end + + template "/data/#{app}/current/config.ru" do + owner node[:owner_name] + group node[:owner_name] + mode 0655 + source "config.ru.erb" + end + + template "/data/#{app}/current/config.yml" do + owner node[:owner_name] + group node[:owner_name] + mode 0655 + source "config.yml.erb" + variables({ + :app => app, + :domain => data[:vhosts].first[:name], + }) + end + +end + diff --git a/cookbooks/integrity/templates/default/config.ru.erb b/cookbooks/integrity/templates/default/config.ru.erb new file mode 100644 index 0000000..1d8f085 --- /dev/null +++ b/cookbooks/integrity/templates/default/config.ru.erb @@ -0,0 +1,19 @@ +require "rubygems" +require "integrity" + +# If you want to add any notifiers, install the gems and then require them here +# For example, to enable the Email notifier: install the gem (from github: +# +# sudo gem install -s http://gems.github.com foca-integrity-email +# +# And then uncomment the following line: +# +# require "notifier/email" + +# Load configuration and initialize Integrity +Integrity.new(File.dirname(__FILE__) + "/config.yml") + +# You probably don't want to edit anything below +Integrity::App.set :environment, ENV["RACK_ENV"] || :production + +run Integrity::App \ No newline at end of file diff --git a/cookbooks/integrity/templates/default/config.yml.erb b/cookbooks/integrity/templates/default/config.yml.erb new file mode 100644 index 0000000..cf41c5c --- /dev/null +++ b/cookbooks/integrity/templates/default/config.yml.erb @@ -0,0 +1,41 @@ +# Domain where integrity will be running from. This is used to have +# nice URLs in your notifications. +# For example: +# http://builder.integrityapp.com +:base_uri: <%= @domain %> + +# This should be a complete connection string to your database. +# +# Examples: +# * `mysql://user:password@localhost/integrity` +# * `postgres://<:password@localhost/integrity` +# * `sqlite3:///home/integrity/db/integrity.sqlite` +# +# Note: +# * The appropriate data_objects adapter must be installed (`do_mysql`, etc) +# * You must create the `integrity` database on localhost, of course. +:database_uri: sqlite3:///data/<%= @app %>/current/integrity.db + +# This is where your project's code will be checked out to. Make sure it's +# writable by the user that runs Integrity. +:export_directory: /data/<%= @app %>/current/builds + +# Path to the integrity log file +:log: /data/<%= @app %>/current/log/integrity.log + +# Enable or disable HTTP authentication for the app. BE AWARE that if you +# disable this anyone can delete and alter projects, so do it only if your +# app is running in a controlled environment (ie, behind your company's +# firewall.) +:use_basic_auth: false + +# When `use_basic_auth` is true, the admin's username for HTTP authentication. +:admin_username: <%= @node[:owner_name] %> + +# When `use_basic_auth` is true, the admin's password. Usually saved as a +# SHA1 hash. See the next option. +:admin_password: <%= Digest::SHA1.hexdigest(@node[:owner_pass]) %> + +# If this is true, then whenever we authenticate the admin user, will hash +# it using SHA1. If not, we'll assume the provided password is in plain text. +:hash_admin_password: true \ No newline at end of file
wyhaines/ey-cloud-recipes
017258faf8e5bca61e48aca2ee44114fe49d049d
commenc out couchdb recipe as an example
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 6f8c557..9350d61 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,8 +1,8 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe -require_recipe "couchdb" \ No newline at end of file +# require_recipe "couchdb" \ No newline at end of file
wyhaines/ey-cloud-recipes
0248e8cf23abe9a0af99779237fd548ff78793c1
use not_if's
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index dc5a928..7883610 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,50 +1,52 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end remote_file "/etc/init.d/couchdb" do source "couchdb" owner "root" group "root" mode 0755 end execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } + not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } + not_if "/etc/init.d/couchdb status | grep 'status: started'" end \ No newline at end of file
wyhaines/ey-cloud-recipes
7d2109cc2ac40afd42de2911c7cce75c5a6b4fd5
reenable couch
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 12f1acc..6f8c557 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,8 +1,8 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe -#require_recipe "couchdb" \ No newline at end of file +require_recipe "couchdb" \ No newline at end of file
wyhaines/ey-cloud-recipes
37c1387b9034e4851463bde1b344f3b77a8c7964
dont run couchdb by default
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 6f8c557..12f1acc 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,8 +1,8 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe -require_recipe "couchdb" \ No newline at end of file +#require_recipe "couchdb" \ No newline at end of file
wyhaines/ey-cloud-recipes
581433f502eb5999a6bdb7ca9609a02b2932e1c5
couchdb touchpus
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index 6da1407..dc5a928 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,51 +1,50 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end remote_file "/etc/init.d/couchdb" do source "couchdb" owner "root" group "root" mode 0755 end execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } - not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } end \ No newline at end of file
wyhaines/ey-cloud-recipes
730ea0e1d42d90e5ca53662d021f78fe0a965a1e
just restart couchdb on successful run
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index 5c75fab..6da1407 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,52 +1,51 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end remote_file "/etc/init.d/couchdb" do source "couchdb" owner "root" group "root" mode 0755 end execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } - not_if "/etc/init.d/couchdb status | grep 'Apache CouchDB has started. Time to relax.'" end \ No newline at end of file
wyhaines/ey-cloud-recipes
8572b9768c36a1949096558e79f6443e2c79f784
make sure couchdb is run
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 9350d61..6f8c557 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,8 +1,8 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end # uncomment if you want to run couchdb recipe -# require_recipe "couchdb" \ No newline at end of file +require_recipe "couchdb" \ No newline at end of file
wyhaines/ey-cloud-recipes
f02c31ab128f535992c5bf765b08974ef66f13a0
comment out the couchdb recipe
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index e5eb863..9350d61 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,7 +1,8 @@ execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/cheftime } end -require_recipe "couchdb" \ No newline at end of file +# uncomment if you want to run couchdb recipe +# require_recipe "couchdb" \ No newline at end of file
wyhaines/ey-cloud-recipes
24c924234a83259baaf3ee2fcef8817c03eebd53
not_if not only_if
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index c52009c..5c75fab 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,52 +1,52 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end remote_file "/etc/init.d/couchdb" do source "couchdb" owner "root" group "root" mode 0755 end execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } - only_if "/etc/init.d/couchdb status | grep 'Apache CouchDB is not running'" + not_if "/etc/init.d/couchdb status | grep 'Apache CouchDB has started. Time to relax.'" end \ No newline at end of file
wyhaines/ey-cloud-recipes
f1a634ad2a9af33d1cee03e685d67fae98934fec
set executable on the init script
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index bee35bf..c52009c 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,52 +1,52 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end remote_file "/etc/init.d/couchdb" do source "couchdb" owner "root" group "root" - mode 0644 + mode 0755 end execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } only_if "/etc/init.d/couchdb status | grep 'Apache CouchDB is not running'" end \ No newline at end of file
wyhaines/ey-cloud-recipes
a09314cce1f6ebcb1116e7a4dda41699e7f21165
use our own custom genttoified /etc/init.d/couchdb file
diff --git a/cookbooks/couchdb/files/default/couchdb b/cookbooks/couchdb/files/default/couchdb new file mode 100644 index 0000000..0e54bae --- /dev/null +++ b/cookbooks/couchdb/files/default/couchdb @@ -0,0 +1,122 @@ +#!/sbin/runscript +# Copyright 1999-2008 Gentoo Foundation +# by Gerardo Puerta Cardelles / Vicente Jimenez Aguilar +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + + +# TODO: +# * Try to use start-stop-daemon to stop the CouchDB server. +# * Change init configuration file from /etc/default/couchdb to /etc/conf.d/couchdb + +depend() { + need net + # or just use? + need localmount + after bootmisc +} + +COUCHDB=/usr/bin/couchdb + +# Gentoo doesn't have /lib/lsb +# LSB_LIBRARY=/lib/lsb/init-functions + +# Better put this file into /etc/conf.d +# +# for a second version? +CONFIGURATION_FILE=/etc/default/couchdb + + +sourceconfig() { + if test -r $CONFIGURATION_FILE + then + . $CONFIGURATION_FILE + fi +} + +checkpidfileoption() { + if test -n "$COUCHDB_PID_FILE"; then + pidfile_option="-p $COUCHDB_PID_FILE" + # Option for the start-stop-daemon (needed?) + couchdb_pidfile="--pidfile $COUCHDB_PID_FILE" + # Could be the same variable as both understand -p + # but prefered to keep then separated + fi + +} + +checkmoreoptions(){ + if test -n "$COUCHDB_USER" + then + # Option for the start-stop-daemon + couchdb_user="--chuid $COUCHDB_USER" + fi + + # Options for the $COUCHDB command + command_options="" + if test -n "$COUCHDB_INI_FILE"; then + command_options="$command_options -c $COUCHDB_INI_FILE" + fi + if test -n "$COUCHDB_STDOUT_FILE"; then + command_options="$command_options -o $COUCHDB_STDOUT_FILE" + fi + if test -n "$COUCHDB_STDERR_FILE"; then + command_options="$command_options -e $COUCHDB_STDERR_FILE" + fi + if test -n "$COUCHDB_RESPAWN_TIMEOUT"; then + command_options="$command_options -r $COUCHDB_RESPAWN_TIMEOUT" + fi +} + + +start() { + ebegin "Starting Apache CouchDB" + if test ! -x $COUCHDB + then + eend $? + fi +# Gentoo doesn't have /lib/lsb +# if test -r $LSB_LIBRARY +# then +# . $LSB_LIBRARY +# fi + + sourceconfig + checkpidfileoption + checkmoreoptions + # All options are used plus -b for the background (needed -b option?) + start-stop-daemon --start $couchdb_user $couchdb_pidfile --oknodo --exec $COUCHDB -- $pidfile_option $command_options -b + eend $? +} + +stop() { +# Imposible to use start-stop-daemon because of respawn. +# Help needed! Tried everything. +# Event sending just a -1 signal but the script respawn another instance. +# Examples of commands tried: +# start-stop-daemon --stop $couchdb_pidfile --signal 1 +# start-stop-daemon --stop --exec $COUCHDB + + ebegin "Stopping Apache CouchDB" + sourceconfig + checkpidfileoption + # Only -p option is useful when is different from default /var/run/couchdb.pid + # Added -d option for the shutdown + $COUCHDB $pidfile_option -d + eend $? +} + +status() { + sourceconfig + checkpidfileoption + # Only -p option is useful when is different from default /var/run/couchdb.pid + # added -s option for status display + $COUCHDB $pidfile_option -s + # WARNING: due to how $COUCHDB reads arguments, + # option -p needs to be put BEFORE -s because when the -s option is read, + # the script check status and exit without reading more options. + # So if we use a PID file other than the default /var/run/couchdb.pid + # and we put no -p option BEFORE the -s option + # the script always displays "Apache CouchDB is not running." as the status. +} + diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index 227a30c..bee35bf 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,45 +1,52 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end +remote_file "/etc/init.d/couchdb" do + source "couchdb" + owner "root" + group "root" + mode 0644 +end + execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } only_if "/etc/init.d/couchdb status | grep 'Apache CouchDB is not running'" end \ No newline at end of file
wyhaines/ey-cloud-recipes
6b0fb30debbb9b3e4d5517003c10ee7f3fe537aa
version not verison
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb index cfb1446..227a30c 100644 --- a/cookbooks/couchdb/recipes/default.rb +++ b/cookbooks/couchdb/recipes/default.rb @@ -1,45 +1,45 @@ # # Cookbook Name:: couchdb # Recipe:: default # package "couchdb" do - verison "0.8.1" + version "0.8.1" end directory "/db/couchdb/log" do owner "couchdb" group "couchdb" mode 0755 recursive true end template "/etc/couchdb/couch.ini" do owner 'root' group 'root' mode 0644 source "couch.ini.erb" variables({ :basedir => '/db/couchdb', :logfile => '/db/couchdb/log/couch.log', :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world :port => '5984',# change if you want to listen on another port :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo :loglevel => 'info' }) end execute "add-couchdb-to-default-run-level" do command %Q{ rc-update add couchdb default } not_if "rc-status | grep couchdb" end execute "ensure-couchdb-is-running" do command %Q{ /etc/init.d/couchdb restart } only_if "/etc/init.d/couchdb status | grep 'Apache CouchDB is not running'" end \ No newline at end of file
wyhaines/ey-cloud-recipes
f092d233047dd23dc24330f8895607996f35cff7
require_recipe 'couchdb' from main recipe
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 3725fef..e5eb863 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,5 +1,7 @@ execute "testing" do command %Q{ - echo "i ran at #{Time.now}" >> /root/yessir + echo "i ran at #{Time.now}" >> /root/cheftime } -end \ No newline at end of file +end + +require_recipe "couchdb" \ No newline at end of file
wyhaines/ey-cloud-recipes
ed9b08bf92f4db8f76c3b344b63ded9093915b68
added couchdb cookbook
diff --git a/Rakefile b/Rakefile index 8d85821..13ec65b 100644 --- a/Rakefile +++ b/Rakefile @@ -1,64 +1,42 @@ TOPDIR = File.dirname(__FILE__) desc "Test your cookbooks for syntax errors" task :test do puts "** Testing your cookbooks for syntax errors" Dir[ File.join(TOPDIR, "cookbooks", "**", "*.rb") ].each do |recipe| sh %{ruby -c #{recipe}} do |ok, res| if ! ok raise "Syntax error in #{recipe}" end end end end desc "By default, run rake test" task :default => [ :test ] desc "Create a new cookbook (with COOKBOOK=name)" task :new_cookbook do create_cookbook(File.join(TOPDIR, "cookbooks")) end def create_cookbook(dir) raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"] puts "** Creating cookbook #{ENV["COOKBOOK"]}" sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "attributes")}" sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "recipes")}" sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "definitions")}" sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "libraries")}" sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "files", "default")}" sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "templates", "default")}" unless File.exists?(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb")) open(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"), "w") do |file| file.puts <<-EOH # # Cookbook Name:: #{ENV["COOKBOOK"]} # Recipe:: default # EOH - case NEW_COOKBOOK_LICENSE - when :apachev2 - file.puts <<-EOH -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -EOH - when :none - file.puts <<-EOH -# All rights reserved - Do Not Redistribute -# -EOH - end end end end diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb new file mode 100644 index 0000000..cfb1446 --- /dev/null +++ b/cookbooks/couchdb/recipes/default.rb @@ -0,0 +1,45 @@ +# +# Cookbook Name:: couchdb +# Recipe:: default +# + +package "couchdb" do + verison "0.8.1" +end + +directory "/db/couchdb/log" do + owner "couchdb" + group "couchdb" + mode 0755 + recursive true +end + +template "/etc/couchdb/couch.ini" do + owner 'root' + group 'root' + mode 0644 + source "couch.ini.erb" + variables({ + :basedir => '/db/couchdb', + :logfile => '/db/couchdb/log/couch.log', + :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world + :port => '5984',# change if you want to listen on another port + :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root + :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo + :loglevel => 'info' + }) +end + +execute "add-couchdb-to-default-run-level" do + command %Q{ + rc-update add couchdb default + } + not_if "rc-status | grep couchdb" +end + +execute "ensure-couchdb-is-running" do + command %Q{ + /etc/init.d/couchdb restart + } + only_if "/etc/init.d/couchdb status | grep 'Apache CouchDB is not running'" +end \ No newline at end of file diff --git a/cookbooks/couchdb/templates/default/couch.ini.erb b/cookbooks/couchdb/templates/default/couch.ini.erb new file mode 100644 index 0000000..f27745a --- /dev/null +++ b/cookbooks/couchdb/templates/default/couch.ini.erb @@ -0,0 +1,21 @@ +[Couch] + +ConsoleStartupMsg=Apache CouchDB is starting. + +DbRootDir=<%= @basedir %> + +Port=<%= @port %> + +BindAddress=<%= @bind_address %> + +DocumentRoot=<%= @doc_root %> + +LogFile=<%= @logfile %> + +UtilDriverDir=<%= @driver_dir %> + +LogLevel=<%= @loglevel %> + +[Couch Query Servers] + +javascript=/usr/bin/couchjs /usr/share/couchdb/server/main.js
wyhaines/ey-cloud-recipes
fd0706457bbb5beec73939ad303ead43fb761739
fix typo
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb index 50784b3..3725fef 100644 --- a/cookbooks/main/recipes/default.rb +++ b/cookbooks/main/recipes/default.rb @@ -1,5 +1,5 @@ -eexecute "testing" do +execute "testing" do command %Q{ echo "i ran at #{Time.now}" >> /root/yessir } end \ No newline at end of file
wyhaines/ey-cloud-recipes
82384cff30c3a46ab8c916d3e3c7f96e67fc792c
use main recipe
diff --git a/cookbooks/main/attributes/recipe.rb b/cookbooks/main/attributes/recipe.rb new file mode 100644 index 0000000..11e0a50 --- /dev/null +++ b/cookbooks/main/attributes/recipe.rb @@ -0,0 +1 @@ +recipes('main') \ No newline at end of file
wyhaines/ey-cloud-recipes
0939eea826731a3adf75ea3efdeee75aa90f72fd
comit test recipe
diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..8d85821 --- /dev/null +++ b/Rakefile @@ -0,0 +1,64 @@ +TOPDIR = File.dirname(__FILE__) + +desc "Test your cookbooks for syntax errors" +task :test do + puts "** Testing your cookbooks for syntax errors" + Dir[ File.join(TOPDIR, "cookbooks", "**", "*.rb") ].each do |recipe| + sh %{ruby -c #{recipe}} do |ok, res| + if ! ok + raise "Syntax error in #{recipe}" + end + end + end +end + +desc "By default, run rake test" +task :default => [ :test ] + +desc "Create a new cookbook (with COOKBOOK=name)" +task :new_cookbook do + create_cookbook(File.join(TOPDIR, "cookbooks")) +end + +def create_cookbook(dir) + raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"] + puts "** Creating cookbook #{ENV["COOKBOOK"]}" + sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "attributes")}" + sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "recipes")}" + sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "definitions")}" + sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "libraries")}" + sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "files", "default")}" + sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "templates", "default")}" + unless File.exists?(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb")) + open(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"), "w") do |file| + file.puts <<-EOH +# +# Cookbook Name:: #{ENV["COOKBOOK"]} +# Recipe:: default +# +EOH + case NEW_COOKBOOK_LICENSE + when :apachev2 + file.puts <<-EOH +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +EOH + when :none + file.puts <<-EOH +# All rights reserved - Do Not Redistribute +# +EOH + end + end + end +end diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb new file mode 100644 index 0000000..bc1e757 --- /dev/null +++ b/cookbooks/main/recipes/default.rb @@ -0,0 +1,5 @@ +execute "testing" do + command %Q{ + echo "i ran at #{Time.now}" >> /root/yessir + } +end \ No newline at end of file
ericgj/rmu-alarmclock
cbdd55f927932daab15c146203e0cbf04f534373
more minor corrections to phase1/README
diff --git a/phase1/README.markdown b/phase1/README.markdown index 3ae0abb..e0423e0 100755 --- a/phase1/README.markdown +++ b/phase1/README.markdown @@ -1,37 +1,37 @@ ## Eventmachine implementation This is the first stage of the project, the Eventmachine implementation. For explanation, see [http://github.com/ericgj/rmu-alarmclock/blob/master/ROADMAP.markdown](ROADMAP) ### How to run the tests -First make sure you have all the necessary gems: `bundle update` +First make sure you have all the necessary gems. Go to the project root (not 'phase1', but the level above). Run `bundle update`. -Then from the project root, `rake test:em:all`. Or `rake test:em:unit` to run unit tests, `rake test:em:functional` for functional tests. +Then from the 'phase1' root, `rake`. Or `rake test:unit` to run unit tests, `rake test:functional` for functional tests. For an explanation of what unit and functional tests are all about in the context of this project, see README files under spec/em/unit and spec/em/functional. -Note the tests aren't that thorough (as of Sept 19), and need to be revised for the latest set of changes. +Note the tests aren't that thorough (as of Sept 21). ### How to run the app -(as of Sept 19) +(as of Sept 21) Right now the three parts of the app (the client, server, and alarm) are launched separately. The plan is to daemonize the server and alarm components to make it easier. -Open up three bash shells and go to the project ('phase1') root. Enter these commands in two of the shells: +Open up three bash shells and go to the 'phase1' root. Enter these commands in two of the shells: bin/remindrd bin/alarmd This will start up the reminder and alarm servers. If it's the first time running, you will be prompted to set the configuration -- choose all default settings. (It will save these to the file `~/.remindr` for the next time). In the third shell, enter a command for setting the reminder. Right now the command syntax is very basic, it only accepts (1) a number of seconds to the alarm and (2) an optional message. So to set a timer for two minutes with a message, enter: bin/remindr 120 We have liftoff! In approximately two minutes, you should see the message appear in the `alarmd` shell, and it will attempt to play a sound. (You need the `esound` client and server components installed to play the sound).
ericgj/rmu-alarmclock
3b52070ddc9979824555fe743a3e5b57b29ddf42
minor fix to path to default sound file
diff --git a/phase1/lib/shared/environment.rb b/phase1/lib/shared/environment.rb index e64ef0c..2b445af 100755 --- a/phase1/lib/shared/environment.rb +++ b/phase1/lib/shared/environment.rb @@ -1,119 +1,119 @@ # load/dump environment settings from YAML module Remindr class Environment < Struct.new(:server, :client, :alarm) require 'yaml' def self.load(file = '.remindr') file = File.join(ENV['HOME'],file) opts = if file && File.exists?(file) YAML::load(open(file)) else {} end env = new(opts) env.file = file env end def initialize(hash = {}) self.server = Server.new(hash['server']) #client = Client.new(hash['client']) self.alarm = Alarm.new(hash['alarm']) end def file=(to_file) @to_file = to_file end def to_h hash = {}; hash['server'] = self.server.to_h hash['alarm'] = self.alarm.to_h hash end def configure Signal.trap("INT") { puts "Exited." } write_on_exit = false unless self.server.host && self.server.port puts "Configuring Reminder server..." unless self.server.host print "> What is the server host address or URL? [localhost] " self.server.host = gets.chomp self.server.host = 'localhost' if self.server.host.empty? write_on_exit = true end unless self.server.port print "> What is the server port? [5997] " self.server.port = gets.chomp.to_i self.server.port = 5997 if self.server.port = 0 write_on_exit = true end end unless self.alarm.host && self.alarm.port && self.alarm.sound puts "Configuring Alarm server..." unless self.alarm.host print "> What is the alarm host address or URL? [localhost] " self.alarm.host = gets.chomp self.alarm.host = 'localhost' if self.alarm.host.empty? write_on_exit = true end unless self.alarm.port print "> What is the alarm port? [5998] " self.alarm.port = gets.chomp.to_i self.alarm.port = 5998 if self.alarm.port = 0 write_on_exit = true end unless self.alarm.sound print "> What is the alarm sound file? [lib/em/rsc/ringin.wav] " self.alarm.sound = gets.chomp - self.alarm.sound = 'lib/em/rsc/ringin.wav' if self.alarm.sound.empty? + self.alarm.sound = 'rsc/ringin.wav' if self.alarm.sound.empty? write_on_exit = true end end if write_on_exit && @to_file File.open( @to_file, 'w' ) do |out| YAML.dump( to_h, out ) end end self end class Server < Struct.new(:host, :port) def initialize(hash = {}) hash ||= {} hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end def to_h hash = {} each_pair {|k, v| hash[k.to_s] = v} hash end end class Alarm < Struct.new(:host, :port, :sound) def initialize(hash = {}) hash ||= {} hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end def to_h hash = {} each_pair {|k, v| hash[k.to_s] = v} hash end end end end \ No newline at end of file
ericgj/rmu-alarmclock
d8f00af53b2f4080043fe45d68005ddef4250e02
minor fix to phase1/README
diff --git a/phase1/README.markdown b/phase1/README.markdown index c7865d7..3ae0abb 100755 --- a/phase1/README.markdown +++ b/phase1/README.markdown @@ -1,37 +1,37 @@ ## Eventmachine implementation This is the first stage of the project, the Eventmachine implementation. For explanation, see [http://github.com/ericgj/rmu-alarmclock/blob/master/ROADMAP.markdown](ROADMAP) ### How to run the tests First make sure you have all the necessary gems: `bundle update` Then from the project root, `rake test:em:all`. Or `rake test:em:unit` to run unit tests, `rake test:em:functional` for functional tests. For an explanation of what unit and functional tests are all about in the context of this project, see README files under spec/em/unit and spec/em/functional. Note the tests aren't that thorough (as of Sept 19), and need to be revised for the latest set of changes. ### How to run the app (as of Sept 19) Right now the three parts of the app (the client, server, and alarm) are launched separately. The plan is to daemonize the server and alarm components to make it easier. -Open up three bash shells and go to the project root. Enter these commands in two of the shells: +Open up three bash shells and go to the project ('phase1') root. Enter these commands in two of the shells: - lib/em/bin/remindrd - lib/em/bin/alarmd + bin/remindrd + bin/alarmd This will start up the reminder and alarm servers. If it's the first time running, you will be prompted to set the configuration -- choose all default settings. (It will save these to the file `~/.remindr` for the next time). In the third shell, enter a command for setting the reminder. Right now the command syntax is very basic, it only accepts (1) a number of seconds to the alarm and (2) an optional message. So to set a timer for two minutes with a message, enter: - lib/em/bin/remindr 120 We have liftoff! + bin/remindr 120 We have liftoff! In approximately two minutes, you should see the message appear in the `alarmd` shell, and it will attempt to play a sound. (You need the `esound` client and server components installed to play the sound).
ericgj/rmu-alarmclock
ec24ad10ac81f6f17f9dc0d56374f6161b5d496f
reorg project dirs, revise em tests to pass, add scaffolding for phase2 gem
diff --git a/Gemfile b/Gemfile index 810be7a..231c260 100755 --- a/Gemfile +++ b/Gemfile @@ -1,16 +1,21 @@ source "http://gems.rubyforge.org" group :daemon do gem 'daemons' end group :em do gem 'eventmachine' gem 'json' end +group :thin do + gem 'thin' + gem 'sinatra' +end + group :test do gem 'bacon' gem 'mocha' gem 'baconmocha' end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 95fb430..71af8b4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,24 +1,33 @@ GEM remote: http://gems.rubyforge.org/ specs: bacon (1.1.0) baconmocha (0.0.2) bacon mocha (>= 0.9.6) daemons (1.1.0) eventmachine (0.12.10) json (1.4.6) mocha (0.9.8) rake + rack (1.2.1) rake (0.8.7) + sinatra (1.0) + rack (>= 1.0) + thin (1.2.7) + daemons (>= 1.0.9) + eventmachine (>= 0.12.6) + rack (>= 1.0.0) PLATFORMS ruby DEPENDENCIES bacon baconmocha daemons eventmachine json mocha + sinatra + thin diff --git a/README.markdown b/README.markdown index 7e34301..05d56a2 100755 --- a/README.markdown +++ b/README.markdown @@ -1,30 +1,39 @@ ## Description Basically the project is a glorified alarm clock, or the 'reminder' part of a calendar application. You tell a server you have an event at a given time and/or given duration and it sends you a reminder at the point in time the event is due to start or end (or at some configurable duration before). You can snooze the reminder (for some configurable duration), or turn it off. You can have multiple reminders going at once. There are basically three components: - the 'client' which sends user event requests to - the 'server' which keeps track of when reminders are due and sends them to - the 'alarm' which notifies the user in some way and sends user 'snooze' or 'off' requests to the server The main constraints are 1. The interface for setting up reminders has to be almost as easy as turning the dial of an egg timer; 2. The communication between the client requesting a reminder and the server sending the reminder is asynchronous; 3. The alarm mechanism (on the client side) should be able to be 'obtrusive', and not necessarily run in the same process as the client program that sends reminder requests to the server; but 4. The default alarm mechanism should be something very basic that makes few assumptions about what software the client has installed. ## Interface The client interface is via command line. Examples: remindr 10 # generic reminder in 10 minutes remindr 30s # reminder in 30 seconds remindr 25 get up and stretch # message reminder remindr 10:30 walk the dog # reminder at specified time remindr --end 11pm-12:30pm meeting # reminder at end of timed event + +## Project roadmap + +I am implementing a simplified app in two different ways and comparing them, before working in more detail on the alarm mechanism and client interface. See the ROADMAP file for more details. + +### Note As of Sep 21, only the first phase (Eventmachine implementation) has been done. + +I've put in the scaffolding for the second phase but not much else. + diff --git a/Rakefile b/Rakefile deleted file mode 100755 index 6468f60..0000000 --- a/Rakefile +++ /dev/null @@ -1,33 +0,0 @@ -$LOAD_PATH << File.expand_path(File.dirname(__FILE__)) - -namespace :test do - - task :setup do - require 'rubygems' - require 'bundler' - Bundler.setup(:test) - require 'bacon' - #Bacon.extend Bacon::TestUnitOutput - Bacon.summary_on_exit - end - - namespace :em do - - task :unit => ['test:setup'] do - puts "-----------------------\nUnit tests\n-----------------------" - Dir['spec/em/unit/**/*.rb'].each {|f| load f; puts "-----"} - end - - task :functional => ['test:setup'] do - puts "-----------------------\nFunctional tests\n-----------------------" - Dir['spec/em/functional/**/*.rb'].each {|f| load f; puts "-----"} - end - - task :all => ['test:setup'] do - Rake::Task['test:em:unit'].execute - Rake::Task['test:em:functional'].execute - end - - end - -end diff --git a/lib/em/README.markdown b/phase1/README.markdown similarity index 100% rename from lib/em/README.markdown rename to phase1/README.markdown diff --git a/phase1/Rakefile b/phase1/Rakefile new file mode 100755 index 0000000..d4154e2 --- /dev/null +++ b/phase1/Rakefile @@ -0,0 +1,31 @@ +$LOAD_PATH << File.expand_path(File.dirname(__FILE__)) + +task :default => ['test:all'] + +namespace :test do + + task :setup do + require 'rubygems' + require 'bundler' + Bundler.setup(:test) + require 'bacon' + #Bacon.extend Bacon::TestUnitOutput + Bacon.summary_on_exit + end + + task :unit => ['test:setup'] do + puts "-----------------------\nUnit tests\n-----------------------" + Dir['spec/unit/**/*.rb'].each {|f| load f; puts "-----"} + end + + task :functional => ['test:setup'] do + puts "-----------------------\nFunctional tests\n-----------------------" + Dir['spec/functional/**/*.rb'].each {|f| load f; puts "-----"} + end + + task :all => ['test:setup'] do + Rake::Task['test:unit'].execute + Rake::Task['test:functional'].execute + end + +end diff --git a/lib/em/bin/alarmd b/phase1/bin/alarmd similarity index 100% rename from lib/em/bin/alarmd rename to phase1/bin/alarmd diff --git a/lib/em/bin/remindr b/phase1/bin/remindr similarity index 100% rename from lib/em/bin/remindr rename to phase1/bin/remindr diff --git a/lib/em/bin/remindrd b/phase1/bin/remindrd similarity index 100% rename from lib/em/bin/remindrd rename to phase1/bin/remindrd diff --git a/lib/em/em_alarm.rb b/phase1/em_alarm.rb similarity index 100% rename from lib/em/em_alarm.rb rename to phase1/em_alarm.rb diff --git a/lib/em/em_client.rb b/phase1/em_client.rb similarity index 100% rename from lib/em/em_client.rb rename to phase1/em_client.rb diff --git a/lib/em/em_server.rb b/phase1/em_server.rb similarity index 100% rename from lib/em/em_server.rb rename to phase1/em_server.rb diff --git a/lib/em/lib/alarm/simple_alarm_server.rb b/phase1/lib/alarm/simple_alarm_server.rb similarity index 100% rename from lib/em/lib/alarm/simple_alarm_server.rb rename to phase1/lib/alarm/simple_alarm_server.rb diff --git a/lib/em/lib/client/cli.rb b/phase1/lib/client/cli.rb similarity index 100% rename from lib/em/lib/client/cli.rb rename to phase1/lib/client/cli.rb diff --git a/lib/em/lib/server/app.rb.old b/phase1/lib/server/app.rb.old similarity index 100% rename from lib/em/lib/server/app.rb.old rename to phase1/lib/server/app.rb.old diff --git a/lib/em/lib/server/reminder_server.rb b/phase1/lib/server/reminder_server.rb similarity index 100% rename from lib/em/lib/server/reminder_server.rb rename to phase1/lib/server/reminder_server.rb diff --git a/lib/em/lib/server/simple_alarm_client.rb.old b/phase1/lib/server/simple_alarm_client.rb.old similarity index 100% rename from lib/em/lib/server/simple_alarm_client.rb.old rename to phase1/lib/server/simple_alarm_client.rb.old diff --git a/lib/em/lib/shared/environment.rb b/phase1/lib/shared/environment.rb similarity index 100% rename from lib/em/lib/shared/environment.rb rename to phase1/lib/shared/environment.rb diff --git a/lib/em/lib/shared/json_client.rb b/phase1/lib/shared/json_client.rb similarity index 100% rename from lib/em/lib/shared/json_client.rb rename to phase1/lib/shared/json_client.rb diff --git a/lib/em/lib/shared/json_server.rb b/phase1/lib/shared/json_server.rb similarity index 100% rename from lib/em/lib/shared/json_server.rb rename to phase1/lib/shared/json_server.rb diff --git a/lib/em/lib/shared/reminder.rb b/phase1/lib/shared/reminder.rb similarity index 100% rename from lib/em/lib/shared/reminder.rb rename to phase1/lib/shared/reminder.rb diff --git a/lib/em/lib/shared/reminder_response.rb b/phase1/lib/shared/reminder_response.rb similarity index 100% rename from lib/em/lib/shared/reminder_response.rb rename to phase1/lib/shared/reminder_response.rb diff --git a/lib/em/rsc/ringin.wav b/phase1/rsc/ringin.wav similarity index 100% rename from lib/em/rsc/ringin.wav rename to phase1/rsc/ringin.wav diff --git a/spec/em/functional/README.markdown b/phase1/spec/functional/README.markdown similarity index 100% rename from spec/em/functional/README.markdown rename to phase1/spec/functional/README.markdown diff --git a/spec/em/functional/cli_functional_spec.rb b/phase1/spec/functional/cli_functional_spec.rb similarity index 76% rename from spec/em/functional/cli_functional_spec.rb rename to phase1/spec/functional/cli_functional_spec.rb index de68018..be50b3e 100755 --- a/spec/em/functional/cli_functional_spec.rb +++ b/phase1/spec/functional/cli_functional_spec.rb @@ -1,33 +1,32 @@ -require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/em_client' +require 'em_client' # Note: actual EM reactor run, dummy server listening on socket (on separate thread) -describe 'CLI', 'run' do +describe Remindr::CLI, 'run' do describe 'when server is listening' do before do @server_thread = EmSpecHelper.start_server_thread( EmSpecHelper::DummyServer, 'localhost', 8888 ) end after do EmSpecHelper.stop_server_thread(@server_thread) end it 'should run without errors' do @client_thread = Thread.current EM.run { - EM.next_tick { CLI.run('localhost', 8888) } + EM.next_tick { Remindr::CLI.run('localhost', 8888) } @client_thread.wakeup true.should.eql true } end end end diff --git a/spec/em/functional/reminder_server_functional_spec.rb b/phase1/spec/functional/reminder_server_functional_spec.rb similarity index 86% rename from spec/em/functional/reminder_server_functional_spec.rb rename to phase1/spec/functional/reminder_server_functional_spec.rb index a062e2f..d0d3f2f 100755 --- a/spec/em/functional/reminder_server_functional_spec.rb +++ b/phase1/spec/functional/reminder_server_functional_spec.rb @@ -1,62 +1,61 @@ -require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/em_server' +require 'em_server' -describe 'ReminderServer', 'receives valid command' do +describe Remindr::Server, 'receives valid command' do it 'should throw reminder near the specified time (3 sec)' do @host = 'localhost'; @port = 8888 @start_time = Time.now @reminder = Reminder.new({"start_at" => @start_time + 3}) @th = Thread.current EM.run { - ReminderServer.start(@host, @port) do |server| + Remindr::Server.start(@host, @port) do |server| server.each_reminder do |r| @th.wakeup now = Time.now r.should.eql @reminder $stdout.print "\n Note: reminder received in #{now - @start_time} seconds.\n" $stdout.flush now.should. satisfy("Not near specified time (delta=#{now - @reminder.start_at}") do |t| (t - @reminder.start_at).between?(-0.1, 0.1) end EM.next_tick { EM.stop } end server.unparseable_message do |cmd| @th.wakeup should.flunk "Received unparseable: #{cmd}" EM.next_tick { EM.stop } end server.invalid_message do |msg| @th.wakeup should.flunk "Received invalid: #{msg}" EM.next_tick { EM.stop } end end # sends data on a different thread and disconnects, # mimicking an EM reactor running in a separate process EmSpecHelper.start_connect_thread( EmSpecHelper::DummyClient, @host, @port, @reminder.to_json + "\n\r" ) } #### Note this not needed -- thread is killed when EM.stop # EmSpecHelper.stop_connect_thread(@th) end end \ No newline at end of file diff --git a/spec/em/helper.rb b/phase1/spec/helper.rb similarity index 51% rename from spec/em/helper.rb rename to phase1/spec/helper.rb index 34e4111..0cd4f35 100755 --- a/spec/em/helper.rb +++ b/phase1/spec/helper.rb @@ -1,7 +1,12 @@ +$LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__),"..")) + +require 'baconmocha' +Bacon.summary_on_exit + Bundler.setup(:em) require 'eventmachine' require 'json' require 'json/add/core' Dir[File.expand_path(File.join(File.dirname(__FILE__),'shared','**','*.rb'))]. each {|f| require f} \ No newline at end of file diff --git a/spec/em/shared/em_spec_helper.rb b/phase1/spec/shared/em_spec_helper.rb similarity index 100% rename from spec/em/shared/em_spec_helper.rb rename to phase1/spec/shared/em_spec_helper.rb diff --git a/spec/em/unit/README.markdown b/phase1/spec/unit/README.markdown similarity index 100% rename from spec/em/unit/README.markdown rename to phase1/spec/unit/README.markdown diff --git a/spec/em/unit/cli_spec.rb b/phase1/spec/unit/cli_spec.rb similarity index 76% rename from spec/em/unit/cli_spec.rb rename to phase1/spec/unit/cli_spec.rb index da86173..981f341 100755 --- a/spec/em/unit/cli_spec.rb +++ b/phase1/spec/unit/cli_spec.rb @@ -1,59 +1,58 @@ -require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/em_client' +require 'em_client' # Note: No EM reactor needed describe 'CLI', 'parse' do describe 'when no arguments' do end describe 'when 1 argument' do end describe 'when 2 arguments' do end describe 'when 3 arguments' do end end # Note: EM reactor stubbed -describe 'CLI::ReminderClient' do +describe Remindr::CLI::ReminderClient do before do @reminder = Reminder.new end it 'it should call send_data with the initial data in post_init' do @subject = EmSpecHelper.stub_connection( - CLI::ReminderClient, @reminder, + Remindr::CLI::ReminderClient, @reminder, :stubs => Proc.new { |stub| stub.expects(:send_data).with(@reminder.to_json + "\n\r").once } ) end it 'it should call close_connection_after_writing in post_init' do @subject = EmSpecHelper.stub_connection( - CLI::ReminderClient, @reminder, + Remindr::CLI::ReminderClient, @reminder, :stubs => :close_connection_after_writing ) end it 'should stop the EM reactor when unbinding' do @subject = EmSpecHelper.stub_connection( - CLI::ReminderClient, @reminder + Remindr::CLI::ReminderClient, @reminder ) { |conn| EM.expects(:stop); conn.unbind } end end diff --git a/spec/em/unit/reminder_server_spec.rb b/phase1/spec/unit/reminder_server_spec.rb similarity index 69% rename from spec/em/unit/reminder_server_spec.rb rename to phase1/spec/unit/reminder_server_spec.rb index 0c77c07..dc156e1 100755 --- a/spec/em/unit/reminder_server_spec.rb +++ b/phase1/spec/unit/reminder_server_spec.rb @@ -1,76 +1,83 @@ -require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/em_server' +require 'em_server' -# stub EM.add_timer -module EventMachine - def self.add_timer(sec, &blk) - sleep(sec); blk.call - end -end -describe 'ReminderServer', 'receives valid command' do +describe Remindr::Server, 'receives valid command' do + before do + # stub EM.add_timer block + module EventMachine + def self.add_timer(sec, &blk) + sleep(sec); blk.call + end + end + end + + after do + # reset EventMachine + load 'eventmachine.rb' + end + it 'should throw each_reminder with reminder matching received message' do @reminder = Reminder.new({'start_at' => Time.now + 1}) - EmSpecHelper.stub_connection(ReminderServer) do |conn| + EmSpecHelper.stub_connection(Remindr::Server) do |conn| conn.each_reminder do |r| r.should.not.be.nil r.each_pair {|k, v| v.should.eql @reminder[k]} end conn.unparseable_message do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| should.flunk "Invalid message: #{msg}" end conn.receive_data(@reminder.to_json + "\n\r") end end end -describe 'ReminderServer', 'receives unparseable command' do +describe Remindr::Server, 'receives unparseable command' do it 'should throw unparseable_command with message' do @reminder = {'hello' => 'world', 'unparseable' => 'message', 'created_at' => Time.now}.to_json - EmSpecHelper.stub_connection(ReminderServer) do |conn| + EmSpecHelper.stub_connection(Remindr::Server) do |conn| conn.each_reminder do |r| should.flunk "Command parsed: #{r.to_json}" end conn.unparseable_message do |cmd| cmd.chomp.should.eql @reminder.chomp end conn.invalid_message do |msg| should.flunk "Command unparseable: #{cmd}" end conn.receive_data(@reminder + "\n\r") end end end -describe 'ReminderServer', 'receives invalid message format' do +describe Remindr::Server, 'receives invalid message format' do it 'should throw invalid_message with message' do @reminder = "invalid message" - EmSpecHelper.stub_connection(ReminderServer) do |conn| + EmSpecHelper.stub_connection(Remindr::Server) do |conn| conn.each_reminder do |r| should.flunk "Command parsed: #{r.to_json}" end conn.unparseable_message do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| msg.chomp.should.eql @reminder.chomp end conn.receive_data(@reminder + "\n\r") end end end diff --git a/spec/em/unit/reminder_spec.rb b/phase1/spec/unit/reminder_spec.rb similarity index 100% rename from spec/em/unit/reminder_spec.rb rename to phase1/spec/unit/reminder_spec.rb diff --git a/phase2/remindrd b/phase2/remindrd new file mode 160000 index 0000000..ace0803 --- /dev/null +++ b/phase2/remindrd @@ -0,0 +1 @@ +Subproject commit ace080377e02f7699b5317cc9ebcec7ec5d22f08 diff --git a/spec/helper.rb b/spec/helper.rb deleted file mode 100755 index c062950..0000000 --- a/spec/helper.rb +++ /dev/null @@ -1,10 +0,0 @@ -$LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__),"..")) - -#### this should be done from rake task -#require 'rubygems' -#require 'bundler' -#Bundler.setup(:test) -#require 'bacon' - -require 'baconmocha' -Bacon.summary_on_exit
ericgj/rmu-alarmclock
de8ce8282de67ec7f1803bb6cb500b7164ceaaf0
working EM implementation (previous commit); updated main README
diff --git a/ROADMAP.markdown b/ROADMAP.markdown index 7fe3ca6..e4ce16d 100755 --- a/ROADMAP.markdown +++ b/ROADMAP.markdown @@ -1,14 +1,16 @@ ## Roadmap **The first stage** of this project I want to do is a simple implementation of all three parts of the app: client, server, and alarm, using straight Eventmachine. By simple I mean: - The most basic form of the command - No mechanism for snoozing/offing alarms +### As of Sept 19, the first stage is mostly completed. See lib/em/README for more details. + **The second stage** of the project is to re-do the app as a 'skinny daemon'. **The third stage** of the project is to evaluate the two implementations and to integrate Growl into one or the other as the alarm/snoozing mechanism. **The fourth stage** is to refine the command syntax. \ No newline at end of file
ericgj/rmu-alarmclock
55dd18e40a04f7bf900566ef08b723dc14e58729
draft simple alarm server that plays sound; reminder server now sets both start and end reminders if appropriate
diff --git a/lib/em/lib/alarm/simple_alarm_server.rb b/lib/em/lib/alarm/simple_alarm_server.rb index e69de29..2b425be 100755 --- a/lib/em/lib/alarm/simple_alarm_server.rb +++ b/lib/em/lib/alarm/simple_alarm_server.rb @@ -0,0 +1,19 @@ + +module SimpleAlarmServer + include EM::Protocols::JSON::Simple + + def self.start(host, port, &blk) + EM.start_server(host, port, self, &blk) + end + + def receive_message msg + play_sound + end + + protected + + def play_sound + `esdcat "#{APPENV.alarm_file}"` + end + +end diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb index 5da5aa2..46fdcd7 100755 --- a/lib/em/lib/server/reminder_server.rb +++ b/lib/em/lib/server/reminder_server.rb @@ -1,34 +1,44 @@ module ReminderServer include EM::Protocols::JSON::Simple def self.start(host, port, &blk) EM.start_server(host, port, self, &blk) end def each_reminder(&blk) @each_reminder_callback = blk end def parse line Reminder.new(JSON.parse(line)) end def receive_message msg schedule(msg) end protected def schedule reminder - d = [reminder.seconds_remaining, 0.1].max + d0 = reminder.seconds_remaining_to_start + d1 = reminder.seconds_remaining + if @each_reminder_callback - EM.add_timer(d) do + + # note only set 'start' reminder if start time hasn't passed + EM.add_timer(d0) do + @each_reminder_callback.call(reminder) + end if d0 > 0 + + # if end time has passed, set end reminder immediately (0.01 sec) + EM.add_timer([d1, 0.01].max) do @each_reminder_callback.call(reminder) end + end end end diff --git a/lib/em/lib/shared/reminder.rb b/lib/em/lib/shared/reminder.rb index 93b92ab..525d919 100755 --- a/lib/em/lib/shared/reminder.rb +++ b/lib/em/lib/shared/reminder.rb @@ -1,31 +1,45 @@ require 'json' require 'json/add/core' class Reminder < Struct.new(:created_at, :start_at, :duration, :message, :timer_id) DEFAULT = { 'duration' => 0, 'message' => 'Here\'s your wake-up call!!' } + def seconds_remaining_to_start + Time.now - start_at + end + def seconds_remaining duration - (Time.now - start_at) end + def state + if seconds_remaining < 0 + :expired + elsif seconds_remaining_to_start < 0 + :started + else + :created + end + end + def initialize(hash = {}) hash = hash.merge(DEFAULT) hash['created_at'] ||= Time.now hash['start_at'] ||= hash['created_at'] hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end def to_h hash = {} each_pair {|k, v| hash[k] = v} hash end def to_json to_h.to_json end end
ericgj/rmu-alarmclock
9e71afb60136ee953a73c3d0f0605d922ff4a611
refactored reminder_server to extract out common JSON message handling into shared/json_server; updated specs
diff --git a/Rakefile b/Rakefile index 750b968..5785b6c 100755 --- a/Rakefile +++ b/Rakefile @@ -1,28 +1,28 @@ $LOAD_PATH << File.expand_path(File.dirname(__FILE__)) namespace :test do task :setup do require 'rubygems' require 'bundler' Bundler.setup(:test) require 'bacon' #Bacon.extend Bacon::TestUnitOutput Bacon.summary_on_exit end namespace :em do task :unit => ['test:setup'] do puts "-----------------------\nUnit tests\n-----------------------" Dir['spec/em/unit/**/*.rb'].each {|f| load f; puts "-----"} end task :functional => ['test:setup'] do - puts "-----------------------\nUnit tests\n-----------------------" + puts "-----------------------\nFunctional tests\n-----------------------" Dir['spec/em/functional/**/*.rb'].each {|f| load f; puts "-----"} end end end diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb index 01d3271..2dd6915 100755 --- a/lib/em/em_server.rb +++ b/lib/em/em_server.rb @@ -1,12 +1,13 @@ require 'rubygems' require "bundler" Bundler.setup(:em) require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder') require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder_response') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'json_server') require File.join(File.dirname(__FILE__),'lib', 'shared', 'environment') require File.join(File.dirname(__FILE__),'lib', 'server', 'reminder_server') require File.join(File.dirname(__FILE__),'lib', 'server', 'simple_alarm_client') #### probably the app should be run within a daemon #### in bin/remindrd # require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb index c1e1306..5da5aa2 100755 --- a/lib/em/lib/server/reminder_server.rb +++ b/lib/em/lib/server/reminder_server.rb @@ -1,66 +1,34 @@ -require 'eventmachine' -require 'json' -require 'json/add/core' - module ReminderServer + include EM::Protocols::JSON::Simple def self.start(host, port, &blk) EM.start_server(host, port, self, &blk) end - - def post_init - @buffer = BufferedTokenizer.new("\r") - end - - def unparseable_command(&blk) - @unparseable_command_callback = blk - end - - def invalid_message(&blk) - @invalid_message_callback = blk - end - + def each_reminder(&blk) @each_reminder_callback = blk end - - def receive_data data - @buffer.extract(data).each do |line| - receive_line line - end - end - - protected - - def receive_line line - if line[0,1] == '{' - begin - schedule(parse(line)) - rescue - @unparseable_command_callback.call(line) \ - if @unparseable_command_callback - end - else - @invalid_message_callback.call(line) \ - if @invalid_message_callback - end + def parse line + Reminder.new(JSON.parse(line)) end - def parse msg - Reminder.new(JSON.parse(msg)) + def receive_message msg + schedule(msg) end + protected + def schedule reminder d = [reminder.seconds_remaining, 0.1].max if @each_reminder_callback EM.add_timer(d) do @each_reminder_callback.call(reminder) end end end end diff --git a/lib/em/lib/shared/json_server.rb b/lib/em/lib/shared/json_server.rb new file mode 100755 index 0000000..da525e9 --- /dev/null +++ b/lib/em/lib/shared/json_server.rb @@ -0,0 +1,63 @@ +require 'eventmachine' +require 'json' +require 'json/add/core' + +# This is a generic EM server for handling simple JSON messages +# with no header lines. +# Subclasses define #receive_message for parsed message handling +# and can also override the basic JSON parse. + +module EM +module Protocols +module JSON +module Simple + + def post_init + @buffer = BufferedTokenizer.new("\r") + end + + def unparseable_message(&blk) + @unparseable_message_callback = blk + end + + def invalid_message(&blk) + @invalid_message_callback = blk + end + + def receive_data data + @buffer.extract(data).each do |line| + receive_line line + end + end + + # callback defined in subclass + def receive_message(msg) + end + + # default parse is the standard JSON parse + def parse line + JSON.parse(line) + end + + protected + + def receive_line line + if line[0,1] == '{' + begin + receive_message parse(line) + rescue + @unparseable_message_callback.call(line) \ + if @unparseable_message_callback + end + else + @invalid_message_callback.call(line) \ + if @invalid_message_callback + end + end + +end +end +end +end + + diff --git a/spec/em/functional/cli_functional_spec.rb b/spec/em/functional/cli_functional_spec.rb index 6c8a4b6..de68018 100755 --- a/spec/em/functional/cli_functional_spec.rb +++ b/spec/em/functional/cli_functional_spec.rb @@ -1,33 +1,33 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_client' # Note: actual EM reactor run, dummy server listening on socket (on separate thread) describe 'CLI', 'run' do describe 'when server is listening' do before do @server_thread = EmSpecHelper.start_server_thread( EmSpecHelper::DummyServer, - 'localhost', 5544 + 'localhost', 8888 ) end after do EmSpecHelper.stop_server_thread(@server_thread) end it 'should run without errors' do @client_thread = Thread.current EM.run { - EM.next_tick { CLI.run('localhost', 5544) } + EM.next_tick { CLI.run('localhost', 8888) } @client_thread.wakeup true.should.eql true } end end end diff --git a/spec/em/functional/reminder_server_functional_spec.rb b/spec/em/functional/reminder_server_functional_spec.rb index b672cbb..a062e2f 100755 --- a/spec/em/functional/reminder_server_functional_spec.rb +++ b/spec/em/functional/reminder_server_functional_spec.rb @@ -1,62 +1,62 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_server' describe 'ReminderServer', 'receives valid command' do it 'should throw reminder near the specified time (3 sec)' do - @host = 'localhost'; @port = 5544 + @host = 'localhost'; @port = 8888 @start_time = Time.now @reminder = Reminder.new({"start_at" => @start_time + 3}) @th = Thread.current EM.run { ReminderServer.start(@host, @port) do |server| server.each_reminder do |r| @th.wakeup now = Time.now r.should.eql @reminder $stdout.print "\n Note: reminder received in #{now - @start_time} seconds.\n" $stdout.flush now.should. satisfy("Not near specified time (delta=#{now - @reminder.start_at}") do |t| (t - @reminder.start_at).between?(-0.1, 0.1) end EM.next_tick { EM.stop } end - server.unparseable_command do |cmd| + server.unparseable_message do |cmd| @th.wakeup should.flunk "Received unparseable: #{cmd}" EM.next_tick { EM.stop } end server.invalid_message do |msg| @th.wakeup should.flunk "Received invalid: #{msg}" EM.next_tick { EM.stop } end end # sends data on a different thread and disconnects, # mimicking an EM reactor running in a separate process EmSpecHelper.start_connect_thread( EmSpecHelper::DummyClient, @host, @port, @reminder.to_json + "\n\r" ) } #### Note this not needed -- thread is killed when EM.stop # EmSpecHelper.stop_connect_thread(@th) end end \ No newline at end of file diff --git a/spec/em/unit/reminder_server_spec.rb b/spec/em/unit/reminder_server_spec.rb index cf01f63..0c77c07 100755 --- a/spec/em/unit/reminder_server_spec.rb +++ b/spec/em/unit/reminder_server_spec.rb @@ -1,76 +1,76 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_server' # stub EM.add_timer module EventMachine def self.add_timer(sec, &blk) sleep(sec); blk.call end end describe 'ReminderServer', 'receives valid command' do it 'should throw each_reminder with reminder matching received message' do @reminder = Reminder.new({'start_at' => Time.now + 1}) EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| r.should.not.be.nil r.each_pair {|k, v| v.should.eql @reminder[k]} end - conn.unparseable_command do |cmd| + conn.unparseable_message do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| should.flunk "Invalid message: #{msg}" end conn.receive_data(@reminder.to_json + "\n\r") end end end describe 'ReminderServer', 'receives unparseable command' do it 'should throw unparseable_command with message' do @reminder = {'hello' => 'world', 'unparseable' => 'message', 'created_at' => Time.now}.to_json EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| should.flunk "Command parsed: #{r.to_json}" end - conn.unparseable_command do |cmd| + conn.unparseable_message do |cmd| cmd.chomp.should.eql @reminder.chomp end conn.invalid_message do |msg| should.flunk "Command unparseable: #{cmd}" end conn.receive_data(@reminder + "\n\r") end end end describe 'ReminderServer', 'receives invalid message format' do it 'should throw invalid_message with message' do @reminder = "invalid message" EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| should.flunk "Command parsed: #{r.to_json}" end - conn.unparseable_command do |cmd| + conn.unparseable_message do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| msg.chomp.should.eql @reminder.chomp end conn.receive_data(@reminder + "\n\r") end end end
ericgj/rmu-alarmclock
cf5e6b89e61db73a4f3d38330e8727076fa08b66
add Rakefile test tasks; update bundle to include daemons gem
diff --git a/Gemfile b/Gemfile index 31044fb..810be7a 100755 --- a/Gemfile +++ b/Gemfile @@ -1,16 +1,16 @@ source "http://gems.rubyforge.org" group :daemon do - gem :daemons + gem 'daemons' end group :em do gem 'eventmachine' gem 'json' end group :test do gem 'bacon' gem 'mocha' gem 'baconmocha' end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 28c74a7..95fb430 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,22 +1,24 @@ GEM remote: http://gems.rubyforge.org/ specs: bacon (1.1.0) baconmocha (0.0.2) bacon mocha (>= 0.9.6) + daemons (1.1.0) eventmachine (0.12.10) json (1.4.6) mocha (0.9.8) rake rake (0.8.7) PLATFORMS ruby DEPENDENCIES bacon baconmocha + daemons eventmachine json mocha diff --git a/Rakefile b/Rakefile index e69de29..750b968 100755 --- a/Rakefile +++ b/Rakefile @@ -0,0 +1,28 @@ +$LOAD_PATH << File.expand_path(File.dirname(__FILE__)) + +namespace :test do + + task :setup do + require 'rubygems' + require 'bundler' + Bundler.setup(:test) + require 'bacon' + #Bacon.extend Bacon::TestUnitOutput + Bacon.summary_on_exit + end + + namespace :em do + + task :unit => ['test:setup'] do + puts "-----------------------\nUnit tests\n-----------------------" + Dir['spec/em/unit/**/*.rb'].each {|f| load f; puts "-----"} + end + + task :functional => ['test:setup'] do + puts "-----------------------\nUnit tests\n-----------------------" + Dir['spec/em/functional/**/*.rb'].each {|f| load f; puts "-----"} + end + + end + +end diff --git a/lib/em/bin/remindrd b/lib/em/bin/remindrd new file mode 100755 index 0000000..e69de29 diff --git a/spec/em/functional/reminder_server_functional_spec.rb b/spec/em/functional/reminder_server_functional_spec.rb index a4c62f4..b672cbb 100755 --- a/spec/em/functional/reminder_server_functional_spec.rb +++ b/spec/em/functional/reminder_server_functional_spec.rb @@ -1,63 +1,62 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/lib/reminder' -require 'lib/em/lib/server/reminder_server' +require 'lib/em/em_server' describe 'ReminderServer', 'receives valid command' do it 'should throw reminder near the specified time (3 sec)' do @host = 'localhost'; @port = 5544 @start_time = Time.now @reminder = Reminder.new({"start_at" => @start_time + 3}) @th = Thread.current EM.run { ReminderServer.start(@host, @port) do |server| server.each_reminder do |r| @th.wakeup now = Time.now r.should.eql @reminder $stdout.print "\n Note: reminder received in #{now - @start_time} seconds.\n" $stdout.flush now.should. satisfy("Not near specified time (delta=#{now - @reminder.start_at}") do |t| (t - @reminder.start_at).between?(-0.1, 0.1) end EM.next_tick { EM.stop } end server.unparseable_command do |cmd| @th.wakeup should.flunk "Received unparseable: #{cmd}" EM.next_tick { EM.stop } end server.invalid_message do |msg| @th.wakeup should.flunk "Received invalid: #{msg}" EM.next_tick { EM.stop } end end # sends data on a different thread and disconnects, # mimicking an EM reactor running in a separate process EmSpecHelper.start_connect_thread( EmSpecHelper::DummyClient, @host, @port, @reminder.to_json + "\n\r" ) } #### Note this not needed -- thread is killed when EM.stop # EmSpecHelper.stop_connect_thread(@th) end end \ No newline at end of file diff --git a/spec/em/unit/reminder_server_spec.rb b/spec/em/unit/reminder_server_spec.rb index b5d4ec1..cf01f63 100755 --- a/spec/em/unit/reminder_server_spec.rb +++ b/spec/em/unit/reminder_server_spec.rb @@ -1,77 +1,76 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/lib/reminder' -require 'lib/em/lib/server/reminder_server' +require 'lib/em/em_server' # stub EM.add_timer module EventMachine def self.add_timer(sec, &blk) sleep(sec); blk.call end end describe 'ReminderServer', 'receives valid command' do it 'should throw each_reminder with reminder matching received message' do @reminder = Reminder.new({'start_at' => Time.now + 1}) EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| r.should.not.be.nil r.each_pair {|k, v| v.should.eql @reminder[k]} end conn.unparseable_command do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| should.flunk "Invalid message: #{msg}" end conn.receive_data(@reminder.to_json + "\n\r") end end end describe 'ReminderServer', 'receives unparseable command' do it 'should throw unparseable_command with message' do @reminder = {'hello' => 'world', 'unparseable' => 'message', 'created_at' => Time.now}.to_json EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| should.flunk "Command parsed: #{r.to_json}" end conn.unparseable_command do |cmd| cmd.chomp.should.eql @reminder.chomp end conn.invalid_message do |msg| should.flunk "Command unparseable: #{cmd}" end conn.receive_data(@reminder + "\n\r") end end end describe 'ReminderServer', 'receives invalid message format' do it 'should throw invalid_message with message' do @reminder = "invalid message" EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| should.flunk "Command parsed: #{r.to_json}" end conn.unparseable_command do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| msg.chomp.should.eql @reminder.chomp end conn.receive_data(@reminder + "\n\r") end end end
ericgj/rmu-alarmclock
3cb8446022843ef6418ca19aafae2ebe9c6841dd
reorganized proj dirs, drafted how daemons will work
diff --git a/Gemfile b/Gemfile index b444bb9..31044fb 100755 --- a/Gemfile +++ b/Gemfile @@ -1,12 +1,16 @@ source "http://gems.rubyforge.org" +group :daemon do + gem :daemons +end + group :em do gem 'eventmachine' gem 'json' end group :test do gem 'bacon' gem 'mocha' gem 'baconmocha' end \ No newline at end of file diff --git a/lib/em/bin/alarmd b/lib/em/bin/alarmd new file mode 100755 index 0000000..00c8bf6 --- /dev/null +++ b/lib/em/bin/alarmd @@ -0,0 +1,20 @@ +#!/usr/bin/env ruby + +options = { :ARGV => ARGV.split(' ') } + +require 'rubygems' +require 'bundler' +Bundle.setup(:daemons) +require 'daemons' + +require File.join(File.dirname(__FILE__),'..','em_alarm') + +Daemons.run_proc('alarmd', options) do + + Signal('INT') { EM.next_tick { EM.stop } } + + EM.run { + SimpleAlarmServer.start(APPENV.host, APPENV.port) + } + +end \ No newline at end of file diff --git a/lib/em/em_alarm.rb b/lib/em/em_alarm.rb new file mode 100755 index 0000000..1fa3ef7 --- /dev/null +++ b/lib/em/em_alarm.rb @@ -0,0 +1,7 @@ +require 'rubygems' +require "bundler" +Bundler.setup(:em) +require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder_response') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'environment') +require File.join(File.dirname(__FILE__),'lib', 'alarm', 'simple_alarm_server') diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb index 182e351..f83fb76 100755 --- a/lib/em/em_client.rb +++ b/lib/em/em_client.rb @@ -1,8 +1,7 @@ require 'rubygems' require "bundler" Bundler.setup(:em) -require File.join(File.dirname(__FILE__),'lib','reminder') -require File.join(File.dirname(__FILE__),'lib','reminder_response') -require File.join(File.dirname(__FILE__),'lib', 'client', 'simple_alarm_server') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder_response') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'environment') require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') -require File.join(File.dirname(__FILE__),'lib', 'client', 'environment') diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb index 3c4dfdc..01d3271 100755 --- a/lib/em/em_server.rb +++ b/lib/em/em_server.rb @@ -1,8 +1,12 @@ require 'rubygems' require "bundler" Bundler.setup(:em) -require File.join(File.dirname(__FILE__),'lib','reminder') -require File.join(File.dirname(__FILE__),'lib','reminder_response') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'reminder_response') +require File.join(File.dirname(__FILE__),'lib', 'shared', 'environment') require File.join(File.dirname(__FILE__),'lib', 'server', 'reminder_server') require File.join(File.dirname(__FILE__),'lib', 'server', 'simple_alarm_client') -require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file + +#### probably the app should be run within a daemon +#### in bin/remindrd +# require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/client/simple_alarm_server.rb b/lib/em/lib/alarm/simple_alarm_server.rb similarity index 100% rename from lib/em/lib/client/simple_alarm_server.rb rename to lib/em/lib/alarm/simple_alarm_server.rb diff --git a/lib/em/lib/client/environment.rb b/lib/em/lib/shared/environment.rb similarity index 100% rename from lib/em/lib/client/environment.rb rename to lib/em/lib/shared/environment.rb diff --git a/lib/em/lib/reminder.rb b/lib/em/lib/shared/reminder.rb similarity index 100% rename from lib/em/lib/reminder.rb rename to lib/em/lib/shared/reminder.rb diff --git a/lib/em/lib/reminder_response.rb b/lib/em/lib/shared/reminder_response.rb similarity index 100% rename from lib/em/lib/reminder_response.rb rename to lib/em/lib/shared/reminder_response.rb diff --git a/spec/helper.rb b/spec/helper.rb index ce822e7..c062950 100755 --- a/spec/helper.rb +++ b/spec/helper.rb @@ -1,9 +1,10 @@ $LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__),"..")) -require 'rubygems' -require 'bundler' -Bundler.setup(:test) +#### this should be done from rake task +#require 'rubygems' +#require 'bundler' +#Bundler.setup(:test) +#require 'bacon' -require 'bacon' require 'baconmocha' Bacon.summary_on_exit
ericgj/rmu-alarmclock
49961d21db27381756c125929899d0f967a52f4a
make CLI independent of the environment; draft bin/remindr; update specs to pass
diff --git a/lib/em/bin/remindr b/lib/em/bin/remindr new file mode 100755 index 0000000..97fa7d4 --- /dev/null +++ b/lib/em/bin/remindr @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby + +require File.join(File.dirname(__FILE__),'..','em_client') + +APPENV = Environment.load + +# daemonize alarm listener here if not started ? + +CLI.run(APPENV.host, APPENV.port, ARGV) \ No newline at end of file diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb index cd8cd96..182e351 100755 --- a/lib/em/em_client.rb +++ b/lib/em/em_client.rb @@ -1,6 +1,8 @@ require 'rubygems' require "bundler" Bundler.setup(:em) require File.join(File.dirname(__FILE__),'lib','reminder') require File.join(File.dirname(__FILE__),'lib','reminder_response') -require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') \ No newline at end of file +require File.join(File.dirname(__FILE__),'lib', 'client', 'simple_alarm_server') +require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') +require File.join(File.dirname(__FILE__),'lib', 'client', 'environment') diff --git a/lib/em/lib/client/cli.rb b/lib/em/lib/client/cli.rb index 8255aec..3c76667 100755 --- a/lib/em/lib/client/cli.rb +++ b/lib/em/lib/client/cli.rb @@ -1,43 +1,41 @@ -# TODO config APPENV with external file -APPENV = { 'host' => '127.0.0.1', - 'port' => 5544 - } +require 'json' +require 'json/add/core' # Usage: -# CLI.run(ARGV) +# CLI.run(host, port, ARGV) module CLI - + def self.parse(*args) h = {} h['duration'] = arg0 if (arg0 = args.shift) h['message'] = args.join(' ') unless args.empty? h['created_at'] = Time.now - msg = Reminder.new(h).to_json + msg = Reminder.new(h) end - def self.run(*args) + def self.run(host, port, *args) EM.run { - EM.connect APPENV['host'], APPENV['port'], ReminderClient, CLI.parse(*args) + EM.connect host, port, ReminderClient, CLI.parse(*args) } end module ReminderClient def initialize(reminder) - @msg = reminder + @msg = reminder.to_json + "\n\r" end def post_init send_data @msg close_connection_after_writing end def unbind EM.stop end end end diff --git a/lib/em/lib/client/environment.rb b/lib/em/lib/client/environment.rb new file mode 100755 index 0000000..df6e4c1 --- /dev/null +++ b/lib/em/lib/client/environment.rb @@ -0,0 +1 @@ +# TODO load environment settings from YAML \ No newline at end of file diff --git a/lib/em/lib/client/simple_alarm_server.rb b/lib/em/lib/client/simple_alarm_server.rb new file mode 100755 index 0000000..e69de29 diff --git a/lib/em/lib/reminder.rb b/lib/em/lib/reminder.rb index ae1a2b8..93b92ab 100755 --- a/lib/em/lib/reminder.rb +++ b/lib/em/lib/reminder.rb @@ -1,31 +1,31 @@ require 'json' require 'json/add/core' class Reminder < Struct.new(:created_at, :start_at, :duration, :message, :timer_id) DEFAULT = { 'duration' => 0, 'message' => 'Here\'s your wake-up call!!' } def seconds_remaining duration - (Time.now - start_at) end - def initialize(hash) + def initialize(hash = {}) hash = hash.merge(DEFAULT) hash['created_at'] ||= Time.now hash['start_at'] ||= hash['created_at'] hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end def to_h hash = {} each_pair {|k, v| hash[k] = v} hash end def to_json to_h.to_json end end diff --git a/spec/em/functional/cli_functional_spec.rb b/spec/em/functional/cli_functional_spec.rb index c879ad9..6c8a4b6 100755 --- a/spec/em/functional/cli_functional_spec.rb +++ b/spec/em/functional/cli_functional_spec.rb @@ -1,33 +1,33 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_client' # Note: actual EM reactor run, dummy server listening on socket (on separate thread) describe 'CLI', 'run' do describe 'when server is listening' do before do @server_thread = EmSpecHelper.start_server_thread( EmSpecHelper::DummyServer, - APPENV['host'], APPENV['port'] + 'localhost', 5544 ) end after do EmSpecHelper.stop_server_thread(@server_thread) end it 'should run without errors' do @client_thread = Thread.current EM.run { - EM.next_tick { CLI.run } + EM.next_tick { CLI.run('localhost', 5544) } @client_thread.wakeup true.should.eql true } end end end diff --git a/spec/em/unit/cli_spec.rb b/spec/em/unit/cli_spec.rb index b099fe4..da86173 100755 --- a/spec/em/unit/cli_spec.rb +++ b/spec/em/unit/cli_spec.rb @@ -1,55 +1,59 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_client' # Note: No EM reactor needed describe 'CLI', 'parse' do describe 'when no arguments' do end describe 'when 1 argument' do end describe 'when 2 arguments' do end describe 'when 3 arguments' do end end # Note: EM reactor stubbed describe 'CLI::ReminderClient' do + before do + @reminder = Reminder.new + end + it 'it should call send_data with the initial data in post_init' do @subject = EmSpecHelper.stub_connection( - CLI::ReminderClient, "data", + CLI::ReminderClient, @reminder, :stubs => Proc.new { |stub| - stub.expects(:send_data).with("data").once + stub.expects(:send_data).with(@reminder.to_json + "\n\r").once } ) end it 'it should call close_connection_after_writing in post_init' do @subject = EmSpecHelper.stub_connection( - CLI::ReminderClient, "data", + CLI::ReminderClient, @reminder, :stubs => :close_connection_after_writing ) end it 'should stop the EM reactor when unbinding' do @subject = EmSpecHelper.stub_connection( - CLI::ReminderClient, "data" + CLI::ReminderClient, @reminder ) { |conn| EM.expects(:stop); conn.unbind } end end
ericgj/rmu-alarmclock
60df45943943499c7bd60009a0344504ebc23d1b
implemented SimpleAlarmClient similar to ReminderServer, with callbacks for 'snooze' and 'off' responses from alarm; sketched ReminderResponse message format; sketched usage of this in app.
diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb index b657d90..cd8cd96 100755 --- a/lib/em/em_client.rb +++ b/lib/em/em_client.rb @@ -1,5 +1,6 @@ require 'rubygems' require "bundler" Bundler.setup(:em) require File.join(File.dirname(__FILE__),'lib','reminder') +require File.join(File.dirname(__FILE__),'lib','reminder_response') require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') \ No newline at end of file diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb index 7ade10d..3c4dfdc 100755 --- a/lib/em/em_server.rb +++ b/lib/em/em_server.rb @@ -1,6 +1,8 @@ require 'rubygems' require "bundler" Bundler.setup(:em) require File.join(File.dirname(__FILE__),'lib','reminder') +require File.join(File.dirname(__FILE__),'lib','reminder_response') require File.join(File.dirname(__FILE__),'lib', 'server', 'reminder_server') +require File.join(File.dirname(__FILE__),'lib', 'server', 'simple_alarm_client') require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/reminder.rb b/lib/em/lib/reminder.rb index 93a5ab0..ae1a2b8 100755 --- a/lib/em/lib/reminder.rb +++ b/lib/em/lib/reminder.rb @@ -1,31 +1,31 @@ require 'json' require 'json/add/core' -class Reminder < Struct.new(:created_at, :start_at, :duration, :message) +class Reminder < Struct.new(:created_at, :start_at, :duration, :message, :timer_id) DEFAULT = { 'duration' => 0, 'message' => 'Here\'s your wake-up call!!' } def seconds_remaining duration - (Time.now - start_at) end def initialize(hash) hash = hash.merge(DEFAULT) hash['created_at'] ||= Time.now hash['start_at'] ||= hash['created_at'] hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end def to_h hash = {} each_pair {|k, v| hash[k] = v} hash end def to_json to_h.to_json end end diff --git a/lib/em/lib/reminder_response.rb b/lib/em/lib/reminder_response.rb new file mode 100755 index 0000000..c93a8c2 --- /dev/null +++ b/lib/em/lib/reminder_response.rb @@ -0,0 +1,17 @@ +require 'json' +require 'json/add/core' + +#TODO + +class ReminderResponse < Struct.new(:response, :created_at, :duration, :reminder) + + def snooze + response == 'snooze' + end + + def off + response == 'off' + end + + +end \ No newline at end of file diff --git a/lib/em/lib/server/app.rb b/lib/em/lib/server/app.rb index f5007a7..e2b047f 100755 --- a/lib/em/lib/server/app.rb +++ b/lib/em/lib/server/app.rb @@ -1,34 +1,48 @@ # TODO config APPENV with external file APPENV = { 'host' => 'localhost', 'port' => 5544, 'alarm-host' => 'localhost', 'alarm-port' => 5545 } -module SimpleAlarmClient - - def initialize(reminder) - @reminder = reminder - end - - def post_init - send_data @reminder.to_json - end - -end EM.run { - server = EM.start_server(APPENV['host'], APPENV['port'], ReminderServer) - - server.unparseable_command do |cmd| - $stdout.print "Unparseable command received: `#{cmd}`\n" - $stdout.flush - end - - server.each_reminder do |reminder| - EM.connect(APPENV['alarm-host'], APPENV['alarm-port'], SimpleAlarmClient, reminder) + ReminderServer.start(APPENV['host'], APPENV['port']) do |server| + + server.each_reminder do |reminder| + + alarm = SimpleAlarmClient.connect( + APPENV['alarm-host'], APPENV['alarm-port'], + reminder + ) + + alarm.snooze do |response| + # TODO handle snooze response + # by sending new reminder that sets a periodic timer unless + # already set + end + + alarm.off do |response| + # TODO handle off response + # by setting off periodic timer identified by timer_id + end + + end + + # TODO these error conditions + # should be sent back to the client somehow? + server.unparseable_command do |cmd| + $stdout.print "Unparseable command received: `#{cmd}`\n" + $stdout.flush + end + + server.invalid_message do |msg| + $stdout.print "Invalid message received: `#{msg}`\n" + $stdout.flush + end + end } diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb index c6bdc50..c1e1306 100755 --- a/lib/em/lib/server/reminder_server.rb +++ b/lib/em/lib/server/reminder_server.rb @@ -1,66 +1,66 @@ require 'eventmachine' require 'json' require 'json/add/core' module ReminderServer - def self.start(host, port) - EM.start_server(host, port, self) + def self.start(host, port, &blk) + EM.start_server(host, port, self, &blk) end def post_init @buffer = BufferedTokenizer.new("\r") end def unparseable_command(&blk) @unparseable_command_callback = blk end def invalid_message(&blk) @invalid_message_callback = blk end def each_reminder(&blk) @each_reminder_callback = blk end def receive_data data @buffer.extract(data).each do |line| receive_line line end end protected def receive_line line if line[0,1] == '{' begin schedule(parse(line)) rescue @unparseable_command_callback.call(line) \ if @unparseable_command_callback end else @invalid_message_callback.call(line) \ if @invalid_message_callback end end def parse msg Reminder.new(JSON.parse(msg)) end def schedule reminder d = [reminder.seconds_remaining, 0.1].max if @each_reminder_callback EM.add_timer(d) do @each_reminder_callback.call(reminder) end end end end diff --git a/lib/em/lib/server/simple_alarm_client.rb b/lib/em/lib/server/simple_alarm_client.rb new file mode 100755 index 0000000..1965375 --- /dev/null +++ b/lib/em/lib/server/simple_alarm_client.rb @@ -0,0 +1,73 @@ +require 'eventmachine' +require 'json' +require 'json/add/core' + +#TODO: refactor this and ReminderServer to extract common methods +# for dealing with json messages +# +module SimpleAlarmClient + + def self.connect(host, port, reminder) + EM.connect(host, port, self, reminder) + end + + def snooze(&blk) + @snooze_callback ||= blk + end + + def off(&blk) + @off_callback ||= blk + end + + def response(&blk) + @response_callback ||= blk + end + + + def initialize(reminder) + @reminder = reminder + end + + def post_init + @buffer = BufferedTokenizer.new("\r") + send_data @reminder.to_json + end + + def receive_data data + @buffer.extract(data).each do |line| + receive_line line + end + end + + protected + + def receive_line line + if line[0,1] == '{' + begin + handle_response(parse(line)) + rescue + @unparseable_command_callback.call(line) \ + if @unparseable_command_callback + end + else + @invalid_message_callback.call(line) \ + if @invalid_message_callback + end + end + + + def parse msg + ReminderResponse.new(JSON.parse(msg)) + end + + def handle_response resp + if resp.snooze + @snooze_callback.call(resp) if @snooze_callback + elsif resp.off + @off_callback.call(resp) if @off_callback + else + @response_callback.call(resp) if @response_callback + end + end + +end \ No newline at end of file diff --git a/spec/em/functional/reminder_server_functional_spec.rb b/spec/em/functional/reminder_server_functional_spec.rb index c35e675..a4c62f4 100755 --- a/spec/em/functional/reminder_server_functional_spec.rb +++ b/spec/em/functional/reminder_server_functional_spec.rb @@ -1,51 +1,63 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/lib/reminder' require 'lib/em/lib/server/reminder_server' describe 'ReminderServer', 'receives valid command' do - it 'should throw reminder near the specified time' do + it 'should throw reminder near the specified time (3 sec)' do @host = 'localhost'; @port = 5544 @start_time = Time.now @reminder = Reminder.new({"start_at" => @start_time + 3}) @th = Thread.current EM.run { - server = ReminderServer.start(@host, @port) - - server.each_reminder do |r| - @th.wakeup - r.should.eql @reminder - @start_time.should. - satisfy('near') { |t| (Time.now - t).between?(3.1, 3.2) } - end - server.unparseable_command do |cmd| - @th.wakeup - puts "unparseable: #{cmd}" - end - - server.invalid_message do |msg| - @th.wakeup - puts "invalid: #{msg}" - end + ReminderServer.start(@host, @port) do |server| + + server.each_reminder do |r| + @th.wakeup + now = Time.now + r.should.eql @reminder + $stdout.print "\n Note: reminder received in #{now - @start_time} seconds.\n" + $stdout.flush + now.should. + satisfy("Not near specified time (delta=#{now - @reminder.start_at}") do |t| + (t - @reminder.start_at).between?(-0.1, 0.1) + end + EM.next_tick { EM.stop } + end + server.unparseable_command do |cmd| + @th.wakeup + should.flunk "Received unparseable: #{cmd}" + EM.next_tick { EM.stop } + end + + server.invalid_message do |msg| + @th.wakeup + should.flunk "Received invalid: #{msg}" + EM.next_tick { EM.stop } + end + + end + # sends data on a different thread and disconnects, # mimicking an EM reactor running in a separate process EmSpecHelper.start_connect_thread( EmSpecHelper::DummyClient, @host, @port, @reminder.to_json + "\n\r" ) } - #EmSpecHelper.stop_connect_thread(@th) + #### Note this not needed -- thread is killed when EM.stop + # EmSpecHelper.stop_connect_thread(@th) end end \ No newline at end of file diff --git a/spec/em/shared/em_spec_helper.rb b/spec/em/shared/em_spec_helper.rb index 46682fe..fcb1fad 100755 --- a/spec/em/shared/em_spec_helper.rb +++ b/spec/em/shared/em_spec_helper.rb @@ -1,173 +1,172 @@ module EmSpecHelper # This is designed to work like EM.connect -- # it mixes the module into StubConnection below instead of EM::Connection. # It does *not* run within an EM reactor. # The block passed it should set any expectations, and # then call the callbacks being tested. # These will be called (synchronously of course) after post_init. # For example, to test that close_connection is called in :receive_data: # stub_connection(MyRealClient, params) do |conn| # conn.expects(:close_connection) # conn.receive_data "200 OK" # end # # If you want to test expectations in post_init, you can pass a :stubs proc: # stub_connection(MyRealClient, params, # :stubs => Proc.new { |s| s.expects(:send_data).with("message") } # ) do |conn| # conn.receive_data "200 OK" # end # # Or more simply as an array if you don't care about parameters or return values: # stub_connection(MyRealClient, params, # :stubs => [ :send_data ] # ) do |conn| # conn.receive_data "200 OK" # end # # If you don't set any expectations, the EM::Connection methods will # simply quietly fire and return nil. # def self.stub_connection(klass, *args, &blk) Class.new(StubConnection){ include klass }.new(*args, &blk) end class StubConnection def self.new(*args) opts = args.last.is_a?(Hash) ? args.pop : {} stubs = opts[:stubs] allocate.instance_eval { # set expectations here case stubs when Symbol self.expects(stubs) when Array # expect methods stubs.each {|sym| self.expects(sym.to_sym)} when Hash # expect methods => returns stubs.each_pair {|sym, v| self.expects(sym.to_sym).returns(v)} else # define more complicated stubs in a proc stubs.call(self) if stubs.respond_to?(:call) end initialize(*args) post_init yield(self) if block_given? self } end def initialize(*args) end # stubbed methods => nil def send_data(data); nil; end def close_connection after_writing = false; nil; end def close_connection_after_writing; nil; end def proxy_incoming_to(conn,bufsize=0); nil; end def stop_proxying; nil; end def detach; nil; end def get_sock_opt level, option; nil; end def error?; nil; end def start_tls args={}; nil; end def get_peer_cert; nil; end def send_datagram data, recipient_address, recipient_port; nil; end def get_peername; nil; end def get_sockname; nil; end def get_pid; nil; end def get_status; nil; end def comm_inactivity_timeout; nil; end def comm_inactivity_timeout= value; nil; end def set_comm_inactivity_timeout value; nil; end def pending_connect_timeout; nil; end def pending_connect_timeout= value; nil; end def set_pending_connect_timeout value; nil; end def reconnect server, port; nil; end def send_file_data filename; nil; end def stream_file_data filename, args={}; nil; end def notify_readable= mode; nil; end def notify_readable?; nil; end def notify_writable= mode; nil; end def notify_writable?; nil; end def pause; nil; end def resume; nil; end def paused?; nil; end # no-op callbacks def post_init; end def receive_data data; end def connection_completed; end def ssl_handshake_completed; end def ssl_verify_peer(cert); end def unbind; end def proxy_target_unbound; end end class << self # # These are designed to run a dummy server in a separate thread # For testing within the EM reactor instead of stubbing it # def start_server_thread(klass, host, port) Thread.new { EM.run { EM.start_server(host, port, klass) } } end - def stop_thread(th) + def stop_server_thread(th) th.wakeup EM.stop end - def stop_server_thread(th); stop_thread(th); end def stop_connect_thread(th); th.wakeup; end def start_connect_thread(klass, host, port, data) Thread.new { EM.run { EM.connect(host, port, klass, data) - EM.next_tick { EM.stop } + #EM.next_tick { EM.stop } } } end end module DummyServer def initialize $stdout.print "Connection initializing\n"; $stdout.flush end def post_init $stdout.print "Connection initialized\n"; $stdout.flush end def receive_data data $stdout.print "Data received\n"; $stdout.flush close_connection end end module DummyClient def initialize(msg) @msg = msg end def post_init send_data @msg close_connection_after_writing end end end \ No newline at end of file
ericgj/rmu-alarmclock
a8a669bc93ce831807c36aa9e1f01f8f8b488cf5
drafted functional specs; reminder_server needs redoing, doesn't work right as implemented
diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb index 9207909..c6bdc50 100755 --- a/lib/em/lib/server/reminder_server.rb +++ b/lib/em/lib/server/reminder_server.rb @@ -1,62 +1,66 @@ require 'eventmachine' require 'json' require 'json/add/core' module ReminderServer + def self.start(host, port) + EM.start_server(host, port, self) + end + def post_init @buffer = BufferedTokenizer.new("\r") end def unparseable_command(&blk) @unparseable_command_callback = blk end def invalid_message(&blk) @invalid_message_callback = blk end def each_reminder(&blk) @each_reminder_callback = blk end def receive_data data @buffer.extract(data).each do |line| receive_line line end end protected def receive_line line if line[0,1] == '{' begin schedule(parse(line)) rescue @unparseable_command_callback.call(line) \ if @unparseable_command_callback end else @invalid_message_callback.call(line) \ if @invalid_message_callback end end def parse msg Reminder.new(JSON.parse(msg)) end def schedule reminder d = [reminder.seconds_remaining, 0.1].max if @each_reminder_callback EM.add_timer(d) do @each_reminder_callback.call(reminder) end end end end diff --git a/spec/em/functional/README.markdown b/spec/em/functional/README.markdown new file mode 100755 index 0000000..aa80c4d --- /dev/null +++ b/spec/em/functional/README.markdown @@ -0,0 +1,5 @@ +## Functional tests for the Eventmachine implementation + +This folder contains functional tests of client and server components under lib/em/lib. + +These test the components within an EM reactor, but in relative isolation, by providing dummy client or server components as the collaborators of the test subject. diff --git a/spec/em/functional/cli_functional_spec.rb b/spec/em/functional/cli_functional_spec.rb new file mode 100755 index 0000000..c879ad9 --- /dev/null +++ b/spec/em/functional/cli_functional_spec.rb @@ -0,0 +1,33 @@ +require File.join(File.dirname(__FILE__),'..','..','helper') +require File.join(File.dirname(__FILE__),'..','helper') + +require 'lib/em/em_client' + +# Note: actual EM reactor run, dummy server listening on socket (on separate thread) + +describe 'CLI', 'run' do + + describe 'when server is listening' do + before do + @server_thread = EmSpecHelper.start_server_thread( + EmSpecHelper::DummyServer, + APPENV['host'], APPENV['port'] + ) + end + + after do + EmSpecHelper.stop_server_thread(@server_thread) + end + + it 'should run without errors' do + @client_thread = Thread.current + EM.run { + EM.next_tick { CLI.run } + @client_thread.wakeup + true.should.eql true + } + end + end + +end + diff --git a/spec/em/functional/reminder_server_functional_spec.rb b/spec/em/functional/reminder_server_functional_spec.rb new file mode 100755 index 0000000..c35e675 --- /dev/null +++ b/spec/em/functional/reminder_server_functional_spec.rb @@ -0,0 +1,51 @@ +require File.join(File.dirname(__FILE__),'..','..','helper') +require File.join(File.dirname(__FILE__),'..','helper') + +require 'lib/em/lib/reminder' +require 'lib/em/lib/server/reminder_server' + + +describe 'ReminderServer', 'receives valid command' do + + it 'should throw reminder near the specified time' do + + @host = 'localhost'; @port = 5544 + @start_time = Time.now + @reminder = Reminder.new({"start_at" => @start_time + 3}) + + @th = Thread.current + EM.run { + server = ReminderServer.start(@host, @port) + + server.each_reminder do |r| + @th.wakeup + r.should.eql @reminder + @start_time.should. + satisfy('near') { |t| (Time.now - t).between?(3.1, 3.2) } + end + + server.unparseable_command do |cmd| + @th.wakeup + puts "unparseable: #{cmd}" + end + + server.invalid_message do |msg| + @th.wakeup + puts "invalid: #{msg}" + end + + # sends data on a different thread and disconnects, + # mimicking an EM reactor running in a separate process + EmSpecHelper.start_connect_thread( + EmSpecHelper::DummyClient, + @host, @port, + @reminder.to_json + "\n\r" + ) + + } + + #EmSpecHelper.stop_connect_thread(@th) + + end + +end \ No newline at end of file diff --git a/spec/em/shared/em_spec_helper.rb b/spec/em/shared/em_spec_helper.rb index c76a721..46682fe 100755 --- a/spec/em/shared/em_spec_helper.rb +++ b/spec/em/shared/em_spec_helper.rb @@ -1,144 +1,173 @@ module EmSpecHelper # This is designed to work like EM.connect -- # it mixes the module into StubConnection below instead of EM::Connection. # It does *not* run within an EM reactor. # The block passed it should set any expectations, and # then call the callbacks being tested. # These will be called (synchronously of course) after post_init. # For example, to test that close_connection is called in :receive_data: # stub_connection(MyRealClient, params) do |conn| # conn.expects(:close_connection) # conn.receive_data "200 OK" # end # # If you want to test expectations in post_init, you can pass a :stubs proc: # stub_connection(MyRealClient, params, # :stubs => Proc.new { |s| s.expects(:send_data).with("message") } # ) do |conn| # conn.receive_data "200 OK" # end # # Or more simply as an array if you don't care about parameters or return values: # stub_connection(MyRealClient, params, # :stubs => [ :send_data ] # ) do |conn| # conn.receive_data "200 OK" # end # # If you don't set any expectations, the EM::Connection methods will # simply quietly fire and return nil. # def self.stub_connection(klass, *args, &blk) Class.new(StubConnection){ include klass }.new(*args, &blk) end class StubConnection def self.new(*args) opts = args.last.is_a?(Hash) ? args.pop : {} stubs = opts[:stubs] allocate.instance_eval { # set expectations here case stubs when Symbol self.expects(stubs) when Array # expect methods stubs.each {|sym| self.expects(sym.to_sym)} when Hash # expect methods => returns stubs.each_pair {|sym, v| self.expects(sym.to_sym).returns(v)} else # define more complicated stubs in a proc stubs.call(self) if stubs.respond_to?(:call) end initialize(*args) post_init yield(self) if block_given? self } end def initialize(*args) end # stubbed methods => nil def send_data(data); nil; end def close_connection after_writing = false; nil; end def close_connection_after_writing; nil; end def proxy_incoming_to(conn,bufsize=0); nil; end def stop_proxying; nil; end def detach; nil; end def get_sock_opt level, option; nil; end def error?; nil; end def start_tls args={}; nil; end def get_peer_cert; nil; end def send_datagram data, recipient_address, recipient_port; nil; end def get_peername; nil; end def get_sockname; nil; end def get_pid; nil; end def get_status; nil; end def comm_inactivity_timeout; nil; end def comm_inactivity_timeout= value; nil; end def set_comm_inactivity_timeout value; nil; end def pending_connect_timeout; nil; end def pending_connect_timeout= value; nil; end def set_pending_connect_timeout value; nil; end def reconnect server, port; nil; end def send_file_data filename; nil; end def stream_file_data filename, args={}; nil; end def notify_readable= mode; nil; end def notify_readable?; nil; end def notify_writable= mode; nil; end def notify_writable?; nil; end def pause; nil; end def resume; nil; end def paused?; nil; end # no-op callbacks def post_init; end def receive_data data; end def connection_completed; end def ssl_handshake_completed; end def ssl_verify_peer(cert); end def unbind; end def proxy_target_unbound; end end - - # - # These are designed to run a dummy server in a separate thread - # For testing within the EM reactor instead of stubbing it - # - def self.start_server_thread(klass, host, port) - Thread.new { - EM.run { - EM.start_server(host, port, klass) + + + class << self + # + # These are designed to run a dummy server in a separate thread + # For testing within the EM reactor instead of stubbing it + # + def start_server_thread(klass, host, port) + Thread.new { + EM.run { + EM.start_server(host, port, klass) + } + } + end + + def stop_thread(th) + th.wakeup + EM.stop + end + + def stop_server_thread(th); stop_thread(th); end + def stop_connect_thread(th); th.wakeup; end + + def start_connect_thread(klass, host, port, data) + Thread.new { + EM.run { + EM.connect(host, port, klass, data) + EM.next_tick { EM.stop } } - } - end - - def self.stop_server_thread(th) - th.wakeup - EM.stop + } + end + end - + module DummyServer def initialize $stdout.print "Connection initializing\n"; $stdout.flush end def post_init $stdout.print "Connection initialized\n"; $stdout.flush end def receive_data data $stdout.print "Data received\n"; $stdout.flush close_connection end end + module DummyClient + + def initialize(msg) + @msg = msg + end + + def post_init + send_data @msg + close_connection_after_writing + end + + end + end \ No newline at end of file diff --git a/spec/em/unit/README.markdown b/spec/em/unit/README.markdown new file mode 100755 index 0000000..8db7fdb --- /dev/null +++ b/spec/em/unit/README.markdown @@ -0,0 +1,5 @@ +## Unit tests for the Eventmachine implementation + +This folder contains unit tests of client and server components under lib/em/lib. + +These tests either do not require an EM reactor to be running at all, or stub the reactor using methods in `shared/em_spec_helper`. diff --git a/spec/em/unit/cli_spec.rb b/spec/em/unit/cli_spec.rb index ce03e0b..b099fe4 100755 --- a/spec/em/unit/cli_spec.rb +++ b/spec/em/unit/cli_spec.rb @@ -1,83 +1,55 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_client' # Note: No EM reactor needed describe 'CLI', 'parse' do describe 'when no arguments' do end describe 'when 1 argument' do end describe 'when 2 arguments' do end describe 'when 3 arguments' do end end # Note: EM reactor stubbed describe 'CLI::ReminderClient' do it 'it should call send_data with the initial data in post_init' do @subject = EmSpecHelper.stub_connection( CLI::ReminderClient, "data", :stubs => Proc.new { |stub| stub.expects(:send_data).with("data").once } ) end it 'it should call close_connection_after_writing in post_init' do @subject = EmSpecHelper.stub_connection( CLI::ReminderClient, "data", :stubs => :close_connection_after_writing ) end it 'should stop the EM reactor when unbinding' do @subject = EmSpecHelper.stub_connection( CLI::ReminderClient, "data" ) { |conn| EM.expects(:stop); conn.unbind } end end -# Note: actual EM reactor run, dummy server listening on socket (on separate thread) - -describe 'CLI', 'run' do - - describe 'when server is listening' do - before do - @server_thread = EmSpecHelper.start_server_thread( - EmSpecHelper::DummyServer, - '127.0.0.1', 5544 - ) - end - - after do - EmSpecHelper.stop_server_thread(@server_thread) - end - - it 'should run without errors' do - @client_thread = Thread.current - EM.run { - EM.next_tick { CLI.run } - @client_thread.wakeup - true.should.eql true - } - end - end - -end - diff --git a/spec/em/unit/reminder_server_spec.rb b/spec/em/unit/reminder_server_spec.rb index ee600c8..b5d4ec1 100755 --- a/spec/em/unit/reminder_server_spec.rb +++ b/spec/em/unit/reminder_server_spec.rb @@ -1,47 +1,77 @@ require File.join(File.dirname(__FILE__),'..','..','helper') require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/lib/reminder' require 'lib/em/lib/server/reminder_server' # stub EM.add_timer module EventMachine def self.add_timer(sec, &blk) sleep(sec); blk.call end end -describe 'ReminderServer', 'valid command' do +describe 'ReminderServer', 'receives valid command' do it 'should throw each_reminder with reminder matching received message' do @reminder = Reminder.new({'start_at' => Time.now + 1}) EmSpecHelper.stub_connection(ReminderServer) do |conn| conn.each_reminder do |r| r.should.not.be.nil r.each_pair {|k, v| v.should.eql @reminder[k]} end conn.unparseable_command do |cmd| should.flunk "Command unparseable: #{cmd}" end conn.invalid_message do |msg| should.flunk "Invalid message: #{msg}" end conn.receive_data(@reminder.to_json + "\n\r") end end end -describe 'ReminderServer', 'invalid message format' do +describe 'ReminderServer', 'receives unparseable command' do - it('should throw invalid_message with message') { should.flunk 'Not yet implemented' } + it 'should throw unparseable_command with message' do + @reminder = {'hello' => 'world', + 'unparseable' => 'message', + 'created_at' => Time.now}.to_json + EmSpecHelper.stub_connection(ReminderServer) do |conn| + conn.each_reminder do |r| + should.flunk "Command parsed: #{r.to_json}" + end + conn.unparseable_command do |cmd| + cmd.chomp.should.eql @reminder.chomp + end + conn.invalid_message do |msg| + should.flunk "Command unparseable: #{cmd}" + end + conn.receive_data(@reminder + "\n\r") + end + end end -describe 'ReminderServer', 'unparseable command' do +describe 'ReminderServer', 'receives invalid message format' do - it('should throw unparseable_command with message') { should.flunk 'Not yet implemented' } + it 'should throw invalid_message with message' do + @reminder = "invalid message" + EmSpecHelper.stub_connection(ReminderServer) do |conn| + conn.each_reminder do |r| + should.flunk "Command parsed: #{r.to_json}" + end + conn.unparseable_command do |cmd| + should.flunk "Command unparseable: #{cmd}" + end + conn.invalid_message do |msg| + msg.chomp.should.eql @reminder.chomp + end + conn.receive_data(@reminder + "\n\r") + end + end end diff --git a/spec/em/unit/reminder_spec.rb b/spec/em/unit/reminder_spec.rb index e69de29..f87f5c1 100755 --- a/spec/em/unit/reminder_spec.rb +++ b/spec/em/unit/reminder_spec.rb @@ -0,0 +1 @@ +# TODO \ No newline at end of file
ericgj/rmu-alarmclock
f2fce502d3ecea25380294f07243d59b889ad23a
reorganized bundles, added json; moved helper module to spec/em/shared, loaded by spec/em/helper; started spec for reminder_server, debugged reminder
diff --git a/Gemfile b/Gemfile index f3de234..b444bb9 100755 --- a/Gemfile +++ b/Gemfile @@ -1,9 +1,12 @@ source "http://gems.rubyforge.org" -gem 'eventmachine' +group :em do + gem 'eventmachine' + gem 'json' +end group :test do gem 'bacon' gem 'mocha' gem 'baconmocha' end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index f321767..28c74a7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,20 +1,22 @@ GEM remote: http://gems.rubyforge.org/ specs: bacon (1.1.0) baconmocha (0.0.2) bacon mocha (>= 0.9.6) eventmachine (0.12.10) + json (1.4.6) mocha (0.9.8) rake rake (0.8.7) PLATFORMS ruby DEPENDENCIES bacon baconmocha eventmachine + json mocha diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb index c1fea92..b657d90 100755 --- a/lib/em/em_client.rb +++ b/lib/em/em_client.rb @@ -1,5 +1,5 @@ require 'rubygems' require "bundler" -Bundler.setup(:default) +Bundler.setup(:em) require File.join(File.dirname(__FILE__),'lib','reminder') require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') \ No newline at end of file diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb index 2df24fa..7ade10d 100755 --- a/lib/em/em_server.rb +++ b/lib/em/em_server.rb @@ -1,6 +1,6 @@ require 'rubygems' require "bundler" -Bundler.setup(:default) +Bundler.setup(:em) require File.join(File.dirname(__FILE__),'lib','reminder') require File.join(File.dirname(__FILE__),'lib', 'server', 'reminder_server') require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/reminder.rb b/lib/em/lib/reminder.rb index 9ee5192..93a5ab0 100755 --- a/lib/em/lib/reminder.rb +++ b/lib/em/lib/reminder.rb @@ -1,30 +1,31 @@ require 'json' +require 'json/add/core' class Reminder < Struct.new(:created_at, :start_at, :duration, :message) DEFAULT = { 'duration' => 0, 'message' => 'Here\'s your wake-up call!!' } def seconds_remaining duration - (Time.now - start_at) end def initialize(hash) hash = hash.merge(DEFAULT) hash['created_at'] ||= Time.now hash['start_at'] ||= hash['created_at'] hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end def to_h hash = {} each_pair {|k, v| hash[k] = v} hash end def to_json to_h.to_json end end diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb index d6d7434..9207909 100755 --- a/lib/em/lib/server/reminder_server.rb +++ b/lib/em/lib/server/reminder_server.rb @@ -1,55 +1,62 @@ require 'eventmachine' +require 'json' +require 'json/add/core' module ReminderServer - require 'json' - def post_init @buffer = BufferedTokenizer.new("\r") end def unparseable_command(&blk) @unparseable_command_callback = blk end + def invalid_message(&blk) + @invalid_message_callback = blk + end + def each_reminder(&blk) @each_reminder_callback = blk end def receive_data data @buffer.extract(data).each do |line| receive_line line end end protected def receive_line line if line[0,1] == '{' begin schedule(parse(line)) rescue - @unparseable_command_callback.call(@buffer) \ + @unparseable_command_callback.call(line) \ if @unparseable_command_callback end + else + @invalid_message_callback.call(line) \ + if @invalid_message_callback end end def parse msg Reminder.new(JSON.parse(msg)) end def schedule reminder d = [reminder.seconds_remaining, 0.1].max if @each_reminder_callback EM.add_timer(d) do @each_reminder_callback.call(reminder) end end end end diff --git a/spec/em/helper.rb b/spec/em/helper.rb new file mode 100755 index 0000000..34e4111 --- /dev/null +++ b/spec/em/helper.rb @@ -0,0 +1,7 @@ +Bundler.setup(:em) +require 'eventmachine' +require 'json' +require 'json/add/core' + +Dir[File.expand_path(File.join(File.dirname(__FILE__),'shared','**','*.rb'))]. + each {|f| require f} \ No newline at end of file diff --git a/spec/em/shared/em_spec_helper.rb b/spec/em/shared/em_spec_helper.rb new file mode 100755 index 0000000..c76a721 --- /dev/null +++ b/spec/em/shared/em_spec_helper.rb @@ -0,0 +1,144 @@ + +module EmSpecHelper + + # This is designed to work like EM.connect -- + # it mixes the module into StubConnection below instead of EM::Connection. + # It does *not* run within an EM reactor. + # The block passed it should set any expectations, and + # then call the callbacks being tested. + # These will be called (synchronously of course) after post_init. + # For example, to test that close_connection is called in :receive_data: + # stub_connection(MyRealClient, params) do |conn| + # conn.expects(:close_connection) + # conn.receive_data "200 OK" + # end + # + # If you want to test expectations in post_init, you can pass a :stubs proc: + # stub_connection(MyRealClient, params, + # :stubs => Proc.new { |s| s.expects(:send_data).with("message") } + # ) do |conn| + # conn.receive_data "200 OK" + # end + # + # Or more simply as an array if you don't care about parameters or return values: + # stub_connection(MyRealClient, params, + # :stubs => [ :send_data ] + # ) do |conn| + # conn.receive_data "200 OK" + # end + # + # If you don't set any expectations, the EM::Connection methods will + # simply quietly fire and return nil. + # + def self.stub_connection(klass, *args, &blk) + Class.new(StubConnection){ include klass }.new(*args, &blk) + end + + class StubConnection + + def self.new(*args) + opts = args.last.is_a?(Hash) ? args.pop : {} + stubs = opts[:stubs] + allocate.instance_eval { + # set expectations here + case stubs + when Symbol + self.expects(stubs) + when Array # expect methods + stubs.each {|sym| self.expects(sym.to_sym)} + when Hash # expect methods => returns + stubs.each_pair {|sym, v| self.expects(sym.to_sym).returns(v)} + else # define more complicated stubs in a proc + stubs.call(self) if stubs.respond_to?(:call) + end + initialize(*args) + post_init + yield(self) if block_given? + self + } + end + + def initialize(*args) + end + + # stubbed methods => nil + + def send_data(data); nil; end + def close_connection after_writing = false; nil; end + def close_connection_after_writing; nil; end + def proxy_incoming_to(conn,bufsize=0); nil; end + def stop_proxying; nil; end + def detach; nil; end + def get_sock_opt level, option; nil; end + def error?; nil; end + def start_tls args={}; nil; end + def get_peer_cert; nil; end + def send_datagram data, recipient_address, recipient_port; nil; end + def get_peername; nil; end + def get_sockname; nil; end + def get_pid; nil; end + def get_status; nil; end + def comm_inactivity_timeout; nil; end + def comm_inactivity_timeout= value; nil; end + def set_comm_inactivity_timeout value; nil; end + def pending_connect_timeout; nil; end + def pending_connect_timeout= value; nil; end + def set_pending_connect_timeout value; nil; end + def reconnect server, port; nil; end + def send_file_data filename; nil; end + def stream_file_data filename, args={}; nil; end + def notify_readable= mode; nil; end + def notify_readable?; nil; end + def notify_writable= mode; nil; end + def notify_writable?; nil; end + def pause; nil; end + def resume; nil; end + def paused?; nil; end + + # no-op callbacks + + def post_init; end + def receive_data data; end + def connection_completed; end + def ssl_handshake_completed; end + def ssl_verify_peer(cert); end + def unbind; end + def proxy_target_unbound; end + + end + + # + # These are designed to run a dummy server in a separate thread + # For testing within the EM reactor instead of stubbing it + # + def self.start_server_thread(klass, host, port) + Thread.new { + EM.run { + EM.start_server(host, port, klass) + } + } + end + + def self.stop_server_thread(th) + th.wakeup + EM.stop + end + + module DummyServer + + def initialize + $stdout.print "Connection initializing\n"; $stdout.flush + end + + def post_init + $stdout.print "Connection initialized\n"; $stdout.flush + end + + def receive_data data + $stdout.print "Data received\n"; $stdout.flush + close_connection + end + + end + +end \ No newline at end of file diff --git a/spec/em/unit/cli_spec.rb b/spec/em/unit/cli_spec.rb index c3bc36c..ce03e0b 100755 --- a/spec/em/unit/cli_spec.rb +++ b/spec/em/unit/cli_spec.rb @@ -1,229 +1,83 @@ require File.join(File.dirname(__FILE__),'..','..','helper') -require 'baconmocha' -require 'eventmachine' +require File.join(File.dirname(__FILE__),'..','helper') require 'lib/em/em_client' -module CLISpecHelper - - # This is designed to work like EM.connect -- - # it mixes the module into StubConnection below instead of EM::Connection. - # It does *not* run within an EM reactor. - # The block passed it should set any expectations, and - # then call the callbacks being tested. - # These will be called (synchronously of course) after post_init. - # For example, to test that close_connection is called in :receive_data: - # stub_connection(MyRealClient, params) do |conn| - # conn.expects(:close_connection) - # conn.receive_data "200 OK" - # end - # - # If you want to test expectations in post_init, you can pass a :stubs proc: - # stub_connection(MyRealClient, params, - # :stubs => Proc.new { |s| s.expects(:send_data).with("message") } - # ) do |conn| - # conn.receive_data "200 OK" - # end - # - # Or more simply as an array if you don't care about parameters or return values: - # stub_connection(MyRealClient, params, - # :stubs => [ :send_data ] - # ) do |conn| - # conn.receive_data "200 OK" - # end - # - # If you don't set any expectations, the EM::Connection methods will - # simply quietly fire and return nil. - # - def self.stub_connection(klass, *args, &blk) - Class.new(StubConnection){ include klass }.new(*args, &blk) - end - - class StubConnection - - def self.new(*args) - opts = args.last.is_a?(Hash) ? args.pop : {} - stubs = opts[:stubs] - allocate.instance_eval { - # set expectations here - case stubs - when Symbol - self.expects(stubs) - when Array # expect methods - stubs.each {|sym| self.expects(sym.to_sym)} - when Hash # expect methods => returns - stubs.each_pair {|sym, v| self.expects(sym.to_sym).returns(v)} - else # define more complicated stubs in a proc - stubs.call(self) if stubs.respond_to?(:call) - end - initialize(*args) - post_init - yield(self) if block_given? - self - } - end - - def initialize(*args) - end - - # stubbed methods => nil - - def send_data(data); nil; end - def close_connection after_writing = false; nil; end - def close_connection_after_writing; nil; end - def proxy_incoming_to(conn,bufsize=0); nil; end - def stop_proxying; nil; end - def detach; nil; end - def get_sock_opt level, option; nil; end - def error?; nil; end - def start_tls args={}; nil; end - def get_peer_cert; nil; end - def send_datagram data, recipient_address, recipient_port; nil; end - def get_peername; nil; end - def get_sockname; nil; end - def get_pid; nil; end - def get_status; nil; end - def comm_inactivity_timeout; nil; end - def comm_inactivity_timeout= value; nil; end - def set_comm_inactivity_timeout value; nil; end - def pending_connect_timeout; nil; end - def pending_connect_timeout= value; nil; end - def set_pending_connect_timeout value; nil; end - def reconnect server, port; nil; end - def send_file_data filename; nil; end - def stream_file_data filename, args={}; nil; end - def notify_readable= mode; nil; end - def notify_readable?; nil; end - def notify_writable= mode; nil; end - def notify_writable?; nil; end - def pause; nil; end - def resume; nil; end - def paused?; nil; end - - # no-op callbacks - - def post_init; end - def receive_data data; end - def connection_completed; end - def ssl_handshake_completed; end - def ssl_verify_peer(cert); end - def unbind; end - def proxy_target_unbound; end - - end - - # - # These are designed to run a dummy server in a separate thread - # For testing within the EM reactor instead of stubbing it - # - def self.start_server_thread(klass, host, port) - Thread.new { - EM.run { - EM.start_server(host, port, klass) - } - } - end - - def self.stop_server_thread(th) - th.wakeup - EM.stop - end - - module DummyServer - - def initialize - $stdout.print "Connection initializing\n"; $stdout.flush - end - - def post_init - $stdout.print "Connection initialized\n"; $stdout.flush - end - - def receive_data data - $stdout.print "Data received\n"; $stdout.flush - close_connection - end - - end - -end - - # Note: No EM reactor needed describe 'CLI', 'parse' do describe 'when no arguments' do end describe 'when 1 argument' do end describe 'when 2 arguments' do end describe 'when 3 arguments' do end end # Note: EM reactor stubbed describe 'CLI::ReminderClient' do it 'it should call send_data with the initial data in post_init' do - @subject = CLISpecHelper.stub_connection( + @subject = EmSpecHelper.stub_connection( CLI::ReminderClient, "data", :stubs => Proc.new { |stub| stub.expects(:send_data).with("data").once } ) end it 'it should call close_connection_after_writing in post_init' do - @subject = CLISpecHelper.stub_connection( + @subject = EmSpecHelper.stub_connection( CLI::ReminderClient, "data", :stubs => :close_connection_after_writing ) end it 'should stop the EM reactor when unbinding' do - @subject = CLISpecHelper.stub_connection( + @subject = EmSpecHelper.stub_connection( CLI::ReminderClient, "data" ) { |conn| EM.expects(:stop); conn.unbind } end end # Note: actual EM reactor run, dummy server listening on socket (on separate thread) describe 'CLI', 'run' do describe 'when server is listening' do before do - @server_thread = CLISpecHelper.start_server_thread( - CLISpecHelper::DummyServer, + @server_thread = EmSpecHelper.start_server_thread( + EmSpecHelper::DummyServer, '127.0.0.1', 5544 ) end after do - CLISpecHelper.stop_server_thread(@server_thread) + EmSpecHelper.stop_server_thread(@server_thread) end it 'should run without errors' do @client_thread = Thread.current EM.run { EM.next_tick { CLI.run } @client_thread.wakeup true.should.eql true } end end end diff --git a/spec/em/unit/reminder_server_spec.rb b/spec/em/unit/reminder_server_spec.rb index 36819c5..ee600c8 100755 --- a/spec/em/unit/reminder_server_spec.rb +++ b/spec/em/unit/reminder_server_spec.rb @@ -1,28 +1,47 @@ require File.join(File.dirname(__FILE__),'..','..','helper') -require 'baconmocha' +require File.join(File.dirname(__FILE__),'..','helper') -require 'lib/em/server/reminder_server' +require 'lib/em/lib/reminder' +require 'lib/em/lib/server/reminder_server' # stub EM.add_timer -class EventMachine +module EventMachine def self.add_timer(sec, &blk) sleep(sec); blk.call end end describe 'ReminderServer', 'valid command' do - # something like - stub_connection(ReminderServer) do |conn| - conn.each_reminder do |r| - # do something to verify - true.should.eql true + it 'should throw each_reminder with reminder matching received message' do + + @reminder = Reminder.new({'start_at' => Time.now + 1}) + EmSpecHelper.stub_connection(ReminderServer) do |conn| + conn.each_reminder do |r| + r.should.not.be.nil + r.each_pair {|k, v| v.should.eql @reminder[k]} + end + conn.unparseable_command do |cmd| + should.flunk "Command unparseable: #{cmd}" + end + conn.invalid_message do |msg| + should.flunk "Invalid message: #{msg}" + end + conn.receive_data(@reminder.to_json + "\n\r") end - conn.receive_data "{\"start_at\": #{Time.now + 1}}" + end + +end + +describe 'ReminderServer', 'invalid message format' do + + it('should throw invalid_message with message') { should.flunk 'Not yet implemented' } end -describe 'ReminderServer', 'invalid command' do +describe 'ReminderServer', 'unparseable command' do + it('should throw unparseable_command with message') { should.flunk 'Not yet implemented' } + end diff --git a/spec/helper.rb b/spec/helper.rb index 66f8796..ce822e7 100755 --- a/spec/helper.rb +++ b/spec/helper.rb @@ -1,8 +1,9 @@ $LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__),"..")) require 'rubygems' require 'bundler' Bundler.setup(:test) require 'bacon' -Bacon.summary_on_exit \ No newline at end of file +require 'baconmocha' +Bacon.summary_on_exit
ericgj/rmu-alarmclock
375110454ea5cd8c6fe14ffde7cc6a43e73eea94
started EM server specs
diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb index 0b117c5..d6d7434 100755 --- a/lib/em/lib/server/reminder_server.rb +++ b/lib/em/lib/server/reminder_server.rb @@ -1,55 +1,55 @@ require 'eventmachine' module ReminderServer require 'json' def post_init @buffer = BufferedTokenizer.new("\r") end def unparseable_command(&blk) @unparseable_command_callback = blk end def each_reminder(&blk) @each_reminder_callback = blk end def receive_data data @buffer.extract(data).each do |line| receive_line line end end protected def receive_line line if line[0,1] == '{' begin schedule(parse(line)) rescue @unparseable_command_callback.call(@buffer) \ if @unparseable_command_callback end end end def parse msg Reminder.new(JSON.parse(msg)) end def schedule reminder - if (d = reminder.seconds_remaining) > 0 + d = [reminder.seconds_remaining, 0.1].max + if @each_reminder_callback EM.add_timer(d) do - @each_reminder_callback.call(reminder) \ - if @each_reminder_callback + @each_reminder_callback.call(reminder) end end end end diff --git a/spec/em/unit/reminder_server_spec.rb b/spec/em/unit/reminder_server_spec.rb new file mode 100755 index 0000000..36819c5 --- /dev/null +++ b/spec/em/unit/reminder_server_spec.rb @@ -0,0 +1,28 @@ +require File.join(File.dirname(__FILE__),'..','..','helper') +require 'baconmocha' + +require 'lib/em/server/reminder_server' + +# stub EM.add_timer +class EventMachine + def self.add_timer(sec, &blk) + sleep(sec); blk.call + end +end + +describe 'ReminderServer', 'valid command' do + + # something like + stub_connection(ReminderServer) do |conn| + conn.each_reminder do |r| + # do something to verify + true.should.eql true + end + conn.receive_data "{\"start_at\": #{Time.now + 1}}" + end + +end + +describe 'ReminderServer', 'invalid command' do + +end
ericgj/rmu-alarmclock
3024eabf6b660b2fbd10a04e510f2bb0f7d00681
finished specs for EM client (mostly), bundled gems
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6732a9a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +vendor/* +.bundle/* diff --git a/Gemfile b/Gemfile new file mode 100755 index 0000000..f3de234 --- /dev/null +++ b/Gemfile @@ -0,0 +1,9 @@ +source "http://gems.rubyforge.org" + +gem 'eventmachine' + +group :test do + gem 'bacon' + gem 'mocha' + gem 'baconmocha' +end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..f321767 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,20 @@ +GEM + remote: http://gems.rubyforge.org/ + specs: + bacon (1.1.0) + baconmocha (0.0.2) + bacon + mocha (>= 0.9.6) + eventmachine (0.12.10) + mocha (0.9.8) + rake + rake (0.8.7) + +PLATFORMS + ruby + +DEPENDENCIES + bacon + baconmocha + eventmachine + mocha diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb index 480f665..c1fea92 100755 --- a/lib/em/em_client.rb +++ b/lib/em/em_client.rb @@ -1,3 +1,5 @@ require 'rubygems' +require "bundler" +Bundler.setup(:default) require File.join(File.dirname(__FILE__),'lib','reminder') require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') \ No newline at end of file diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb index f2c3aa5..2df24fa 100755 --- a/lib/em/em_server.rb +++ b/lib/em/em_server.rb @@ -1,4 +1,6 @@ require 'rubygems' +require "bundler" +Bundler.setup(:default) require File.join(File.dirname(__FILE__),'lib','reminder') require File.join(File.dirname(__FILE__),'lib', 'server', 'reminder_server') require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/client/cli.rb b/lib/em/lib/client/cli.rb index 0b6c9c4..8255aec 100755 --- a/lib/em/lib/client/cli.rb +++ b/lib/em/lib/client/cli.rb @@ -1,43 +1,43 @@ # TODO config APPENV with external file APPENV = { 'host' => '127.0.0.1', 'port' => 5544 } # Usage: # CLI.run(ARGV) module CLI def self.parse(*args) h = {} h['duration'] = arg0 if (arg0 = args.shift) h['message'] = args.join(' ') unless args.empty? h['created_at'] = Time.now msg = Reminder.new(h).to_json end def self.run(*args) EM.run { EM.connect APPENV['host'], APPENV['port'], ReminderClient, CLI.parse(*args) } end module ReminderClient def initialize(reminder) @msg = reminder end def post_init - send_data msg + send_data @msg close_connection_after_writing end def unbind EM.stop end end end diff --git a/spec/em/unit/cli_spec.rb b/spec/em/unit/cli_spec.rb index 09b33dd..c3bc36c 100755 --- a/spec/em/unit/cli_spec.rb +++ b/spec/em/unit/cli_spec.rb @@ -1,83 +1,229 @@ require File.join(File.dirname(__FILE__),'..','..','helper') -#require 'baconmocha' +require 'baconmocha' require 'eventmachine' require 'lib/em/em_client' module CLISpecHelper - def self.start_server_thread(klass) + # This is designed to work like EM.connect -- + # it mixes the module into StubConnection below instead of EM::Connection. + # It does *not* run within an EM reactor. + # The block passed it should set any expectations, and + # then call the callbacks being tested. + # These will be called (synchronously of course) after post_init. + # For example, to test that close_connection is called in :receive_data: + # stub_connection(MyRealClient, params) do |conn| + # conn.expects(:close_connection) + # conn.receive_data "200 OK" + # end + # + # If you want to test expectations in post_init, you can pass a :stubs proc: + # stub_connection(MyRealClient, params, + # :stubs => Proc.new { |s| s.expects(:send_data).with("message") } + # ) do |conn| + # conn.receive_data "200 OK" + # end + # + # Or more simply as an array if you don't care about parameters or return values: + # stub_connection(MyRealClient, params, + # :stubs => [ :send_data ] + # ) do |conn| + # conn.receive_data "200 OK" + # end + # + # If you don't set any expectations, the EM::Connection methods will + # simply quietly fire and return nil. + # + def self.stub_connection(klass, *args, &blk) + Class.new(StubConnection){ include klass }.new(*args, &blk) + end + + class StubConnection + + def self.new(*args) + opts = args.last.is_a?(Hash) ? args.pop : {} + stubs = opts[:stubs] + allocate.instance_eval { + # set expectations here + case stubs + when Symbol + self.expects(stubs) + when Array # expect methods + stubs.each {|sym| self.expects(sym.to_sym)} + when Hash # expect methods => returns + stubs.each_pair {|sym, v| self.expects(sym.to_sym).returns(v)} + else # define more complicated stubs in a proc + stubs.call(self) if stubs.respond_to?(:call) + end + initialize(*args) + post_init + yield(self) if block_given? + self + } + end + + def initialize(*args) + end + + # stubbed methods => nil + + def send_data(data); nil; end + def close_connection after_writing = false; nil; end + def close_connection_after_writing; nil; end + def proxy_incoming_to(conn,bufsize=0); nil; end + def stop_proxying; nil; end + def detach; nil; end + def get_sock_opt level, option; nil; end + def error?; nil; end + def start_tls args={}; nil; end + def get_peer_cert; nil; end + def send_datagram data, recipient_address, recipient_port; nil; end + def get_peername; nil; end + def get_sockname; nil; end + def get_pid; nil; end + def get_status; nil; end + def comm_inactivity_timeout; nil; end + def comm_inactivity_timeout= value; nil; end + def set_comm_inactivity_timeout value; nil; end + def pending_connect_timeout; nil; end + def pending_connect_timeout= value; nil; end + def set_pending_connect_timeout value; nil; end + def reconnect server, port; nil; end + def send_file_data filename; nil; end + def stream_file_data filename, args={}; nil; end + def notify_readable= mode; nil; end + def notify_readable?; nil; end + def notify_writable= mode; nil; end + def notify_writable?; nil; end + def pause; nil; end + def resume; nil; end + def paused?; nil; end + + # no-op callbacks + + def post_init; end + def receive_data data; end + def connection_completed; end + def ssl_handshake_completed; end + def ssl_verify_peer(cert); end + def unbind; end + def proxy_target_unbound; end + + end + + # + # These are designed to run a dummy server in a separate thread + # For testing within the EM reactor instead of stubbing it + # + def self.start_server_thread(klass, host, port) Thread.new { EM.run { - EM.start_server('127.0.0.1', 5544, klass) + EM.start_server(host, port, klass) } } end def self.stop_server_thread(th) th.wakeup EM.stop end - -end -module DummyServer - - def initialize - $stdout.print "Connection initializing\n"; $stdout.flush - end - - def post_init - $stdout.print "Connection initialized\n"; $stdout.flush - end - - def receive_data data - $stdout.print "Data received\n"; $stdout.flush - close_connection + module DummyServer + + def initialize + $stdout.print "Connection initializing\n"; $stdout.flush + end + + def post_init + $stdout.print "Connection initialized\n"; $stdout.flush + end + + def receive_data data + $stdout.print "Data received\n"; $stdout.flush + close_connection + end + end - + end + +# Note: No EM reactor needed + describe 'CLI', 'parse' do describe 'when no arguments' do end describe 'when 1 argument' do end describe 'when 2 arguments' do end describe 'when 3 arguments' do end end -describe 'CLI', 'run' do +# Note: EM reactor stubbed + +describe 'CLI::ReminderClient' do + + it 'it should call send_data with the initial data in post_init' do + @subject = CLISpecHelper.stub_connection( + CLI::ReminderClient, "data", + :stubs => Proc.new { |stub| + stub.expects(:send_data).with("data").once + } + ) + end + + it 'it should call close_connection_after_writing in post_init' do + @subject = CLISpecHelper.stub_connection( + CLI::ReminderClient, "data", + :stubs => :close_connection_after_writing + ) + end + + it 'should stop the EM reactor when unbinding' do + @subject = CLISpecHelper.stub_connection( + CLI::ReminderClient, "data" + ) { |conn| EM.expects(:stop); conn.unbind } + end +end + +# Note: actual EM reactor run, dummy server listening on socket (on separate thread) + +describe 'CLI', 'run' do + describe 'when server is listening' do before do - @server_thread = CLISpecHelper.start_server_thread(DummyServer) + @server_thread = CLISpecHelper.start_server_thread( + CLISpecHelper::DummyServer, + '127.0.0.1', 5544 + ) end after do CLISpecHelper.stop_server_thread(@server_thread) end it 'should run without errors' do @client_thread = Thread.current EM.run { EM.next_tick { CLI.run } @client_thread.wakeup true.should.eql true } end end end diff --git a/spec/helper.rb b/spec/helper.rb index 0afab24..66f8796 100755 --- a/spec/helper.rb +++ b/spec/helper.rb @@ -1,3 +1,8 @@ $LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__),"..")) + +require 'rubygems' +require 'bundler' +Bundler.setup(:test) + require 'bacon' Bacon.summary_on_exit \ No newline at end of file
ericgj/rmu-alarmclock
cfb089d5dd24306c92f44cf694d122fd69b2446b
started specs for client component; redid reminder as Struct
diff --git a/Rakefile b/Rakefile new file mode 100755 index 0000000..e69de29 diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb index 2a53aac..480f665 100755 --- a/lib/em/em_client.rb +++ b/lib/em/em_client.rb @@ -1,3 +1,3 @@ require 'rubygems' -require File.join(File.dirpath(__FILE__),'lib','reminder') -require File.join(File.dirpath(__FILE__),'lib', 'client', 'cli') \ No newline at end of file +require File.join(File.dirname(__FILE__),'lib','reminder') +require File.join(File.dirname(__FILE__),'lib', 'client', 'cli') \ No newline at end of file diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb index 8b0f8aa..f2c3aa5 100755 --- a/lib/em/em_server.rb +++ b/lib/em/em_server.rb @@ -1,4 +1,4 @@ require 'rubygems' -require File.join(File.dirpath(__FILE__),'lib','reminder') -require File.join(File.dirpath(__FILE__),'lib', 'server', 'reminder_server') -require File.join(File.dirpath(__FILE__),'lib', 'server', 'app') \ No newline at end of file +require File.join(File.dirname(__FILE__),'lib','reminder') +require File.join(File.dirname(__FILE__),'lib', 'server', 'reminder_server') +require File.join(File.dirname(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/client/cli.rb b/lib/em/lib/client/cli.rb index 7497fb9..0b6c9c4 100755 --- a/lib/em/lib/client/cli.rb +++ b/lib/em/lib/client/cli.rb @@ -1,44 +1,43 @@ # TODO config APPENV with external file -APPENV = { 'host' => 'localhost', +APPENV = { 'host' => '127.0.0.1', 'port' => 5544 } # Usage: # CLI.run(ARGV) module CLI def self.parse(*args) - msg = Reminder.new( { - 'duration' => args.shift, - 'message' => args.join(' '), - 'created_at' => Time.now - } - ).to_json + h = {} + h['duration'] = arg0 if (arg0 = args.shift) + h['message'] = args.join(' ') unless args.empty? + h['created_at'] = Time.now + msg = Reminder.new(h).to_json end def self.run(*args) EM.run { EM.connect APPENV['host'], APPENV['port'], ReminderClient, CLI.parse(*args) } end module ReminderClient def initialize(reminder) @msg = reminder end def post_init send_data msg close_connection_after_writing end def unbind EM.stop end end end diff --git a/lib/em/lib/reminder.rb b/lib/em/lib/reminder.rb index 5570619..9ee5192 100755 --- a/lib/em/lib/reminder.rb +++ b/lib/em/lib/reminder.rb @@ -1,34 +1,30 @@ require 'json' -class Reminder - - attr_reader :created_at, :start_at, :duration, :message +class Reminder < Struct.new(:created_at, :start_at, :duration, :message) + DEFAULT = { 'duration' => 0, + 'message' => 'Here\'s your wake-up call!!' + } + def seconds_remaining - @duration - (Time.now - @start_at) + duration - (Time.now - start_at) end def initialize(hash) - @created_at = hash['created_at'] - @start_at = hash['start_at'] || hash['created_at'] - @duration = hash['duration'] - @message = hash['message'] || default_message - end - - def default_message - 'Here\'s your wake-up call!!' + hash = hash.merge(DEFAULT) + hash['created_at'] ||= Time.now + hash['start_at'] ||= hash['created_at'] + hash.each_pair {|k,v| self.__send__("#{k}=".to_sym, v)} end - + def to_h - { 'created_at' => @created_at, - 'start_at' => @start_at, - 'duration' => @duration, - 'message' => @message - } + hash = {} + each_pair {|k, v| hash[k] = v} + hash end def to_json to_h.to_json end end diff --git a/spec/em/unit/cli_spec.rb b/spec/em/unit/cli_spec.rb new file mode 100755 index 0000000..09b33dd --- /dev/null +++ b/spec/em/unit/cli_spec.rb @@ -0,0 +1,83 @@ +require File.join(File.dirname(__FILE__),'..','..','helper') +#require 'baconmocha' +require 'eventmachine' + +require 'lib/em/em_client' + +module CLISpecHelper + + def self.start_server_thread(klass) + Thread.new { + EM.run { + EM.start_server('127.0.0.1', 5544, klass) + } + } + end + + def self.stop_server_thread(th) + th.wakeup + EM.stop + end + +end + +module DummyServer + + def initialize + $stdout.print "Connection initializing\n"; $stdout.flush + end + + def post_init + $stdout.print "Connection initialized\n"; $stdout.flush + end + + def receive_data data + $stdout.print "Data received\n"; $stdout.flush + close_connection + end + +end + +describe 'CLI', 'parse' do + + describe 'when no arguments' do + + end + + describe 'when 1 argument' do + + end + + describe 'when 2 arguments' do + + end + + describe 'when 3 arguments' do + + end + +end + +describe 'CLI', 'run' do + + describe 'when server is listening' do + before do + @server_thread = CLISpecHelper.start_server_thread(DummyServer) + end + + after do + CLISpecHelper.stop_server_thread(@server_thread) + end + + it 'should run without errors' do + @client_thread = Thread.current + EM.run { + EM.next_tick { CLI.run } + @client_thread.wakeup + true.should.eql true + } + end + end + +end + diff --git a/spec/em/unit/reminder_spec.rb b/spec/em/unit/reminder_spec.rb new file mode 100755 index 0000000..e69de29 diff --git a/spec/helper.rb b/spec/helper.rb new file mode 100755 index 0000000..0afab24 --- /dev/null +++ b/spec/helper.rb @@ -0,0 +1,3 @@ +$LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__),"..")) +require 'bacon' +Bacon.summary_on_exit \ No newline at end of file
ericgj/rmu-alarmclock
4e566815f80c7cdb001988c0be555d91a7f7a790
first draft simple eventmachine implementation
diff --git a/README.markdown b/README.markdown new file mode 100755 index 0000000..7e34301 --- /dev/null +++ b/README.markdown @@ -0,0 +1,30 @@ +## Description + +Basically the project is a glorified alarm clock, or the 'reminder' part of a calendar application. You tell a server you have an event at a given time and/or given duration and it sends you a reminder at the point in time the event is due to start or end (or at some configurable duration before). You can snooze the reminder (for some configurable duration), or turn it off. You can have multiple reminders going at once. + +There are basically three components: + +- the 'client' which sends user event requests to +- the 'server' which keeps track of when reminders are due and sends them to +- the 'alarm' which notifies the user in some way and sends user 'snooze' or 'off' requests to the server + +The main constraints are + +1. The interface for setting up reminders has to be almost as easy as turning the dial of an egg timer; +2. The communication between the client requesting a reminder and the server sending the reminder is asynchronous; +3. The alarm mechanism (on the client side) should be able to be 'obtrusive', and not necessarily run in the same process as the client program that sends reminder requests to the server; but +4. The default alarm mechanism should be something very basic that makes few assumptions about what software the client has installed. + + +## Interface + +The client interface is via command line. + +Examples: + + remindr 10 # generic reminder in 10 minutes + remindr 30s # reminder in 30 seconds + remindr 25 get up and stretch # message reminder + remindr 10:30 walk the dog # reminder at specified time + remindr --end 11pm-12:30pm meeting # reminder at end of timed event + diff --git a/ROADMAP.markdown b/ROADMAP.markdown new file mode 100755 index 0000000..7fe3ca6 --- /dev/null +++ b/ROADMAP.markdown @@ -0,0 +1,14 @@ +## Roadmap + +**The first stage** of this project I want to do is a simple implementation of all three parts of the app: client, server, and alarm, using straight Eventmachine. + +By simple I mean: + +- The most basic form of the command +- No mechanism for snoozing/offing alarms + +**The second stage** of the project is to re-do the app as a 'skinny daemon'. + +**The third stage** of the project is to evaluate the two implementations and to integrate Growl into one or the other as the alarm/snoozing mechanism. + +**The fourth stage** is to refine the command syntax. \ No newline at end of file diff --git a/lib/em/README.markdown b/lib/em/README.markdown new file mode 100755 index 0000000..a20d2ba --- /dev/null +++ b/lib/em/README.markdown @@ -0,0 +1,5 @@ +This is the first stage of the project, the Eventmachine implementation. + +For explanation, see [http://github.com/ericgj/rmu-alarmclock/ROADMAP.markdown](ROADMAP) + +As of 12 Sep, it is still a draft. \ No newline at end of file diff --git a/lib/em/em_client.rb b/lib/em/em_client.rb new file mode 100755 index 0000000..2a53aac --- /dev/null +++ b/lib/em/em_client.rb @@ -0,0 +1,3 @@ +require 'rubygems' +require File.join(File.dirpath(__FILE__),'lib','reminder') +require File.join(File.dirpath(__FILE__),'lib', 'client', 'cli') \ No newline at end of file diff --git a/lib/em/em_server.rb b/lib/em/em_server.rb new file mode 100755 index 0000000..8b0f8aa --- /dev/null +++ b/lib/em/em_server.rb @@ -0,0 +1,4 @@ +require 'rubygems' +require File.join(File.dirpath(__FILE__),'lib','reminder') +require File.join(File.dirpath(__FILE__),'lib', 'server', 'reminder_server') +require File.join(File.dirpath(__FILE__),'lib', 'server', 'app') \ No newline at end of file diff --git a/lib/em/lib/client/cli.rb b/lib/em/lib/client/cli.rb new file mode 100755 index 0000000..7497fb9 --- /dev/null +++ b/lib/em/lib/client/cli.rb @@ -0,0 +1,44 @@ +# TODO config APPENV with external file +APPENV = { 'host' => 'localhost', + 'port' => 5544 + } + +# Usage: +# CLI.run(ARGV) + +module CLI + + def self.parse(*args) + msg = Reminder.new( { + 'duration' => args.shift, + 'message' => args.join(' '), + 'created_at' => Time.now + } + ).to_json + end + + def self.run(*args) + EM.run { + EM.connect APPENV['host'], APPENV['port'], ReminderClient, CLI.parse(*args) + } + end + + module ReminderClient + + def initialize(reminder) + @msg = reminder + end + + def post_init + send_data msg + close_connection_after_writing + end + + def unbind + EM.stop + end + + end + +end + diff --git a/lib/em/lib/reminder.rb b/lib/em/lib/reminder.rb new file mode 100755 index 0000000..5570619 --- /dev/null +++ b/lib/em/lib/reminder.rb @@ -0,0 +1,34 @@ +require 'json' + +class Reminder + + attr_reader :created_at, :start_at, :duration, :message + + def seconds_remaining + @duration - (Time.now - @start_at) + end + + def initialize(hash) + @created_at = hash['created_at'] + @start_at = hash['start_at'] || hash['created_at'] + @duration = hash['duration'] + @message = hash['message'] || default_message + end + + def default_message + 'Here\'s your wake-up call!!' + end + + def to_h + { 'created_at' => @created_at, + 'start_at' => @start_at, + 'duration' => @duration, + 'message' => @message + } + end + + def to_json + to_h.to_json + end + +end diff --git a/lib/em/lib/server/app.rb b/lib/em/lib/server/app.rb new file mode 100755 index 0000000..f5007a7 --- /dev/null +++ b/lib/em/lib/server/app.rb @@ -0,0 +1,34 @@ +# TODO config APPENV with external file +APPENV = { 'host' => 'localhost', + 'port' => 5544, + 'alarm-host' => 'localhost', + 'alarm-port' => 5545 + } + +module SimpleAlarmClient + + def initialize(reminder) + @reminder = reminder + end + + def post_init + send_data @reminder.to_json + end + +end + +EM.run { + + server = EM.start_server(APPENV['host'], APPENV['port'], ReminderServer) + + server.unparseable_command do |cmd| + $stdout.print "Unparseable command received: `#{cmd}`\n" + $stdout.flush + end + + server.each_reminder do |reminder| + EM.connect(APPENV['alarm-host'], APPENV['alarm-port'], SimpleAlarmClient, reminder) + end + +} + diff --git a/lib/em/lib/server/reminder_server.rb b/lib/em/lib/server/reminder_server.rb new file mode 100755 index 0000000..0b117c5 --- /dev/null +++ b/lib/em/lib/server/reminder_server.rb @@ -0,0 +1,55 @@ +require 'eventmachine' + +module ReminderServer + + require 'json' + + def post_init + @buffer = BufferedTokenizer.new("\r") + end + + def unparseable_command(&blk) + @unparseable_command_callback = blk + end + + def each_reminder(&blk) + @each_reminder_callback = blk + end + + def receive_data data + @buffer.extract(data).each do |line| + receive_line line + end + end + + + protected + + def receive_line line + if line[0,1] == '{' + begin + schedule(parse(line)) + rescue + @unparseable_command_callback.call(@buffer) \ + if @unparseable_command_callback + end + end + end + + def parse msg + Reminder.new(JSON.parse(msg)) + end + + def schedule reminder + if (d = reminder.seconds_remaining) > 0 + EM.add_timer(d) do + @each_reminder_callback.call(reminder) \ + if @each_reminder_callback + end + end + end + +end + + +
ericgj/rmu-alarmclock
8697935a676713ed2f84046a8c9284c8d4c8c733
Added proposal
diff --git a/PROPOSAL.markdown b/PROPOSAL.markdown new file mode 100644 index 0000000..1853b7e --- /dev/null +++ b/PROPOSAL.markdown @@ -0,0 +1,53 @@ +## Description + +Basically the project is a glorified alarm clock, or the 'reminder' part of a calendar application. You tell a server you have an event at a given time and/or given duration and it sends you a reminder at the point in time the event is due to start or end (or at some configurable duration before). You can snooze the reminder (for some configurable duration), or turn it off. You can have multiple reminders going at once. + +There are basically three components: + +- the 'client' which sends user event requests to +- the 'server' which keeps track of when reminders are due and sends them to +- the 'alarm' which notifies the user in some way and sends user 'snooze' or 'off' requests to the server + +The interactions may turn out to be a little different than this but that's the naive picture. + +Note it isn't intended to be a full fledged calendar app with CRUD interface to the events, etc. + + +## Motivations + +Originally, the idea grew out of my need for a simple timer to use when programming instead of the egg timer or cell phone alarm I currently use. Very useful tools to help pull one's head up out of whatever it's buried in! + +I am not quite convinced there is a better mouse trap to build for the job than the egg timer. Hard to beat the simplicity of that interface. (In fact I'm not convinced the best solution for me is a software one at all, since the point of the reminder/alarm is to draw your attention up from the screen...) + +So I've come to see primary purpose of the project is a toy for exploring various Ruby technologies (see below), and of course for improving my programming practices. + +The main constraints are + +1. The interface for setting up reminders has to be almost as easy as turning the dial of an egg timer; +2. The communication between the client requesting a reminder and the server sending the reminder is asynchronous; +3. The alarm mechanism (on the client side) should be able to be 'obtrusive', and not necessarily run in the same process as the client program that sends reminder requests to the server; but +4. The default alarm mechanism should be something very basic that makes few assumptions about what software the client has installed. + +I tried to stay within the guidelines of 'not too huge or challenging a project, but does something interesting or useful', but let me know what you think. + + +## What I am hoping to explore with this project + +First of all I am looking forward to developing this project from the 'outside in' using **BDD** (although I'm plenty familiar with RSpec, I have just started actually doing BDD). + +Initially the client interface would be from the command line, so I want to explore **approaches to and tools for implementing a CLI**. + +The alarm mechanism is the most unsettled aspect of the project. My thought is to first implement it as a simple spawned process that does not allow feedback back to the server, ie. doesn't allow 'snoozing'. Further on I'd like to have it do something like run a **Shoes** app, or interface with something like **Growl** (which has a built-in callback mechanism). + +As for the back end, I am not settled yet on using http, in any case I have two routes in mind, both utilizing asynchronous messaging to varying degrees. Perhaps I could try both and see what are the dis/advantages of each. + +- Client and server pieces each run within **EventMachine** reactors. Client triggers alarm mechanism on receiving reminder from the server, and alarm runs within the client reactor although it may spawn external processes. + +- Taking the approach detailed recently by [Head Labs](http://labs.headlondon.com/2010/07/skinny-daemons/), design the server piece as a 'skinny daemon' (RESTful **Sinatra/Rack** app running inside a **Thin** webserver on localhost). The client piece then would use **RestClient** or similar under the hood. Since the server is running locally, it itself handles spawning the alarm mechanism from a timer callback. + + +## Potential extensions (not necessarily done within the deadlines of the course) + +1. Persistence +2. Rescheduling +3. Multiuser
vishwam/apod.gadget
752bd45283cbe4cac91c5b0ed1ac501f8f129712
Version 1.1, uploaded to live gallery on 20100829. Added MIT license document, icons for logo/status, readme for silk icons. Cleaned up html/js/css.
diff --git a/Gadget.xml b/Gadget.xml index 69de7c2..2bdfc30 100755 --- a/Gadget.xml +++ b/Gadget.xml @@ -1,16 +1,25 @@ <?xml version="1.0" encoding="utf-8" ?> <gadget> - <name>APoD</name> - <version>1.0.0.0</version> - <description>Astronomy Picture of the Day</description> + <name>APOD</name> + <version>1.1.0.0</version> + <description> + Astronomy Picture of the Day + Discover the cosmos! + http://apod.nasa.gov/ + </description> + <copyright>© 2010 (MIT License)</copyright> <author name="Vishwam Subramanyam"> - <info url="http://v.4261.in/projects/APoD_Gadget" /> + <info url="http://v.4261.in/projects/apod-gadget" text="v.4261.in" /> + <logo src="images/logo.png" /> </author> + <icons> + <icon height="256" width="256" src="images/icon 256.png" /> + </icons> <hosts> <host name="sidebar"> <base type="HTML" apiVersion="1.0.0" src="apod.html" /> <permissions>Full</permissions> <platform minPlatformVersion="1.0" /> </host> </hosts> </gadget> \ No newline at end of file diff --git a/apod.html b/apod.html index 2f1b50a..d765255 100755 Binary files a/apod.html and b/apod.html differ diff --git a/css/apod.css b/css/apod.css index b0f8ebf..33ac454 100755 Binary files a/css/apod.css and b/css/apod.css differ diff --git a/images/arrow_refresh_small.png b/images/arrow_refresh_small.png new file mode 100755 index 0000000..4f38da5 Binary files /dev/null and b/images/arrow_refresh_small.png differ diff --git a/images/error.png b/images/error.png new file mode 100755 index 0000000..628cf2d Binary files /dev/null and b/images/error.png differ diff --git a/images/icon 256.png b/images/icon 256.png new file mode 100755 index 0000000..d0594a4 Binary files /dev/null and b/images/icon 256.png differ diff --git a/images/logo.png b/images/logo.png new file mode 100755 index 0000000..26948fa Binary files /dev/null and b/images/logo.png differ diff --git a/images/silk icons readme.txt b/images/silk icons readme.txt new file mode 100755 index 0000000..400a64d --- /dev/null +++ b/images/silk icons readme.txt @@ -0,0 +1,22 @@ +Silk icon set 1.3 + +_________________________________________ +Mark James +http://www.famfamfam.com/lab/icons/silk/ +_________________________________________ + +This work is licensed under a +Creative Commons Attribution 2.5 License. +[ http://creativecommons.org/licenses/by/2.5/ ] + +This means you may use it for any purpose, +and make any changes you like. +All I ask is that you include a link back +to this page in your credits. + +Are you using this icon set? Send me an email +(including a link or picture if available) to +mjames@gmail.com + +Any other questions about this icon set please +contact mjames@gmail.com \ No newline at end of file diff --git a/js/apod.js b/js/apod.js index f4965cd..812f65d 100755 Binary files a/js/apod.js and b/js/apod.js differ diff --git a/license.txt b/license.txt new file mode 100755 index 0000000..31348e7 --- /dev/null +++ b/license.txt @@ -0,0 +1,23 @@ +Astronomy Picture of the Day (APOD) Gadget + +The MIT License + +Copyright (c) 2010 Vishwam Subramanyam <v@4261.in> + +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.