CombinedText
stringlengths
4
3.42M
# # Be sure to run `pod spec lint YumiBaiduSDK.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "YumiIronsourceSDK" s.version = "6.4.21" s.summary = "YumiIronsourceSDK." s.description = "YumiIronsourceSDK is the Ironsource SDK cocoapods created by Yumimobi" s.homepage = "http://www.yumimobi.com/" s.license = "MIT" s.author = { "Yumimobi sdk team" => "ad-client@zplay.cn" } s.ios.deployment_target = "7.0" s.source = { :http => "http://ad-sdk.oss-cn-beijing.aliyuncs.com/iOS/Ironsource_SDK_v#{s.version}.zip" } src_root = "Ironsource_SDK_v#{s.version}/lib" s.vendored_frameworks = "#{src_root}/Supersonic.framework" s.resource = "#{src_root}/Supersonic.framework/*.{png}" s.libraries = "xml2","z.1.2.5","c++","sqlite3" s.weak_frameworks = 'WebKit' end update ironsource source # # Be sure to run `pod spec lint YumiBaiduSDK.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "YumiIronsourceSDK" s.version = "6.4.21" s.summary = "YumiIronsourceSDK." s.description = "YumiIronsourceSDK is the Ironsource SDK cocoapods created by Yumimobi" s.homepage = "http://www.yumimobi.com/" s.license = "MIT" s.author = { "Yumimobi sdk team" => "ad-client@zplay.cn" } s.ios.deployment_target = "7.0" s.source = { :http => "http://adsdk.yumimobi.com/iOS/Ironsource_SDK_v#{s.version}.zip" } src_root = "Ironsource_SDK_v#{s.version}/lib" s.vendored_frameworks = "#{src_root}/Supersonic.framework" s.resource = "#{src_root}/Supersonic.framework/*.{png}" s.libraries = "xml2","z.1.2.5","c++","sqlite3" s.weak_frameworks = 'WebKit' end
class FontKarlaTamilInclined < Cask version '1.001' sha256 :no_check url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/karlatamilinclined', :using => :svn, :revision => '50', :trust_cert => true homepage 'https://www.google.com/fonts/earlyaccess' font 'KarlaTamilInclined-Bold.ttf' font 'KarlaTamilInclined-Regular.ttf' end version 'latest' for font-karla-tamil-inclined.rb preserve known version in comment for later use class FontKarlaTamilInclined < Cask # version '1.001' version 'latest' sha256 :no_check url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/karlatamilinclined', :using => :svn, :revision => '50', :trust_cert => true homepage 'https://www.google.com/fonts/earlyaccess' font 'KarlaTamilInclined-Bold.ttf' font 'KarlaTamilInclined-Regular.ttf' end
cask "photo-supreme-single-user" do version "7.4.1.4613" sha256 :no_check # required as upstream package is updated in-place url "https://trial.idimager.com/PhotoSupreme_V#{version.major}.pkg" name "Photo Supreme Single User" desc "Digital Asset Management" homepage "https://www.idimager.com/home" livecheck do url "https://www.idimager.com/what-s-new-in-photo-supreme-v#{version.major}" regex(/>s*(\d+(?:\.\d+)+)[\s<]/i) end pkg "PhotoSupreme_V#{version.major}.pkg" uninstall pkgutil: "com.idimager.idimagersu" end photo-supreme-single-user 7.4.1.4619 Update photo-supreme-single-user from 7.4.1.4613 to 7.4.1.4619 Closes #135176. Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com> Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com> cask "photo-supreme-single-user" do version "7.4.1.4619" sha256 :no_check # required as upstream package is updated in-place url "https://trial.idimager.com/PhotoSupreme_V#{version.major}.pkg" name "Photo Supreme Single User" desc "Digital Asset Management" homepage "https://www.idimager.com/home" livecheck do url "https://www.idimager.com/what-s-new-in-photo-supreme-v#{version.major}" regex(/>s*(\d+(?:\.\d+)+)[\s<]/i) end pkg "PhotoSupreme_V#{version.major}.pkg" uninstall pkgutil: "com.idimager.idimagersu" end
cask 'virtualbox-extension-pack' do version '5.0.18-106667' sha256 '1ccc48d457d1ee568166066df025f6cf82b6dde1ddc993c9bea1fe7abbe255ef' url "http://download.virtualbox.org/virtualbox/#{version.sub(%r{-.*}, '')}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" name 'Oracle VirtualBox Extension Pack' homepage 'https://www.virtualbox.org' license :closed depends_on cask: 'virtualbox' container type: :naked stage_only true postflight do system 'sudo', 'VBoxManage', 'extpack', 'install', '--replace', "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" end uninstall_postflight do system 'sudo', 'VBoxManage', 'extpack', 'uninstall', 'Oracle VM VirtualBox Extension Pack' end end updated virtualbox-extension-pack (5.0.20-106931) (#20863) cask 'virtualbox-extension-pack' do version '5.0.20-106931' sha256 '11f40842a56ebb17da1bbc82a21543e66108a5330ebd54ded68038a990aa071b' url "http://download.virtualbox.org/virtualbox/#{version.sub(%r{-.*}, '')}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" name 'Oracle VirtualBox Extension Pack' homepage 'https://www.virtualbox.org' license :closed depends_on cask: 'virtualbox' container type: :naked stage_only true postflight do system 'sudo', 'VBoxManage', 'extpack', 'install', '--replace', "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" end uninstall_postflight do system 'sudo', 'VBoxManage', 'extpack', 'uninstall', 'Oracle VM VirtualBox Extension Pack' end end
append_file 'Gemfile', <<-GEMFILE git 'git://github.com/rspec/rspec.git' git 'git://github.com/rspec/rspec-core.git' git 'git://github.com/rspec/rspec-expectations.git' git 'git://github.com/rspec/rspec-mocks.git' git 'git://github.com/rspec/rspec-rails.git' gem 'rspec' gem 'rspec-core' gem 'rspec-expectations' gem 'rspec-mocks' gem 'rspec-rails' GEMFILE run('bundle install vendor') run('script/rails generate rspec:install') apply 'http://github.com/snusnu/rails-templates/raw/rspec/sample_scaffold.rb' run('rspec spec') run('vendor/bin/rake spec') Let's try it another way append_file 'Gemfile', <<-GEMFILE git 'git://github.com/rspec/rspec.git' git 'git://github.com/rspec/rspec-core.git' git 'git://github.com/rspec/rspec-expectations.git' git 'git://github.com/rspec/rspec-mocks.git' git 'git://github.com/rspec/rspec-rails.git' gem 'rspec' gem 'rspec-core' gem 'rspec-expectations' gem 'rspec-mocks' gem 'rspec-rails' GEMFILE run('bundle install vendor') run('vendor/bin/rails generate rspec:install') apply 'http://github.com/snusnu/rails-templates/raw/rspec/sample_scaffold.rb' run('rspec spec') run('vendor/bin/rake spec')
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: currency-rate 0.3.8 ruby lib Gem::Specification.new do |s| s.name = "currency-rate" s.version = "0.3.8" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Roman Snitko"] s.date = "2017-07-26" s.description = "Fetches exchange rates from various sources and does the conversion" s.email = "roman.snitko@gmail.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "currency-rate.gemspec", "lib/adapter.rb", "lib/btc_adapter.rb", "lib/btc_adapters/average_rate_adapter.rb", "lib/btc_adapters/bitfinex_adapter.rb", "lib/btc_adapters/bitpay_adapter.rb", "lib/btc_adapters/bitstamp_adapter.rb", "lib/btc_adapters/btcchina_adapter.rb", "lib/btc_adapters/btce_adapter.rb", "lib/btc_adapters/coinbase_adapter.rb", "lib/btc_adapters/huobi_adapter.rb", "lib/btc_adapters/kraken_adapter.rb", "lib/btc_adapters/localbitcoins_adapter.rb", "lib/btc_adapters/okcoin_adapter.rb", "lib/core_ext/deep_get.rb", "lib/currency_rate.rb", "lib/fiat_adapter.rb", "lib/fiat_adapters/fixer_adapter.rb", "lib/fiat_adapters/yahoo_adapter.rb", "lib/storage.rb", "spec/currency_rate_spec.rb", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/average_rate_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/bitfinex_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/bitpay_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/btcchina_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/btce_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/coinbase_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/huobi_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/kraken_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/localbitcoins_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/okcoin_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/fiat_adapters/fixer_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/fiat_adapters/yahoo_adapter.yml", "spec/lib/btc_adapter_spec.rb", "spec/lib/btc_adapters/average_rate_adapter_spec.rb", "spec/lib/btc_adapters/bitfinex_adapter_spec.rb", "spec/lib/btc_adapters/bitpay_adapter_spec.rb", "spec/lib/btc_adapters/bitstamp_adapter_spec.rb", "spec/lib/btc_adapters/btcchina_adapter_spec.rb", "spec/lib/btc_adapters/btce_adapter_spec.rb", "spec/lib/btc_adapters/coinbase_adapter_spec.rb", "spec/lib/btc_adapters/huobi_adapter_spec.rb", "spec/lib/btc_adapters/kraken_adapter_spec.rb", "spec/lib/btc_adapters/localbitcoins_adapter_spec.rb", "spec/lib/btc_adapters/okcoin_adapter_spec.rb", "spec/lib/fiat_adapters/fixer_adapter_spec.rb", "spec/lib/fiat_adapters/yahoo_adapter_spec.rb", "spec/lib/storage_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/snitko/currency-rate" s.licenses = ["MIT"] s.rubygems_version = "2.5.1" s.summary = "Converter for fiat and crypto currencies" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<satoshi-unit>, [">= 0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.3.7"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<webmock>, [">= 0"]) s.add_development_dependency(%q<vcr>, [">= 0"]) else s.add_dependency(%q<satoshi-unit>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.3.7"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) end else s.add_dependency(%q<satoshi-unit>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.3.7"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) end end Regenerate gemspec for version 0.3.8 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: currency-rate 0.3.8 ruby lib Gem::Specification.new do |s| s.name = "currency-rate" s.version = "0.3.8" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Roman Snitko"] s.date = "2017-08-24" s.description = "Fetches exchange rates from various sources and does the conversion" s.email = "roman.snitko@gmail.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "currency-rate.gemspec", "lib/adapter.rb", "lib/core_ext/deep_get.rb", "lib/crypto_adapter.rb", "lib/crypto_adapters/average_rate_adapter.rb", "lib/crypto_adapters/bitfinex_adapter.rb", "lib/crypto_adapters/bitpay_adapter.rb", "lib/crypto_adapters/bitstamp_adapter.rb", "lib/crypto_adapters/btcchina_adapter.rb", "lib/crypto_adapters/btce_adapter.rb", "lib/crypto_adapters/coinbase_adapter.rb", "lib/crypto_adapters/huobi_adapter.rb", "lib/crypto_adapters/kraken_adapter.rb", "lib/crypto_adapters/localbitcoins_adapter.rb", "lib/crypto_adapters/okcoin_adapter.rb", "lib/currency_rate.rb", "lib/fiat_adapter.rb", "lib/fiat_adapters/fixer_adapter.rb", "lib/fiat_adapters/yahoo_adapter.rb", "lib/storage.rb", "spec/currency_rate_spec.rb", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/average_rate_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/bitfinex_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/bitpay_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/btcchina_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/btce_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/coinbase_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/huobi_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/kraken_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/localbitcoins_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/btc_adapters/okcoin_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/fiat_adapters/fixer_adapter.yml", "spec/fixtures/vcr/exchange_rate_adapters/fiat_adapters/yahoo_adapter.yml", "spec/lib/crypto_adapter_spec.rb", "spec/lib/crypto_adapters/average_rate_adapter_spec.rb", "spec/lib/crypto_adapters/bitfinex_adapter_spec.rb", "spec/lib/crypto_adapters/bitpay_adapter_spec.rb", "spec/lib/crypto_adapters/bitstamp_adapter_spec.rb", "spec/lib/crypto_adapters/btcchina_adapter_spec.rb", "spec/lib/crypto_adapters/btce_adapter_spec.rb", "spec/lib/crypto_adapters/coinbase_adapter_spec.rb", "spec/lib/crypto_adapters/huobi_adapter_spec.rb", "spec/lib/crypto_adapters/kraken_adapter_spec.rb", "spec/lib/crypto_adapters/localbitcoins_adapter_spec.rb", "spec/lib/crypto_adapters/okcoin_adapter_spec.rb", "spec/lib/fiat_adapters/fixer_adapter_spec.rb", "spec/lib/fiat_adapters/yahoo_adapter_spec.rb", "spec/lib/storage_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/snitko/currency-rate" s.licenses = ["MIT"] s.rubygems_version = "2.5.1" s.summary = "Converter for fiat and crypto currencies" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<satoshi-unit>, [">= 0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.3.7"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<webmock>, [">= 0"]) s.add_development_dependency(%q<vcr>, [">= 0"]) else s.add_dependency(%q<satoshi-unit>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.3.7"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) end else s.add_dependency(%q<satoshi-unit>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.3.7"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) end end
test_name "certificate whitelisting using legacy location in [jetty]" do confd = "#{puppetdb_confdir(database)}/conf.d" dbname = database.node_name on database, puppet_agent("--configprint ssldir") ssldir = stdout.chomp step "reconfigure PuppetDB to use certificate whitelist" do on database, "cp #{confd}/jetty.ini #{confd}/jetty.ini.bak" on database, "grep -v ^certificate-whitelist #{confd}/jetty.ini > #{confd}/jetty.ini.tmp" on database, "mv -f #{confd}/jetty.ini.tmp #{confd}/jetty.ini" modify_config_setting(database, "jetty.ini", "jetty", "certificate-whitelist", "#{confd}/whitelist") end # Execute a curl from the database to itself using HTTPS, using the # supplied whitelist, and verify the response is what we expect curl_against_whitelist = proc do |whitelist, expected_status_code| create_remote_file database, "#{confd}/whitelist", whitelist on database, "chmod 644 #{confd}/whitelist" restart_puppetdb database on database, "curl -sL -w '%{http_code}\\n' " + "--cacert #{ssldir}/certs/ca.pem " + "--cert #{ssldir}/certs/#{dbname}.pem " + "--key #{ssldir}/private_keys/#{dbname}.pem "+ "https://#{dbname}:8081/v3/metrics/mbeans " + "-o /dev/null" actual_status_code = stdout.chomp assert_equal expected_status_code.to_s, actual_status_code, "Reqs from #{dbname} with whitelist '#{whitelist}' should return #{expected_status_code}, not #{actual_status_code}" end step "hosts in whitelist should be allowed in" do curl_against_whitelist.call "#{dbname}\n", 200 end step "hosts not in whitelist should be forbidden" do curl_against_whitelist.call "", 403 end step "restore original jetty.ini" do on database, "mv #{confd}/jetty.ini.bak #{confd}/jetty.ini" on database, "chmod 644 #{confd}/jetty.ini" on database, "rm #{confd}/whitelist" restart_puppetdb database end end (PDB-1247) Fix cert_whitelist_legacy test From 1476b28 test_name "certificate whitelisting using legacy location in [jetty]" do confd = "#{puppetdb_confdir(database)}/conf.d" dbname = database.node_name on database, puppet_agent("--configprint ssldir") ssldir = stdout.chomp step "reconfigure PuppetDB to use certificate whitelist" do on database, "cp #{confd}/jetty.ini #{confd}/jetty.ini.bak" on database, "grep -v ^certificate-whitelist #{confd}/jetty.ini > #{confd}/jetty.ini.tmp" on database, "mv -f #{confd}/jetty.ini.tmp #{confd}/jetty.ini" modify_config_setting(database, "jetty.ini", "jetty", "certificate-whitelist", "#{confd}/whitelist") end # Execute a curl from the database to itself using HTTPS, using the # supplied whitelist, and verify the response is what we expect curl_against_whitelist = proc do |whitelist, expected_status_code| create_remote_file database, "#{confd}/whitelist", whitelist on database, "chmod 644 #{confd}/whitelist" restart_puppetdb database on database, "curl --tlsv1 -sL -w '%{http_code}\\n' " + "--cacert #{ssldir}/certs/ca.pem " + "--cert #{ssldir}/certs/#{dbname}.pem " + "--key #{ssldir}/private_keys/#{dbname}.pem "+ "https://#{dbname}:8081/v3/metrics/mbeans " + "-o /dev/null" actual_status_code = stdout.chomp assert_equal expected_status_code.to_s, actual_status_code, "Reqs from #{dbname} with whitelist '#{whitelist}' should return #{expected_status_code}, not #{actual_status_code}" end step "hosts in whitelist should be allowed in" do curl_against_whitelist.call "#{dbname}\n", 200 end step "hosts not in whitelist should be forbidden" do curl_against_whitelist.call "", 403 end step "restore original jetty.ini" do on database, "mv #{confd}/jetty.ini.bak #{confd}/jetty.ini" on database, "chmod 644 #{confd}/jetty.ini" on database, "rm #{confd}/whitelist" restart_puppetdb database end end
require 'rubygems' require 'prawn' require 'json' require 'pp' include GriffinMarkdown @render_notes_and_doodles = true @location_label_width = 6 @header_height = 3 @row_height = 2 @column_width = 8 @title_font_size = 19 @grey = 'eeeeee' @grey_dark = 'dddddd' @grey_50 = '888888' @grey_40 = '444444' @grey_20 = '222222' @black = '000000' @white = 'ffffff' entries = {} # 24-hour times to display @morning_hours = [ 9, 10, 11, 12, 13 ] @afternoon_hours = [ 14, 15, 16, 17, 18 ] @locs1 = (1..15).map { |x| "A&S #{x}" } @locs1 << 'University-Battlefield' @locs1 << 'Dance' @locs1 << 'Games' @locs2 = [ 'Performing Arts', 'Amphitheater', 'Middle Eastern', 'Æthelmearc 1', 'Æthelmearc 2', 'Touch The Earth', 'Performing Arts Rehearsal', 'Livonia Smithery', 'Pine Box Traders', ].sort @loc_count = {} @locs1.each { |loc| @loc_count[loc] = 0 } @locs2.each { |loc| @loc_count[loc] = 0 } def generate_magic_tokens(instructables) items = instructables.map { |x| [x.formatted_topic, x.name.gsub('*', ''), x.id] }.sort last_topic = nil magic_token = 0 @instructable_magic_tokens = {} items.each do |item| if last_topic != item[0].split(':').first.strip magic_token += 100 - (magic_token % 100) last_topic = item[0].split(':').first.strip end @instructable_magic_tokens[item[2]] = magic_token magic_token += 1 end end instructables = Instructable.where(schedule: 'Pennsic University') generate_magic_tokens(instructables) ids = instructables.map { |x| x.id } instances = Instance.where(instructable_id: ids).includes(:instructable).select { |x| x.scheduled? } instances.each do |instance| if instance.start_time.nil? pp instance next end date = instance.start_time.to_date entries[date] ||= { morning: { loc1: [], loc2: [] }, afternoon: { loc1: [], loc2: [] }, other_location: [], other_time: [], other: [], } hour = instance.start_time.hour morning_check = @morning_hours.index(hour) afternoon_check = @afternoon_hours.index(hour) actual_loc = instance.location.gsub(/ Tent$/, '') loc = instance.instructable.location_nontrack? ? instance.instructable.camp_name : actual_loc loc.gsub!(/ Tent$/, '') loc1_check = @locs1.index(loc) || @locs1.index(actual_loc) loc2_check = @locs2.index(loc) || @locs2.index(actual_loc) @loc_count[loc] ||= 0 @loc_count[loc] += 1 subsection = nil in_loc = false if not (morning_check or afternoon_check) or not (loc1_check or loc2_check) section = :other if (loc1_check or loc2_check) and hour < @morning_hours.first in_loc = true end elsif (loc1_check or loc2_check) and (morning_check) section = :morning subsection = loc1_check ? :loc1 : :loc2 elsif (loc1_check or loc2_check) and (afternoon_check) section = :afternoon subsection = loc1_check ? :loc1 : :loc2 else puts "OTHER:" pp instance section = :other end locindex = (loc1_check || loc2_check) hourindex = (morning_check || afternoon_check) duration = instance.instructable.duration minute = instance.start_time.strftime('%M').to_i if hourindex hourindex += (minute / 60.0) if (hourindex + duration) > 5 display_duration = 5 - hourindex extended_right = true else display_duration = duration extended_right = false end else display_duration = duration extended_right = false end extended_left = false if instance.instructable.name == 'Bellatrix: Individual Session' start_time = "By appointment" section = :other subsection = nil else start_time = instance.start_time end data = { name: instance.instructable.name, start_time: start_time, hourindex: hourindex, locindex: locindex, duration: duration, display_duration: display_duration, id: @instructable_magic_tokens[instance.instructable.id], extended_right: extended_right, extended_left: extended_left, instance: instance, } spot = subsection ? entries[date][section][subsection] : entries[date][section] spot << data if in_loc and (hour + minute / 60.0 + duration > @morning_hours.first) display_duration = duration - (@morning_hours.first - (hour + minute / 60.0)) name = instance.instructable.name name = 'Yoga' if name =~ /^Yoga/ data = { name: name, start_time: start_time, hourindex: 0, locindex: locindex, duration: duration, display_duration: display_duration, id: @instructable_magic_tokens[instance.instructable.id], extended_right: extended_right, extended_left: true, instance: instance, } spot = entries[date][:morning][loc1_check ? :loc1 : :loc2] spot << data end if extended_right and section == :morning display_duration = duration - display_duration if display_duration > 5 display_duration = 5 extended_right = true else extended_right = false end data = { name: instance.instructable.name, start_time: instance.start_time, hourindex: 0, locindex: locindex, duration: duration, display_duration: display_duration, id: @instructable_magic_tokens[instance.instructable.id], extended_right: extended_right, extended_left: true, instance: instance, } spot = entries[date][:afternoon][subsection] spot << data end end def draw_hour_labels(pdf, opts) opts[:hour_labels].count.times do |timeindex| opts[:location_labels].count.times do |locindex| y1 = @header_height + locindex * @row_height x1 = @location_label_width + timeindex * @column_width y2 = y1 + @row_height - 1 x2 = x1 - 1 + @column_width box = pdf.grid([y1, x1], [y2, x2]) box.bounding_box { pdf.stroke_color @grey_dark pdf.fill_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds pdf.stroke_color @black pdf.fill_color @black } end end opts[:hour_labels].each_with_index do |label, labelindex| y1 = @header_height - 1 x1 = @location_label_width + labelindex * @column_width y2 = y1 x2 = x1 + @column_width - 1 box = pdf.grid([y1, x1], [y2, x2]) box.bounding_box { pdf.fill_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.fill_color @black pdf.stroke { #pdf.line [box.width, 0], box.width, box.height pdf.line [0, 0], 0, box.height pdf.line [0, 0], box.width, 0 } } box_opts = { at: [box.top_left[0] + 2, box.top_left[1] - 2], width: box.width - 4, height: box.height - 4, size: 10, overflow: :shrink_to_fit, min_font_size: 6, align: :center, valign: :center, style: :bold, } if label < 12 pdf.text_box "#{label}:00 am", box_opts else pm = label > 12 ? label - 12 : 12 pdf.text_box "#{pm}:00 pm", box_opts end end end def draw_location_labels(pdf, opts) opts[:location_labels].each_with_index do |label, labelindex| y1 = @header_height + labelindex * @row_height x1 = 0 y2 = y1 + @row_height - 1 x2 = @location_label_width - 1 box = pdf.grid([y1, x1], [y2, x2]) box.bounding_box { pdf.fill_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.fill_color @black pdf.stroke { pdf.line [0, box.height], box.width, box.height pdf.line [0, 0], box.width, 0 pdf.line [box.width, 0], box.width, box.height } } box_opts = { at: [box.top_left[0] + 2, box.top_left[1] - 2], width: box.width - 4, height: box.height - 4, size: 9, overflow: :shrink_to_fit, min_font_size: 8, align: :center, valign: :center, style: :bold, } pdf.text_box label, box_opts end end def render(pdf, opts) debug = false if debug pdf.stroke_axis end pdf.line_width 0.25 pdf.stroke_color @black hour_slots = opts[:hour_labels].count location_slots = opts[:location_labels].count location_slots = 18 if location_slots < 18 pdf.define_grid(columns: hour_slots * 8 + 6, rows: location_slots * 2 + 2 + 1, gutter: 0) if debug (pdf.grid.rows - 1).times do |row| (pdf.grid.columns - 1).times do |column| pdf.grid([row, column], [row + 1, column + 1]).bounding_box do pdf.stroke_color @grey pdf.stroke_bounds end end end pdf.stroke_color @black end box = pdf.grid([0, 0], [@header_height - 1, pdf.grid.columns - 1]) box.bounding_box do pdf.fill_color @grey pdf.stroke_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds end box = pdf.grid([0, 0], [1, pdf.grid.columns - 1]) msg = opts[:title] box_opts = { align: :center, valign: :center, size: @title_font_size, at: [box.top_left[0], box.top_left[1] - 2], width: box.width, height: box.height, } pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text_box msg, box_opts end end pdf.fill_color @black pdf.stroke_color @black draw_hour_labels(pdf, opts) draw_location_labels(pdf, opts) pdf.font_size 12 opts[:entries].each do |data| locindex = data[:locindex] hourindex = data[:hourindex] display_duration = data[:display_duration] duration = data[:duration] extended_right = data[:extended_right] extended_left = data[:extended_left] y1 = @header_height + locindex * @row_height x1 = @location_label_width + hourindex.to_f * @column_width y2 = y1 + @row_height - 1 x2 = x1 - 1 + display_duration * @column_width box = pdf.grid([y1, x1], [y2, x2]) if extended_left at = [box.top_left[0] + 6, box.top_left[1] - 2] else at = [box.top_left[0] + 2, box.top_left[1] - 2] end box_opts = { at: at, width: box.width - 4, height: box.height - 4, size: 9, overflow: :shrink_to_fit, min_font_size: 8, leading: 0, inline_format: true, } box.bounding_box { pdf.fill_color @white pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.fill_color @black pdf.stroke_bounds } msg = "#{markdown_html data[:name]} <i>(#{data[:id]})</i>" if duration != display_duration msg += "<br/><b>(#{duration} hours)</b>" end pdf.text_box msg, box_opts if extended_right coords = [ [box.top_right[0], box.top_right[1]], [box.top_right[0] + 5, (box.top_right[1] + box.bottom_right[1]) / 2], [box.bottom_right[0], box.bottom_right[1]] ] pdf.fill_polygon *coords end if extended_left coords = [ [box.top_left[0], box.top_left[1]], [box.top_left[0] + 5, (box.top_left[1] + box.bottom_left[1]) / 2], [box.bottom_left[0], box.bottom_left[1]] ] pdf.fill_polygon *coords end end end def render_extra(pdf, opts) rowoffset = opts[:rowoffset] box = pdf.grid([rowoffset, 0], [pdf.grid.rows - 1, pdf.grid.columns - 1]) box = pdf.grid([rowoffset, 0], [rowoffset + 1, pdf.grid.columns - 1]) box.bounding_box do pdf.fill_color @grey pdf.stroke_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds end msg = opts[:title] box_opts = { align: :center, valign: :center, size: @title_font_size, at: [box.top_left[0], box.top_left[1] - 2], width: box.width, height: box.height, } pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text_box msg, box_opts end end pdf.stroke_color @black pdf.fill_color @black rowoffset += 2 entries_count = opts[:entries].count if entries_count < 25 font_size = 7.8 + (25 - entries_count) / 10.0 columns = 1 else font_size = 8.5 - (entries_count / 30.0) columns = 2 end first = true box = pdf.grid([rowoffset, 0], [pdf.grid.rows - 1, pdf.grid.columns - 1]) pdf.column_box([box.top_left[0], box.top_left[1] - 3], columns: columns, width: box.width) do opts[:entries].each do |entry| pdf.move_down 2 unless first first = false if entry[:start_time].is_a?(String) start_time = entry[:instance].formatted_location start_time += " (#{entry[:start_time]})" else start_time = entry[:instance].formatted_location_and_time(:pennsic_time_only) end msg = "#{entry[:id]}: #{markdown_html(entry[:name])}, #{start_time}" duration = entry[:duration] if duration != 1 msg += ", #{duration} hours" end pdf.text msg, size: font_size, inline_format: true end end end def render_notes(pdf, opts) rowoffset = opts[:rowoffset] draw_lines = opts[:mode] == :notes draw_box = opts[:mode] == :doodles line_box = pdf.grid([rowoffset + 2, 0], [pdf.grid.rows - 1, pdf.grid.columns - 1]) if draw_box line_box.bounding_box do pdf.stroke_color @grey_40 pdf.fill_color @grey_40 pdf.stroke_bounds end end box = pdf.grid([rowoffset, 0], [rowoffset + 1, pdf.grid.columns - 1]) box.bounding_box do pdf.fill_color @grey pdf.stroke_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds end msg = opts[:title] box_opts = { align: :center, valign: :center, size: @title_font_size, at: [box.top_left[0], box.top_left[1] - 2], width: box.width, height: box.height, } pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text_box msg, box_opts end end if draw_lines rowoffset += 2 pdf.stroke_color @grey_40 pdf.fill_color @grey_40 spacing = 25 y = spacing pdf.move_down spacing while y < line_box.height pdf.stroke_horizontal_rule pdf.move_down spacing y += spacing end end pdf.stroke_color @black pdf.fill_color @black end def draftit(pdf) return pdf.save_graphics_state do pdf.soft_mask do pdf.rotate(45, origin: [0, 0]) do pdf.fill_color @grey_50 pdf.draw_text "Draft", size: 200, at: [250, 0] pdf.fill_color @black end end pdf.rotate(45, origin: [0, 0]) do pdf.fill_color 'bbbbbb' pdf.draw_text "Draft", size: 200, at: [250, 0] pdf.fill_color @black end end end def materials_and_handout_content(instructable) materials = [] handout = [] handout << "limit: #{instructable.handout_limit}" if instructable.handout_limit materials << "limit: #{instructable.material_limit}" if instructable.material_limit handout << "fee: $#{'%.2f' % instructable.handout_fee}" if instructable.handout_fee materials << "fee: $#{'%.2f' % instructable.material_fee}" if instructable.material_fee handout_content = nil handout_content = 'Handout ' + handout.join(', ') + '. ' if handout.size > 0 materials_content = nil materials_content = 'Materials ' + materials.join(', ') + '. ' if materials.size > 0 [ handout_content, materials_content ].compact end def render_topic_list(pdf, instructables) previous_topic = '' instructables.sort { |a, b| [a.formatted_topic, a.name.gsub('*', '')] <=> [b.formatted_topic, b.name.gsub('*', '')] }.each do |instructable| if instructable.topic != previous_topic pdf.move_down 7 unless pdf.cursor == pdf.bounds.top pdf.font_size @title_font_size pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text instructable.topic end end pdf.font_size 7.5 pdf.fill_color @black pdf.stroke_color @black end previous_topic = instructable.topic pdf.move_down 5 unless pdf.cursor == pdf.bounds.top name = markdown_html(instructable.name, tags_remove: 'strong') token = @instructable_magic_tokens[instructable.id] topic = "Topic: #{instructable.formatted_topic}" culture = instructable.culture.present? ? "Culture: #{instructable.culture}" : nil heading = "<strong>#{token}</strong>: <strong>#{name}</strong>" lines = [ heading, [topic, culture].compact.join(', '), "Instructor: #{instructable.user.titled_sca_name}", ] scheduled_instances = instructable.instances.select { |x| x.scheduled? } if scheduled_instances.count > 1 and scheduled_instances.map(&:formatted_location).uniq.count == 1 lines << 'Taught: ' + scheduled_instances.map { |x| "#{x.start_time.strftime('%a %b %e %I:%M %p')}" }.join(', ') lines << 'Location: ' + scheduled_instances.first.formatted_location else lines << 'Taught: ' + scheduled_instances.map { |x| x.scheduled? ? "#{x.start_time.strftime('%a %b %e %I:%M %p')} #{x.formatted_location}" : nil }.compact.join(', ') end lines << materials_and_handout_content(instructable).join(' ') pdf.text lines.join("\n"), inline_format: true pdf.move_down 2 unless pdf.cursor == pdf.bounds.top pdf.text markdown_html(instructable.description_web.present? ? instructable.description_web : instructable.description_book), inline_format: true, align: :justify end end pdf = Prawn::Document.new(page_size: "LETTER", page_layout: :portrait, compress: true, optimize_objects: true, info: { Title: "Pennsic Schedule", Author: "thing.pennsicuniversity.org", Subject: "Pennsic Schedule", Keywords: "Pennsic Schedule", Creator: "sched.rb", CreationDate: Time.now }) pdf.font_families.update( 'TitleFont' => { normal: { file: Rails.root.join('app', 'assets', 'fonts', 'Arial.ttf') }, }, 'BodyFont' => { normal: Rails.root.join('app', 'assets', 'fonts', 'Arial.ttf'), bold: Rails.root.join('app', 'assets', 'fonts', 'Arial Bold.ttf'), italic: Rails.root.join('app', 'assets', 'fonts', 'Arial Italic.ttf'), bold_italic: Rails.root.join('app', 'assets', 'fonts', 'Arial Bold Italic.ttf'), }, ) pdf.font 'BodyFont' pdf.text "Spacer page" pdf.start_new_page @note_counter = 1 def next_note_type ret = [:notes, :doodles][@note_counter % 2] @note_counter += 1 ret end entries.keys.sort.each do |key| day = key.strftime("%d").to_i date = key.strftime("%A, %B #{day.ordinalize}, A.S. L") render(pdf, location_labels: @locs1, hour_labels: @morning_hours, entries: entries[key][:morning][:loc1], title: "#{date} ~ Morning") draftit(pdf) pdf.start_new_page render(pdf, location_labels: @locs2, hour_labels: @morning_hours, entries: entries[key][:morning][:loc2], title: "#{date} ~ Morning") subentries = entries[key][:other] if subentries.count > 0 subentries.sort! { |a, b| a[:start_time].to_i <=> b[:start_time].to_i } render_extra(pdf, entries: subentries, title: "#{date} ~ Additional Classes", rowoffset: @locs2.count * @row_height + @header_height + 1) else render_notes(pdf, mode: :notes, title: "Notes", rowoffset: @locs2.count * @row_height + @header_height + 1) end draftit(pdf) pdf.start_new_page render(pdf, location_labels: @locs1, hour_labels: @afternoon_hours, entries: entries[key][:afternoon][:loc1], title: "#{date} ~ Afternoon") draftit(pdf) pdf.start_new_page render(pdf, location_labels: @locs2, hour_labels: @afternoon_hours, entries: entries[key][:afternoon][:loc2], title: "#{date} ~ Afternoon") note_type = next_note_type if (@render_notes_and_doodles) render_notes(pdf, mode: note_type, title: (note_type == :notes ? 'Notes' : 'Notes and Doodles'), rowoffset: @locs2.count * @row_height + @header_height + 1) end draftit(pdf) pdf.start_new_page end pdf.font 'BodyFont' pdf.column_box([0, pdf.cursor ], columns: 3, spacer: 6, width: pdf.bounds.width) do render_topic_list(pdf, instructables) end pdf.render_file 'sched.pdf' @loc_count.keys.sort.each { |x| puts (' %2d %s' % [@loc_count[x], x]) } am/pm -> AM/PM require 'rubygems' require 'prawn' require 'json' require 'pp' include GriffinMarkdown @render_notes_and_doodles = true @location_label_width = 6 @header_height = 3 @row_height = 2 @column_width = 8 @title_font_size = 19 @grey = 'eeeeee' @grey_dark = 'dddddd' @grey_50 = '888888' @grey_40 = '444444' @grey_20 = '222222' @black = '000000' @white = 'ffffff' entries = {} # 24-hour times to display @morning_hours = [ 9, 10, 11, 12, 13 ] @afternoon_hours = [ 14, 15, 16, 17, 18 ] @locs1 = (1..15).map { |x| "A&S #{x}" } @locs1 << 'University-Battlefield' @locs1 << 'Dance' @locs1 << 'Games' @locs2 = [ 'Performing Arts', 'Amphitheater', 'Middle Eastern', 'Æthelmearc 1', 'Æthelmearc 2', 'Touch The Earth', 'Performing Arts Rehearsal', 'Livonia Smithery', 'Pine Box Traders', ].sort @loc_count = {} @locs1.each { |loc| @loc_count[loc] = 0 } @locs2.each { |loc| @loc_count[loc] = 0 } def generate_magic_tokens(instructables) items = instructables.map { |x| [x.formatted_topic, x.name.gsub('*', ''), x.id] }.sort last_topic = nil magic_token = 0 @instructable_magic_tokens = {} items.each do |item| if last_topic != item[0].split(':').first.strip magic_token += 100 - (magic_token % 100) last_topic = item[0].split(':').first.strip end @instructable_magic_tokens[item[2]] = magic_token magic_token += 1 end end instructables = Instructable.where(schedule: 'Pennsic University') generate_magic_tokens(instructables) ids = instructables.map { |x| x.id } instances = Instance.where(instructable_id: ids).includes(:instructable).select { |x| x.scheduled? } instances.each do |instance| if instance.start_time.nil? pp instance next end date = instance.start_time.to_date entries[date] ||= { morning: { loc1: [], loc2: [] }, afternoon: { loc1: [], loc2: [] }, other_location: [], other_time: [], other: [], } hour = instance.start_time.hour morning_check = @morning_hours.index(hour) afternoon_check = @afternoon_hours.index(hour) actual_loc = instance.location.gsub(/ Tent$/, '') loc = instance.instructable.location_nontrack? ? instance.instructable.camp_name : actual_loc loc.gsub!(/ Tent$/, '') loc1_check = @locs1.index(loc) || @locs1.index(actual_loc) loc2_check = @locs2.index(loc) || @locs2.index(actual_loc) @loc_count[loc] ||= 0 @loc_count[loc] += 1 subsection = nil in_loc = false if not (morning_check or afternoon_check) or not (loc1_check or loc2_check) section = :other if (loc1_check or loc2_check) and hour < @morning_hours.first in_loc = true end elsif (loc1_check or loc2_check) and (morning_check) section = :morning subsection = loc1_check ? :loc1 : :loc2 elsif (loc1_check or loc2_check) and (afternoon_check) section = :afternoon subsection = loc1_check ? :loc1 : :loc2 else puts "OTHER:" pp instance section = :other end locindex = (loc1_check || loc2_check) hourindex = (morning_check || afternoon_check) duration = instance.instructable.duration minute = instance.start_time.strftime('%M').to_i if hourindex hourindex += (minute / 60.0) if (hourindex + duration) > 5 display_duration = 5 - hourindex extended_right = true else display_duration = duration extended_right = false end else display_duration = duration extended_right = false end extended_left = false if instance.instructable.name == 'Bellatrix: Individual Session' start_time = "By appointment" section = :other subsection = nil else start_time = instance.start_time end data = { name: instance.instructable.name, start_time: start_time, hourindex: hourindex, locindex: locindex, duration: duration, display_duration: display_duration, id: @instructable_magic_tokens[instance.instructable.id], extended_right: extended_right, extended_left: extended_left, instance: instance, } spot = subsection ? entries[date][section][subsection] : entries[date][section] spot << data if in_loc and (hour + minute / 60.0 + duration > @morning_hours.first) display_duration = duration - (@morning_hours.first - (hour + minute / 60.0)) name = instance.instructable.name name = 'Yoga' if name =~ /^Yoga/ data = { name: name, start_time: start_time, hourindex: 0, locindex: locindex, duration: duration, display_duration: display_duration, id: @instructable_magic_tokens[instance.instructable.id], extended_right: extended_right, extended_left: true, instance: instance, } spot = entries[date][:morning][loc1_check ? :loc1 : :loc2] spot << data end if extended_right and section == :morning display_duration = duration - display_duration if display_duration > 5 display_duration = 5 extended_right = true else extended_right = false end data = { name: instance.instructable.name, start_time: instance.start_time, hourindex: 0, locindex: locindex, duration: duration, display_duration: display_duration, id: @instructable_magic_tokens[instance.instructable.id], extended_right: extended_right, extended_left: true, instance: instance, } spot = entries[date][:afternoon][subsection] spot << data end end def draw_hour_labels(pdf, opts) opts[:hour_labels].count.times do |timeindex| opts[:location_labels].count.times do |locindex| y1 = @header_height + locindex * @row_height x1 = @location_label_width + timeindex * @column_width y2 = y1 + @row_height - 1 x2 = x1 - 1 + @column_width box = pdf.grid([y1, x1], [y2, x2]) box.bounding_box { pdf.stroke_color @grey_dark pdf.fill_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds pdf.stroke_color @black pdf.fill_color @black } end end opts[:hour_labels].each_with_index do |label, labelindex| y1 = @header_height - 1 x1 = @location_label_width + labelindex * @column_width y2 = y1 x2 = x1 + @column_width - 1 box = pdf.grid([y1, x1], [y2, x2]) box.bounding_box { pdf.fill_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.fill_color @black pdf.stroke { #pdf.line [box.width, 0], box.width, box.height pdf.line [0, 0], 0, box.height pdf.line [0, 0], box.width, 0 } } box_opts = { at: [box.top_left[0] + 2, box.top_left[1] - 2], width: box.width - 4, height: box.height - 4, size: 10, overflow: :shrink_to_fit, min_font_size: 6, align: :center, valign: :center, style: :bold, } if label < 12 pdf.text_box "#{label}:00 AM", box_opts else pm = label > 12 ? label - 12 : 12 pdf.text_box "#{pm}:00 PM", box_opts end end end def draw_location_labels(pdf, opts) opts[:location_labels].each_with_index do |label, labelindex| y1 = @header_height + labelindex * @row_height x1 = 0 y2 = y1 + @row_height - 1 x2 = @location_label_width - 1 box = pdf.grid([y1, x1], [y2, x2]) box.bounding_box { pdf.fill_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.fill_color @black pdf.stroke { pdf.line [0, box.height], box.width, box.height pdf.line [0, 0], box.width, 0 pdf.line [box.width, 0], box.width, box.height } } box_opts = { at: [box.top_left[0] + 2, box.top_left[1] - 2], width: box.width - 4, height: box.height - 4, size: 9, overflow: :shrink_to_fit, min_font_size: 8, align: :center, valign: :center, style: :bold, } pdf.text_box label, box_opts end end def render(pdf, opts) debug = false if debug pdf.stroke_axis end pdf.line_width 0.25 pdf.stroke_color @black hour_slots = opts[:hour_labels].count location_slots = opts[:location_labels].count location_slots = 18 if location_slots < 18 pdf.define_grid(columns: hour_slots * 8 + 6, rows: location_slots * 2 + 2 + 1, gutter: 0) if debug (pdf.grid.rows - 1).times do |row| (pdf.grid.columns - 1).times do |column| pdf.grid([row, column], [row + 1, column + 1]).bounding_box do pdf.stroke_color @grey pdf.stroke_bounds end end end pdf.stroke_color @black end box = pdf.grid([0, 0], [@header_height - 1, pdf.grid.columns - 1]) box.bounding_box do pdf.fill_color @grey pdf.stroke_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds end box = pdf.grid([0, 0], [1, pdf.grid.columns - 1]) msg = opts[:title] box_opts = { align: :center, valign: :center, size: @title_font_size, at: [box.top_left[0], box.top_left[1] - 2], width: box.width, height: box.height, } pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text_box msg, box_opts end end pdf.fill_color @black pdf.stroke_color @black draw_hour_labels(pdf, opts) draw_location_labels(pdf, opts) pdf.font_size 12 opts[:entries].each do |data| locindex = data[:locindex] hourindex = data[:hourindex] display_duration = data[:display_duration] duration = data[:duration] extended_right = data[:extended_right] extended_left = data[:extended_left] y1 = @header_height + locindex * @row_height x1 = @location_label_width + hourindex.to_f * @column_width y2 = y1 + @row_height - 1 x2 = x1 - 1 + display_duration * @column_width box = pdf.grid([y1, x1], [y2, x2]) if extended_left at = [box.top_left[0] + 6, box.top_left[1] - 2] else at = [box.top_left[0] + 2, box.top_left[1] - 2] end box_opts = { at: at, width: box.width - 4, height: box.height - 4, size: 9, overflow: :shrink_to_fit, min_font_size: 8, leading: 0, inline_format: true, } box.bounding_box { pdf.fill_color @white pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.fill_color @black pdf.stroke_bounds } msg = "#{markdown_html data[:name]} <i>(#{data[:id]})</i>" if duration != display_duration msg += "<br/><b>(#{duration} hours)</b>" end pdf.text_box msg, box_opts if extended_right coords = [ [box.top_right[0], box.top_right[1]], [box.top_right[0] + 5, (box.top_right[1] + box.bottom_right[1]) / 2], [box.bottom_right[0], box.bottom_right[1]] ] pdf.fill_polygon *coords end if extended_left coords = [ [box.top_left[0], box.top_left[1]], [box.top_left[0] + 5, (box.top_left[1] + box.bottom_left[1]) / 2], [box.bottom_left[0], box.bottom_left[1]] ] pdf.fill_polygon *coords end end end def render_extra(pdf, opts) rowoffset = opts[:rowoffset] box = pdf.grid([rowoffset, 0], [pdf.grid.rows - 1, pdf.grid.columns - 1]) box = pdf.grid([rowoffset, 0], [rowoffset + 1, pdf.grid.columns - 1]) box.bounding_box do pdf.fill_color @grey pdf.stroke_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds end msg = opts[:title] box_opts = { align: :center, valign: :center, size: @title_font_size, at: [box.top_left[0], box.top_left[1] - 2], width: box.width, height: box.height, } pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text_box msg, box_opts end end pdf.stroke_color @black pdf.fill_color @black rowoffset += 2 entries_count = opts[:entries].count if entries_count < 25 font_size = 7.8 + (25 - entries_count) / 10.0 columns = 1 else font_size = 8.5 - (entries_count / 30.0) columns = 2 end first = true box = pdf.grid([rowoffset, 0], [pdf.grid.rows - 1, pdf.grid.columns - 1]) pdf.column_box([box.top_left[0], box.top_left[1] - 3], columns: columns, width: box.width) do opts[:entries].each do |entry| pdf.move_down 2 unless first first = false if entry[:start_time].is_a?(String) start_time = entry[:instance].formatted_location start_time += " (#{entry[:start_time]})" else start_time = entry[:instance].formatted_location_and_time(:pennsic_time_only) end msg = "#{entry[:id]}: #{markdown_html(entry[:name])}, #{start_time}" duration = entry[:duration] if duration != 1 msg += ", #{duration} hours" end pdf.text msg, size: font_size, inline_format: true end end end def render_notes(pdf, opts) rowoffset = opts[:rowoffset] draw_lines = opts[:mode] == :notes draw_box = opts[:mode] == :doodles line_box = pdf.grid([rowoffset + 2, 0], [pdf.grid.rows - 1, pdf.grid.columns - 1]) if draw_box line_box.bounding_box do pdf.stroke_color @grey_40 pdf.fill_color @grey_40 pdf.stroke_bounds end end box = pdf.grid([rowoffset, 0], [rowoffset + 1, pdf.grid.columns - 1]) box.bounding_box do pdf.fill_color @grey pdf.stroke_color @grey pdf.fill { pdf.rectangle [0, box.height], box.width, box.height } pdf.stroke_bounds end msg = opts[:title] box_opts = { align: :center, valign: :center, size: @title_font_size, at: [box.top_left[0], box.top_left[1] - 2], width: box.width, height: box.height, } pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text_box msg, box_opts end end if draw_lines rowoffset += 2 pdf.stroke_color @grey_40 pdf.fill_color @grey_40 spacing = 25 y = spacing pdf.move_down spacing while y < line_box.height pdf.stroke_horizontal_rule pdf.move_down spacing y += spacing end end pdf.stroke_color @black pdf.fill_color @black end def draftit(pdf) return pdf.save_graphics_state do pdf.soft_mask do pdf.rotate(45, origin: [0, 0]) do pdf.fill_color @grey_50 pdf.draw_text "Draft", size: 200, at: [250, 0] pdf.fill_color @black end end pdf.rotate(45, origin: [0, 0]) do pdf.fill_color 'bbbbbb' pdf.draw_text "Draft", size: 200, at: [250, 0] pdf.fill_color @black end end end def materials_and_handout_content(instructable) materials = [] handout = [] handout << "limit: #{instructable.handout_limit}" if instructable.handout_limit materials << "limit: #{instructable.material_limit}" if instructable.material_limit handout << "fee: $#{'%.2f' % instructable.handout_fee}" if instructable.handout_fee materials << "fee: $#{'%.2f' % instructable.material_fee}" if instructable.material_fee handout_content = nil handout_content = 'Handout ' + handout.join(', ') + '. ' if handout.size > 0 materials_content = nil materials_content = 'Materials ' + materials.join(', ') + '. ' if materials.size > 0 [ handout_content, materials_content ].compact end def render_topic_list(pdf, instructables) previous_topic = '' instructables.sort { |a, b| [a.formatted_topic, a.name.gsub('*', '')] <=> [b.formatted_topic, b.name.gsub('*', '')] }.each do |instructable| if instructable.topic != previous_topic pdf.move_down 7 unless pdf.cursor == pdf.bounds.top pdf.font_size @title_font_size pdf.text_rendering_mode(:fill_stroke) do pdf.fill_color @grey_50 pdf.stroke_color @grey_40 pdf.font("TitleFont") do pdf.text instructable.topic end end pdf.font_size 7.5 pdf.fill_color @black pdf.stroke_color @black end previous_topic = instructable.topic pdf.move_down 5 unless pdf.cursor == pdf.bounds.top name = markdown_html(instructable.name, tags_remove: 'strong') token = @instructable_magic_tokens[instructable.id] topic = "Topic: #{instructable.formatted_topic}" culture = instructable.culture.present? ? "Culture: #{instructable.culture}" : nil heading = "<strong>#{token}</strong>: <strong>#{name}</strong>" lines = [ heading, [topic, culture].compact.join(', '), "Instructor: #{instructable.user.titled_sca_name}", ] scheduled_instances = instructable.instances.select { |x| x.scheduled? } if scheduled_instances.count > 1 and scheduled_instances.map(&:formatted_location).uniq.count == 1 lines << 'Taught: ' + scheduled_instances.map { |x| "#{x.start_time.strftime('%a %b %e %I:%M %p')}" }.join(', ') lines << 'Location: ' + scheduled_instances.first.formatted_location else lines << 'Taught: ' + scheduled_instances.map { |x| x.scheduled? ? "#{x.start_time.strftime('%a %b %e %I:%M %p')} #{x.formatted_location}" : nil }.compact.join(', ') end lines << materials_and_handout_content(instructable).join(' ') pdf.text lines.join("\n"), inline_format: true pdf.move_down 2 unless pdf.cursor == pdf.bounds.top pdf.text markdown_html(instructable.description_web.present? ? instructable.description_web : instructable.description_book), inline_format: true, align: :justify end end pdf = Prawn::Document.new(page_size: "LETTER", page_layout: :portrait, compress: true, optimize_objects: true, info: { Title: "Pennsic Schedule", Author: "thing.pennsicuniversity.org", Subject: "Pennsic Schedule", Keywords: "Pennsic Schedule", Creator: "sched.rb", CreationDate: Time.now }) pdf.font_families.update( 'TitleFont' => { normal: { file: Rails.root.join('app', 'assets', 'fonts', 'Arial.ttf') }, }, 'BodyFont' => { normal: Rails.root.join('app', 'assets', 'fonts', 'Arial.ttf'), bold: Rails.root.join('app', 'assets', 'fonts', 'Arial Bold.ttf'), italic: Rails.root.join('app', 'assets', 'fonts', 'Arial Italic.ttf'), bold_italic: Rails.root.join('app', 'assets', 'fonts', 'Arial Bold Italic.ttf'), }, ) pdf.font 'BodyFont' pdf.text "Spacer page" pdf.start_new_page @note_counter = 1 def next_note_type ret = [:notes, :doodles][@note_counter % 2] @note_counter += 1 ret end entries.keys.sort.each do |key| day = key.strftime("%d").to_i date = key.strftime("%A, %B #{day.ordinalize}, A.S. L") render(pdf, location_labels: @locs1, hour_labels: @morning_hours, entries: entries[key][:morning][:loc1], title: "#{date} ~ Morning") draftit(pdf) pdf.start_new_page render(pdf, location_labels: @locs2, hour_labels: @morning_hours, entries: entries[key][:morning][:loc2], title: "#{date} ~ Morning") subentries = entries[key][:other] if subentries.count > 0 subentries.sort! { |a, b| a[:start_time].to_i <=> b[:start_time].to_i } render_extra(pdf, entries: subentries, title: "#{date} ~ Additional Classes", rowoffset: @locs2.count * @row_height + @header_height + 1) else render_notes(pdf, mode: :notes, title: "Notes", rowoffset: @locs2.count * @row_height + @header_height + 1) end draftit(pdf) pdf.start_new_page render(pdf, location_labels: @locs1, hour_labels: @afternoon_hours, entries: entries[key][:afternoon][:loc1], title: "#{date} ~ Afternoon") draftit(pdf) pdf.start_new_page render(pdf, location_labels: @locs2, hour_labels: @afternoon_hours, entries: entries[key][:afternoon][:loc2], title: "#{date} ~ Afternoon") note_type = next_note_type if (@render_notes_and_doodles) render_notes(pdf, mode: note_type, title: (note_type == :notes ? 'Notes' : 'Notes and Doodles'), rowoffset: @locs2.count * @row_height + @header_height + 1) end draftit(pdf) pdf.start_new_page end pdf.font 'BodyFont' pdf.column_box([0, pdf.cursor ], columns: 3, spacer: 6, width: pdf.bounds.width) do render_topic_list(pdf, instructables) end pdf.render_file 'sched.pdf' @loc_count.keys.sort.each { |x| puts (' %2d %s' % [@loc_count[x], x]) }
# frozen_string_literal: true require "delegate" module ActionMailer # The <tt>ActionMailer::MessageDelivery</tt> class is used by # ActionMailer::Base when creating a new mailer. # <tt>MessageDelivery</tt> is a wrapper (+Delegator+ subclass) around a lazy # created <tt>Mail::Message</tt>. You can get direct access to the # <tt>Mail::Message</tt>, deliver the email or schedule the email to be sent # through Active Job. # # Notifier.welcome(User.first) # an ActionMailer::MessageDelivery object # Notifier.welcome(User.first).deliver_now # sends the email # Notifier.welcome(User.first).deliver_later # enqueue email delivery as a job through Active Job # Notifier.welcome(User.first).message # a Mail::Message object class MessageDelivery < Delegator def initialize(mailer_class, action, *args) #:nodoc: @mailer_class, @action, @args = mailer_class, action, args # The mail is only processed if we try to call any methods on it. # Typical usage will leave it unloaded and call deliver_later. @processed_mailer = nil @mail_message = nil end # Method calls are delegated to the Mail::Message that's ready to deliver. def __getobj__ #:nodoc: @mail_message ||= processed_mailer.message end # Unused except for delegator internals (dup, marshaling). def __setobj__(mail_message) #:nodoc: @mail_message = mail_message end # Returns the resulting Mail::Message def message __getobj__ end # Was the delegate loaded, causing the mailer action to be processed? def processed? @processed_mailer || @mail_message end # Enqueues the email to be delivered through Active Job. When the # job runs it will send the email using +deliver_now!+. That means # that the message will be sent bypassing checking +perform_deliveries+ # and +raise_delivery_errors+, so use with caution. # # Notifier.welcome(User.first).deliver_later! # Notifier.welcome(User.first).deliver_later!(wait: 1.hour) # Notifier.welcome(User.first).deliver_later!(wait_until: 10.hours.from_now) # # By default, the email will be enqueued using <tt>ActionMailer::DeliveryJob</tt>. Each # <tt>ActionMailer::Base</tt> class can specify the job to use by setting the class variable # +delivery_job+. # # class AccountRegistrationMailer < ApplicationMailer # self.delivery_job = RegistrationDeliveryJob # end # # Options: # # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time # * <tt>:queue</tt> - Enqueue the email on the specified queue def deliver_later!(options = {}) enqueue_delivery :deliver_now!, options end # Enqueues the email to be delivered through Active Job. When the # job runs it will send the email using +deliver_now+. # # Notifier.welcome(User.first).deliver_later # Notifier.welcome(User.first).deliver_later(wait: 1.hour) # Notifier.welcome(User.first).deliver_later(wait_until: 10.hours.from_now) # # By default, the email will be enqueued using <tt>ActionMailer::DeliveryJob</tt>. Each # <tt>ActionMailer::Base</tt> class can specify the job to use by setting the class variable # +delivery_job+. # # class AccountRegistrationMailer < ApplicationMailer # self.delivery_job = RegistrationDeliveryJob # end # # Options: # # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay. # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time. # * <tt>:queue</tt> - Enqueue the email on the specified queue. def deliver_later(options = {}) enqueue_delivery :deliver_now, options end # Delivers an email without checking +perform_deliveries+ and +raise_delivery_errors+, # so use with caution. # # Notifier.welcome(User.first).deliver_now! # def deliver_now! processed_mailer.handle_exceptions do message.deliver! end end # Delivers an email: # # Notifier.welcome(User.first).deliver_now # def deliver_now processed_mailer.handle_exceptions do message.deliver end end private # Returns the processed Mailer instance. We keep this instance # on hand so we can delegate exception handling to it. def processed_mailer @processed_mailer ||= @mailer_class.new.tap do |mailer| mailer.process @action, *@args end end def enqueue_delivery(delivery_method, options = {}) if processed? ::Kernel.raise "You've accessed the message before asking to " \ "deliver it later, so you may have made local changes that would " \ "be silently lost if we enqueued a job to deliver it. Why? Only " \ "the mailer method *arguments* are passed with the delivery job! " \ "Do not access the message in any way if you mean to deliver it " \ "later. Workarounds: 1. don't touch the message before calling " \ "#deliver_later, 2. only touch the message *within your mailer " \ "method*, or 3. use a custom Active Job instead of #deliver_later." else args = @mailer_class.name, @action.to_s, delivery_method.to_s, *@args job = @mailer_class.delivery_job job.set(options).perform_later(*args) end end end end Move the options for deliver_later up near to the example [ci skip] - And move the Active Job related section down. Otherwise it was appearing as if the options are available for the `delivery_job` setting. # frozen_string_literal: true require "delegate" module ActionMailer # The <tt>ActionMailer::MessageDelivery</tt> class is used by # ActionMailer::Base when creating a new mailer. # <tt>MessageDelivery</tt> is a wrapper (+Delegator+ subclass) around a lazy # created <tt>Mail::Message</tt>. You can get direct access to the # <tt>Mail::Message</tt>, deliver the email or schedule the email to be sent # through Active Job. # # Notifier.welcome(User.first) # an ActionMailer::MessageDelivery object # Notifier.welcome(User.first).deliver_now # sends the email # Notifier.welcome(User.first).deliver_later # enqueue email delivery as a job through Active Job # Notifier.welcome(User.first).message # a Mail::Message object class MessageDelivery < Delegator def initialize(mailer_class, action, *args) #:nodoc: @mailer_class, @action, @args = mailer_class, action, args # The mail is only processed if we try to call any methods on it. # Typical usage will leave it unloaded and call deliver_later. @processed_mailer = nil @mail_message = nil end # Method calls are delegated to the Mail::Message that's ready to deliver. def __getobj__ #:nodoc: @mail_message ||= processed_mailer.message end # Unused except for delegator internals (dup, marshaling). def __setobj__(mail_message) #:nodoc: @mail_message = mail_message end # Returns the resulting Mail::Message def message __getobj__ end # Was the delegate loaded, causing the mailer action to be processed? def processed? @processed_mailer || @mail_message end # Enqueues the email to be delivered through Active Job. When the # job runs it will send the email using +deliver_now!+. That means # that the message will be sent bypassing checking +perform_deliveries+ # and +raise_delivery_errors+, so use with caution. # # Notifier.welcome(User.first).deliver_later! # Notifier.welcome(User.first).deliver_later!(wait: 1.hour) # Notifier.welcome(User.first).deliver_later!(wait_until: 10.hours.from_now) # # Options: # # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time # * <tt>:queue</tt> - Enqueue the email on the specified queue # # By default, the email will be enqueued using <tt>ActionMailer::DeliveryJob</tt>. Each # <tt>ActionMailer::Base</tt> class can specify the job to use by setting the class variable # +delivery_job+. # # class AccountRegistrationMailer < ApplicationMailer # self.delivery_job = RegistrationDeliveryJob # end def deliver_later!(options = {}) enqueue_delivery :deliver_now!, options end # Enqueues the email to be delivered through Active Job. When the # job runs it will send the email using +deliver_now+. # # Notifier.welcome(User.first).deliver_later # Notifier.welcome(User.first).deliver_later(wait: 1.hour) # Notifier.welcome(User.first).deliver_later(wait_until: 10.hours.from_now) # # Options: # # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay. # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time. # * <tt>:queue</tt> - Enqueue the email on the specified queue. # # By default, the email will be enqueued using <tt>ActionMailer::DeliveryJob</tt>. Each # <tt>ActionMailer::Base</tt> class can specify the job to use by setting the class variable # +delivery_job+. # # class AccountRegistrationMailer < ApplicationMailer # self.delivery_job = RegistrationDeliveryJob # end def deliver_later(options = {}) enqueue_delivery :deliver_now, options end # Delivers an email without checking +perform_deliveries+ and +raise_delivery_errors+, # so use with caution. # # Notifier.welcome(User.first).deliver_now! # def deliver_now! processed_mailer.handle_exceptions do message.deliver! end end # Delivers an email: # # Notifier.welcome(User.first).deliver_now # def deliver_now processed_mailer.handle_exceptions do message.deliver end end private # Returns the processed Mailer instance. We keep this instance # on hand so we can delegate exception handling to it. def processed_mailer @processed_mailer ||= @mailer_class.new.tap do |mailer| mailer.process @action, *@args end end def enqueue_delivery(delivery_method, options = {}) if processed? ::Kernel.raise "You've accessed the message before asking to " \ "deliver it later, so you may have made local changes that would " \ "be silently lost if we enqueued a job to deliver it. Why? Only " \ "the mailer method *arguments* are passed with the delivery job! " \ "Do not access the message in any way if you mean to deliver it " \ "later. Workarounds: 1. don't touch the message before calling " \ "#deliver_later, 2. only touch the message *within your mailer " \ "method*, or 3. use a custom Active Job instead of #deliver_later." else args = @mailer_class.name, @action.to_s, delivery_method.to_s, *@args job = @mailer_class.delivery_job job.set(options).perform_later(*args) end end end end
module ActionView # = Action View Cache Helper module Helpers module CacheHelper # This helper exposes a method for caching fragments of a view # rather than an entire action or page. This technique is useful # caching pieces like menus, lists of newstopics, static HTML # fragments, and so on. This method takes a block that contains # the content you wish to cache. # # See ActionController::Caching::Fragments for usage instructions. # # ==== Examples # If you want to cache a navigation menu, you can do following: # # <% cache do %> # <%= render :partial => "menu" %> # <% end %> # # You can also cache static content: # # <% cache do %> # <p>Hello users! Welcome to our website!</p> # <% end %> # # Static content with embedded ruby content can be cached as # well: # # <% cache do %> # Topics: # <%= render :partial => "topics", :collection => @topic_list %> # <i>Topics listed alphabetically</i> # <% end %> def cache(name = {}, options = nil, &block) if controller.perform_caching safe_concat(fragment_for(name, options, &block)) else yield end nil end private # TODO: Create an object that has caching read/write on it def fragment_for(name = {}, options = nil, &block) #:nodoc: if fragment = controller.read_fragment(name, options) fragment else # VIEW TODO: Make #capture usable outside of ERB # This dance is needed because Builder can't use capture pos = output_buffer.length yield safe_output_buffer = output_buffer.to_str fragment = safe_output_buffer.slice!(pos..-1) self.output_buffer = ActionView::OutputBuffer.new(safe_output_buffer) controller.write_fragment(name, fragment, options) end end end end end Adapt [823aa223efbac6ad4d31ea33402892267bb77cb4] to make sure we perform cloning before manipulation only on `OutputBuffer`. After the fragment rendering, `Builder` returns the `String` object instead of `ActionView::OutputBuffer`. Somehow the same procedure which was in [823aa223efbac6ad4d31ea33402892267bb77cb4] does not play nice with the String, and result in the fragment got lost. module ActionView # = Action View Cache Helper module Helpers module CacheHelper # This helper exposes a method for caching fragments of a view # rather than an entire action or page. This technique is useful # caching pieces like menus, lists of newstopics, static HTML # fragments, and so on. This method takes a block that contains # the content you wish to cache. # # See ActionController::Caching::Fragments for usage instructions. # # ==== Examples # If you want to cache a navigation menu, you can do following: # # <% cache do %> # <%= render :partial => "menu" %> # <% end %> # # You can also cache static content: # # <% cache do %> # <p>Hello users! Welcome to our website!</p> # <% end %> # # Static content with embedded ruby content can be cached as # well: # # <% cache do %> # Topics: # <%= render :partial => "topics", :collection => @topic_list %> # <i>Topics listed alphabetically</i> # <% end %> def cache(name = {}, options = nil, &block) if controller.perform_caching safe_concat(fragment_for(name, options, &block)) else yield end nil end private # TODO: Create an object that has caching read/write on it def fragment_for(name = {}, options = nil, &block) #:nodoc: if fragment = controller.read_fragment(name, options) fragment else # VIEW TODO: Make #capture usable outside of ERB # This dance is needed because Builder can't use capture pos = output_buffer.length yield if output_buffer.is_a?(ActionView::OutputBuffer) safe_output_buffer = output_buffer.to_str fragment = safe_output_buffer.slice!(pos..-1) self.output_buffer = ActionView::OutputBuffer.new(safe_output_buffer) else fragment = output_buffer.slice!(pos..-1) end controller.write_fragment(name, fragment, options) end end end end end
require 'abstract_unit' class JavaScriptHelperTest < ActionView::TestCase tests ActionView::Helpers::JavaScriptHelper def _evaluate_assigns_and_ivars() end attr_accessor :formats, :output_buffer def update_details(details) @details = details yield if block_given? end def setup super ActiveSupport.escape_html_entities_in_json = true @template = self end def teardown ActiveSupport.escape_html_entities_in_json = false end def _evaluate_assigns_and_ivars() end def test_escape_javascript assert_equal '', escape_javascript(nil) assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos')) assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) ) assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags)) end def test_button_to_function assert_dom_equal %(<input type="button" onclick="alert('Hello world!');" value="Greeting" />), button_to_function("Greeting", "alert('Hello world!')") end def test_button_to_function_with_rjs_block html = button_to_function( "Greet me!" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<input type="button" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);;" value="Greet me!" />), html end def test_button_to_function_with_rjs_block_and_options html = button_to_function( "Greet me!", :class => "greeter" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<input type="button" class="greeter" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C\/h1\\u003E&quot;);;" value="Greet me!" />), html end def test_button_to_function_with_onclick assert_dom_equal "<input onclick=\"alert('Goodbye World :('); alert('Hello world!');\" type=\"button\" value=\"Greeting\" />", button_to_function("Greeting", "alert('Hello world!')", :onclick => "alert('Goodbye World :(')") end def test_button_to_function_without_function assert_dom_equal "<input onclick=\";\" type=\"button\" value=\"Greeting\" />", button_to_function("Greeting") end def test_link_to_function assert_dom_equal %(<a href="#" onclick="alert('Hello world!'); return false;">Greeting</a>), link_to_function("Greeting", "alert('Hello world!')") end def test_link_to_function_with_existing_onclick assert_dom_equal %(<a href="#" onclick="confirm('Sanity!'); alert('Hello world!'); return false;">Greeting</a>), link_to_function("Greeting", "alert('Hello world!')", :onclick => "confirm('Sanity!')") end def test_link_to_function_with_rjs_block html = link_to_function( "Greet me!" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<a href="#" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);; return false;">Greet me!</a>), html end def test_link_to_function_with_rjs_block_and_options html = link_to_function( "Greet me!", :class => "updater" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<a href="#" class="updater" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);; return false;">Greet me!</a>), html end def test_link_to_function_with_href assert_dom_equal %(<a href="http://example.com/" onclick="alert('Hello world!'); return false;">Greeting</a>), link_to_function("Greeting", "alert('Hello world!')", :href => 'http://example.com/') end def test_link_to_function_with_inner_block_does_not_raise_exception html = link_to_function( "Greet me!" ) do |page| page.replace_html 'header', (content_tag :h1 do 'Greetings' end) end assert_dom_equal %(<a href="#" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);; return false;">Greet me!</a>), html end def test_javascript_tag self.output_buffer = 'foo' assert_dom_equal "<script type=\"text/javascript\">\n//<![CDATA[\nalert('hello')\n//]]>\n</script>", javascript_tag("alert('hello')") assert_equal 'foo', output_buffer, 'javascript_tag without a block should not concat to output_buffer' end def test_javascript_tag_with_options assert_dom_equal "<script id=\"the_js_tag\" type=\"text/javascript\">\n//<![CDATA[\nalert('hello')\n//]]>\n</script>", javascript_tag("alert('hello')", :id => "the_js_tag") end def test_javascript_cdata_section assert_dom_equal "\n//<![CDATA[\nalert('hello')\n//]]>\n", javascript_cdata_section("alert('hello')") end end Remove duplicated method. require 'abstract_unit' class JavaScriptHelperTest < ActionView::TestCase tests ActionView::Helpers::JavaScriptHelper def _evaluate_assigns_and_ivars() end attr_accessor :formats, :output_buffer def update_details(details) @details = details yield if block_given? end def setup super ActiveSupport.escape_html_entities_in_json = true @template = self end def teardown ActiveSupport.escape_html_entities_in_json = false end def test_escape_javascript assert_equal '', escape_javascript(nil) assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos')) assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) ) assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags)) end def test_button_to_function assert_dom_equal %(<input type="button" onclick="alert('Hello world!');" value="Greeting" />), button_to_function("Greeting", "alert('Hello world!')") end def test_button_to_function_with_rjs_block html = button_to_function( "Greet me!" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<input type="button" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);;" value="Greet me!" />), html end def test_button_to_function_with_rjs_block_and_options html = button_to_function( "Greet me!", :class => "greeter" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<input type="button" class="greeter" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C\/h1\\u003E&quot;);;" value="Greet me!" />), html end def test_button_to_function_with_onclick assert_dom_equal "<input onclick=\"alert('Goodbye World :('); alert('Hello world!');\" type=\"button\" value=\"Greeting\" />", button_to_function("Greeting", "alert('Hello world!')", :onclick => "alert('Goodbye World :(')") end def test_button_to_function_without_function assert_dom_equal "<input onclick=\";\" type=\"button\" value=\"Greeting\" />", button_to_function("Greeting") end def test_link_to_function assert_dom_equal %(<a href="#" onclick="alert('Hello world!'); return false;">Greeting</a>), link_to_function("Greeting", "alert('Hello world!')") end def test_link_to_function_with_existing_onclick assert_dom_equal %(<a href="#" onclick="confirm('Sanity!'); alert('Hello world!'); return false;">Greeting</a>), link_to_function("Greeting", "alert('Hello world!')", :onclick => "confirm('Sanity!')") end def test_link_to_function_with_rjs_block html = link_to_function( "Greet me!" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<a href="#" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);; return false;">Greet me!</a>), html end def test_link_to_function_with_rjs_block_and_options html = link_to_function( "Greet me!", :class => "updater" ) do |page| page.replace_html 'header', "<h1>Greetings</h1>" end assert_dom_equal %(<a href="#" class="updater" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);; return false;">Greet me!</a>), html end def test_link_to_function_with_href assert_dom_equal %(<a href="http://example.com/" onclick="alert('Hello world!'); return false;">Greeting</a>), link_to_function("Greeting", "alert('Hello world!')", :href => 'http://example.com/') end def test_link_to_function_with_inner_block_does_not_raise_exception html = link_to_function( "Greet me!" ) do |page| page.replace_html 'header', (content_tag :h1 do 'Greetings' end) end assert_dom_equal %(<a href="#" onclick="Element.update(&quot;header&quot;, &quot;\\u003Ch1\\u003EGreetings\\u003C/h1\\u003E&quot;);; return false;">Greet me!</a>), html end def test_javascript_tag self.output_buffer = 'foo' assert_dom_equal "<script type=\"text/javascript\">\n//<![CDATA[\nalert('hello')\n//]]>\n</script>", javascript_tag("alert('hello')") assert_equal 'foo', output_buffer, 'javascript_tag without a block should not concat to output_buffer' end def test_javascript_tag_with_options assert_dom_equal "<script id=\"the_js_tag\" type=\"text/javascript\">\n//<![CDATA[\nalert('hello')\n//]]>\n</script>", javascript_tag("alert('hello')", :id => "the_js_tag") end def test_javascript_cdata_section assert_dom_equal "\n//<![CDATA[\nalert('hello')\n//]]>\n", javascript_cdata_section("alert('hello')") end end
module ActiveModel module Validations module ClassMethods # Validates whether the value of the specified attribute is of the correct form, going by the regular expression provided. # You can require that the attribute matches the regular expression: # # class Person < ActiveRecord::Base # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create # end # # Alternatively, you can require that the specified attribute does _not_ match the regular expression: # # class Person < ActiveRecord::Base # validates_format_of :email, :without => /NOSPAM/ # end # # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line. # # You must pass either <tt>:with</tt> or <tt>:without</tt> as an option. In addition, both must be a regular expression, # or else an exception will be raised. # # Configuration options: # * <tt>:message</tt> - A custom error message (default is: "is invalid"). # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+). # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+). # * <tt>:with</tt> - Regular expression that if the attribute matches will result in a successful validation. # * <tt>:without</tt> - Regular expression that if the attribute does not match will result in a successful validation. # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>). # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The # method, proc or string should return or evaluate to a true or false value. # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The # method, proc or string should return or evaluate to a true or false value. def validates_format_of(*attr_names) configuration = attr_names.extract_options! unless configuration.include?(:with) ^ configuration.include?(:without) # ^ == xor, or "exclusive or" raise ArgumentError, "Either :with or :without must be supplied (but not both)" end if configuration[:with] && !configuration[:with].is_a?(Regexp) raise ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash" end if configuration[:without] && !configuration[:without].is_a?(Regexp) raise ArgumentError, "A regular expression must be supplied as the :without option of the configuration hash" end validates_each(attr_names, configuration) do |record, attr_name, value| if configuration[:with] && value.to_s !~ configuration[:with] record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) end if configuration[:without] && value.to_s =~ configuration[:without] record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) end end end end end end Move :with/:without check outside the method generated by validates_format_of module ActiveModel module Validations module ClassMethods # Validates whether the value of the specified attribute is of the correct form, going by the regular expression provided. # You can require that the attribute matches the regular expression: # # class Person < ActiveRecord::Base # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create # end # # Alternatively, you can require that the specified attribute does _not_ match the regular expression: # # class Person < ActiveRecord::Base # validates_format_of :email, :without => /NOSPAM/ # end # # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line. # # You must pass either <tt>:with</tt> or <tt>:without</tt> as an option. In addition, both must be a regular expression, # or else an exception will be raised. # # Configuration options: # * <tt>:message</tt> - A custom error message (default is: "is invalid"). # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+). # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+). # * <tt>:with</tt> - Regular expression that if the attribute matches will result in a successful validation. # * <tt>:without</tt> - Regular expression that if the attribute does not match will result in a successful validation. # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>). # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The # method, proc or string should return or evaluate to a true or false value. # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The # method, proc or string should return or evaluate to a true or false value. def validates_format_of(*attr_names) configuration = attr_names.extract_options! unless configuration.include?(:with) ^ configuration.include?(:without) # ^ == xor, or "exclusive or" raise ArgumentError, "Either :with or :without must be supplied (but not both)" end if configuration[:with] && !configuration[:with].is_a?(Regexp) raise ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash" end if configuration[:without] && !configuration[:without].is_a?(Regexp) raise ArgumentError, "A regular expression must be supplied as the :without option of the configuration hash" end if configuration[:with] validates_each(attr_names, configuration) do |record, attr_name, value| record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) if value.to_s !~ configuration[:with] end elsif configuration[:without] validates_each(attr_names, configuration) do |record, attr_name, value| record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) if value.to_s =~ configuration[:without] end end end end end end
require 'active_support/values/time_zone' require 'active_support/core_ext/object/acts_like' module ActiveSupport # A Time-like class that can represent a time in any time zone. Necessary # because standard Ruby Time instances are limited to UTC and the # system's <tt>ENV['TZ']</tt> zone. # # You shouldn't ever need to create a TimeWithZone instance directly via +new+. # Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances, # and +in_time_zone+ on Time and DateTime instances. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00 # Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # # See Time and TimeZone for further documentation of these methods. # # TimeWithZone instances implement the same API as Ruby Time instances, so # that Time and TimeWithZone instances are interchangeable. # # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00 # t.hour # => 13 # t.dst? # => true # t.utc_offset # => -14400 # t.zone # => "EDT" # t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400" # t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00 # t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00 # t > Time.utc(1999) # => true # t.is_a?(Time) # => true # t.is_a?(ActiveSupport::TimeWithZone) # => true class TimeWithZone # Report class name as 'Time' to thwart type checking. def self.name 'Time' end include Comparable attr_reader :time_zone def initialize(utc_time, time_zone, local_time = nil, period = nil) @utc, @time_zone, @time = utc_time, time_zone, local_time @period = @utc ? period : get_period_and_ensure_valid_local_time(period) end # Returns a Time or DateTime instance that represents the time in +time_zone+. def time @time ||= period.to_local(@utc) end # Returns a Time or DateTime instance that represents the time in UTC. def utc @utc ||= period.to_utc(@time) end alias_method :comparable_time, :utc alias_method :getgm, :utc alias_method :getutc, :utc alias_method :gmtime, :utc # Returns the underlying TZInfo::TimezonePeriod. def period @period ||= time_zone.period_for_utc(@utc) end # Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone. def in_time_zone(new_zone = ::Time.zone) return self if time_zone == new_zone utc.in_time_zone(new_zone) end # Returns a <tt>Time.local()</tt> instance of the simultaneous time in your # system's <tt>ENV['TZ']</tt> zone. def localtime(utc_offset = nil) utc.respond_to?(:getlocal) ? utc.getlocal(utc_offset) : utc.to_time.getlocal(utc_offset) end alias_method :getlocal, :localtime # Returns true if the current time is within Daylight Savings Time for the # specified time zone. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # Time.zone.parse("2012-5-30").dst? # => true # Time.zone.parse("2012-11-30").dst? # => false def dst? period.dst? end alias_method :isdst, :dst? # Returns true if the current time zone is set to UTC. # # Time.zone = 'UTC' # => 'UTC' # Time.zone.now.utc? # => true # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # Time.zone.now.utc? # => false def utc? time_zone.name == 'UTC' end alias_method :gmt?, :utc? # Returns the offset from current time to UTC time in seconds. def utc_offset period.utc_total_offset end alias_method :gmt_offset, :utc_offset alias_method :gmtoff, :utc_offset # Returns a formatted string of the offset from UTC, or an alternative # string if the time zone is already UTC. # # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" # Time.zone.now.formatted_offset(true) # => "-05:00" # Time.zone.now.formatted_offset(false) # => "-0500" # Time.zone = 'UTC' # => "UTC" # Time.zone.now.formatted_offset(true, "0") # => "0" def formatted_offset(colon = true, alternate_utc_string = nil) utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) end # Returns the time zone abbreviation. # # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" # Time.zone.now.zone # => "EST" def zone period.zone_identifier.to_s end # Returns a string of the object's date, time, zone and offset from UTC. # # Time.zone.now.httpdate # => "Thu, 04 Dec 2014 11:00:25 EST -05:00" def inspect "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}" end # Returns a string of the object's date and time in the ISO 8601 standard # format. # # Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00" def xmlschema(fraction_digits = 0) fraction = if fraction_digits.to_i > 0 (".%06i" % time.usec)[0, fraction_digits.to_i + 1] end "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}" end alias_method :iso8601, :xmlschema # Coerces time to a string for JSON encoding. The default format is ISO 8601. # You can get %Y/%m/%d %H:%M:%S +offset style by setting # <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt> # to +false+. # # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json # # => "2005-02-01T05:15:10.000-10:00" # # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json # # => "2005/02/01 05:15:10 -1000" def as_json(options = nil) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema(ActiveSupport::JSON::Encoding.time_precision) else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end def encode_with(coder) if coder.respond_to?(:represent_object) coder.represent_object(nil, utc) else coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ")) end end # Returns a string of the object's date and time in the format used by # HTTP requests. # # Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT" def httpdate utc.httpdate end # Returns a string of the object's date and time in the RFC 2822 standard # format. # # Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000" def rfc2822 to_s(:rfc822) end alias_method :rfc822, :rfc2822 # Returns a string of the object's date and time. # Accepts an optional <tt>format</tt>: # * <tt>:default</tt> - default value, mimics Ruby 1.9 Time#to_s format. # * <tt>:db</tt> - format outputs time in UTC :db time. See Time#to_formatted_s(:db). # * Any key in <tt>Time::DATE_FORMATS</tt> can be used. See active_support/core_ext/time/conversions.rb. def to_s(format = :default) if format == :db utc.to_s(format) elsif formatter = ::Time::DATE_FORMATS[format] formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) else "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format end end alias_method :to_formatted_s, :to_s # Replaces <tt>%Z</tt> directive with +zone before passing to Time#strftime, # so that zone information is correct. def strftime(format) format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}") getlocal(utc_offset).strftime(format) end # Use the time in UTC for comparisons. def <=>(other) utc <=> other end # Returns true if the current object's time is within the specified # +min+ and +max+ time. def between?(min, max) utc.between?(min, max) end # Returns true if the current object's time is in the past. def past? utc.past? end # Returns true if the current object's time falls within # the current day. def today? time.today? end # Returns true if the current object's time is in the future. def future? utc.future? end def eql?(other) utc.eql?(other) end def hash utc.hash end # Adds an interval of time to the current object's time and return that # value as a new TimeWithZone object. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 # now + 1000 # => Sun, 02 Nov 2014 01:43:08 EDT -04:00 # # If we're adding a Duration of variable length (i.e., years, months, days), # move forward from #time, otherwise move forward from #utc, for accuracy # when moving across DST boundaries. # # For instance, a time + 24.hours will advance exactly 24 hours, while a # time + 1.day will advance 23-25 hours, depending on the day. # # now + 24.hours # => Mon, 03 Nov 2014 00:26:28 EST -05:00 # now + 1.day # => Mon, 03 Nov 2014 01:26:28 EST -05:00 def +(other) if duration_of_variable_length?(other) method_missing(:+, other) else result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other) result.in_time_zone(time_zone) end end # Returns a new TimeWithZone object that represents the difference between # the current object's time and the +other+ time. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EST -05:00 # now - 1000 # => Sun, 02 Nov 2014 01:09:48 EST -05:00 # # If subtracting a Duration of variable length (i.e., years, months, days), # move backward from #time, otherwise move backward from #utc, for accuracy # when moving across DST boundaries. # # For instance, a time - 24.hours will go subtract exactly 24 hours, while a # time - 1.day will subtract 23-25 hours, depending on the day. # # now - 24.hours # => Sat, 01 Nov 2014 02:26:28 EDT -04:00 # now - 1.day # => Sat, 01 Nov 2014 01:26:28 EDT -04:00 def -(other) if other.acts_like?(:time) to_time - other.to_time elsif duration_of_variable_length?(other) method_missing(:-, other) else result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other) result.in_time_zone(time_zone) end end def since(other) # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time, # otherwise move forward from #utc, for accuracy when moving across DST boundaries if duration_of_variable_length?(other) method_missing(:since, other) else utc.since(other).in_time_zone(time_zone) end end def ago(other) since(-other) end def advance(options) # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, # otherwise advance from #utc, for accuracy when moving across DST boundaries if options.values_at(:years, :weeks, :months, :days).any? method_missing(:advance, options) else utc.advance(options).in_time_zone(time_zone) end end %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name| class_eval <<-EOV, __FILE__, __LINE__ + 1 def #{method_name} # def month time.#{method_name} # time.month end # end EOV end def to_a [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone] end # Returns the object's date and time as a floating point number of seconds # since the Epoch (January 1, 1970 00:00 UTC). # # Time.zone.now.to_f # => 1417709320.285418 def to_f utc.to_f end # Returns the object's date and time as an integer number of seconds # since the Epoch (January 1, 1970 00:00 UTC). # # Time.zone.now.to_i # => 1417709320 def to_i utc.to_i end alias_method :tv_sec, :to_i # Returns the object's date and time as a rational number of seconds # since the Epoch (January 1, 1970 00:00 UTC). # # Time.zone.now.to_r # => (708854548642709/500000) def to_r utc.to_r end # Return an instance of Time in the system timezone. def to_time utc.to_time end def to_datetime utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) end # So that +self+ <tt>acts_like?(:time)</tt>. def acts_like_time? true end # Say we're a Time to thwart type checking. def is_a?(klass) klass == ::Time || super end alias_method :kind_of?, :is_a? def freeze period; utc; time # preload instance variables before freezing super end def marshal_dump [utc, time_zone.name, time] end def marshal_load(variables) initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc) end # respond_to_missing? is not called in some cases, such as when type conversion is # performed with Kernel#String def respond_to?(sym, include_priv = false) # ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow return false if sym.to_sym == :to_str super end # Ensure proxy class responds to all methods that underlying time instance # responds to. def respond_to_missing?(sym, include_priv) # consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime return false if sym.to_sym == :acts_like_date? time.respond_to?(sym, include_priv) end # Send the missing method to +time+ instance, and wrap result in a new # TimeWithZone with the existing +time_zone+. def method_missing(sym, *args, &block) wrap_with_time_zone time.__send__(sym, *args, &block) rescue NoMethodError => e raise e, e.message.sub(time.inspect, self.inspect), e.backtrace end private def get_period_and_ensure_valid_local_time(period) # we don't want a Time.local instance enforcing its own DST rules as well, # so transfer time values to a utc constructor if necessary @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc? begin period || @time_zone.period_for_local(@time) rescue ::TZInfo::PeriodNotFound # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again @time += 1.hour retry end end def transfer_time_values_to_utc_constructor(time) ::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1000)) end def duration_of_variable_length?(obj) ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) } end def wrap_with_time_zone(time) if time.acts_like?(:time) periods = time_zone.periods_for_local(time) self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil) elsif time.is_a?(Range) wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end) else time end end end end Replace AS::TimeWithZone#since with alias to + Stems from [Google group discussion](https://groups.google.com/forum/#!topic/rubyonrails-core/jSPbP-TNLb0). Currently `AS::TimeWithZone` has two methods to add an interval to a time: `+(other)` and `since(other)` ([docs](http://edgeapi.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html)). The two methods are "pretty much" equivalent in every case: 1. When adding any interval to an `AS::TimeWithZone` representing a `Time`: ```ruby t = Time.now.in_time_zone #=> Thu, 04 Dec 2014 18:56:28 EST -05:00 t + 1 == t.since(1) #=> true t + 1.day == t.since(1.day) #=> true t + 1.month == t.since(1.month) #=> true ``` 2. When adding any interval to an `AS::TimeWithZone` representing a `Date`: ```ruby d = Date.today.in_time_zone #=> Thu, 04 Dec 2014 00:00:00 EST -05:00 d + 1 == d.since(1) #=> true d + 1.day == d.since(1.day) #=> true d + 1.month == d.since(1.month) #=> true ``` 3. When adding any interval to an `AS::TimeWithZone` representing a `DateTime`: ```ruby dt = DateTime.now.in_time_zone #=> Thu, 04 Dec 2014 18:57:28 EST -05:00 dt + 1 == dt.since(1) #=> true dt + 1.day == dt.since(1.day) #=> true dt + 1.month == dt.since(1.month) #=> false ``` As you can see, the only case in which they differ is when the interval added to a `DateTime` is in a format like `1.month`. However, this usage of "since" is explicitly discouraged by the [documentation of `DateTime#since`](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/date_time/calculations.rb#L86L88): > Returns a new DateTime representing the time a number of seconds since the instance time. > Do not use this method in combination with x.months, use months_since instead! And indeed, following this recommendation the correct result is returned: ```ruby dt + 1.month == dt.months_since 1 #=> true ``` Therefore, my proposal is to remove the method definition of `TimeWithZone#since` and instead replace it with a simple `alias_method :since, :+`. The rationale is that the only case where they differ is a case that is explicitly discouraged as "wrong". In my opinion, having two methods named `since` and `+` and having to figure out exactly what the difference is makes the codebase more confusing. However, I understand this PR is "subjective", so if you feel like it's better to ignore this, feel free to close the PR. Thanks! require 'active_support/values/time_zone' require 'active_support/core_ext/object/acts_like' module ActiveSupport # A Time-like class that can represent a time in any time zone. Necessary # because standard Ruby Time instances are limited to UTC and the # system's <tt>ENV['TZ']</tt> zone. # # You shouldn't ever need to create a TimeWithZone instance directly via +new+. # Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances, # and +in_time_zone+ on Time and DateTime instances. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00 # Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00 # # See Time and TimeZone for further documentation of these methods. # # TimeWithZone instances implement the same API as Ruby Time instances, so # that Time and TimeWithZone instances are interchangeable. # # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00 # t.hour # => 13 # t.dst? # => true # t.utc_offset # => -14400 # t.zone # => "EDT" # t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400" # t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00 # t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00 # t > Time.utc(1999) # => true # t.is_a?(Time) # => true # t.is_a?(ActiveSupport::TimeWithZone) # => true class TimeWithZone # Report class name as 'Time' to thwart type checking. def self.name 'Time' end include Comparable attr_reader :time_zone def initialize(utc_time, time_zone, local_time = nil, period = nil) @utc, @time_zone, @time = utc_time, time_zone, local_time @period = @utc ? period : get_period_and_ensure_valid_local_time(period) end # Returns a Time or DateTime instance that represents the time in +time_zone+. def time @time ||= period.to_local(@utc) end # Returns a Time or DateTime instance that represents the time in UTC. def utc @utc ||= period.to_utc(@time) end alias_method :comparable_time, :utc alias_method :getgm, :utc alias_method :getutc, :utc alias_method :gmtime, :utc # Returns the underlying TZInfo::TimezonePeriod. def period @period ||= time_zone.period_for_utc(@utc) end # Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone. def in_time_zone(new_zone = ::Time.zone) return self if time_zone == new_zone utc.in_time_zone(new_zone) end # Returns a <tt>Time.local()</tt> instance of the simultaneous time in your # system's <tt>ENV['TZ']</tt> zone. def localtime(utc_offset = nil) utc.respond_to?(:getlocal) ? utc.getlocal(utc_offset) : utc.to_time.getlocal(utc_offset) end alias_method :getlocal, :localtime # Returns true if the current time is within Daylight Savings Time for the # specified time zone. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # Time.zone.parse("2012-5-30").dst? # => true # Time.zone.parse("2012-11-30").dst? # => false def dst? period.dst? end alias_method :isdst, :dst? # Returns true if the current time zone is set to UTC. # # Time.zone = 'UTC' # => 'UTC' # Time.zone.now.utc? # => true # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # Time.zone.now.utc? # => false def utc? time_zone.name == 'UTC' end alias_method :gmt?, :utc? # Returns the offset from current time to UTC time in seconds. def utc_offset period.utc_total_offset end alias_method :gmt_offset, :utc_offset alias_method :gmtoff, :utc_offset # Returns a formatted string of the offset from UTC, or an alternative # string if the time zone is already UTC. # # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" # Time.zone.now.formatted_offset(true) # => "-05:00" # Time.zone.now.formatted_offset(false) # => "-0500" # Time.zone = 'UTC' # => "UTC" # Time.zone.now.formatted_offset(true, "0") # => "0" def formatted_offset(colon = true, alternate_utc_string = nil) utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) end # Returns the time zone abbreviation. # # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" # Time.zone.now.zone # => "EST" def zone period.zone_identifier.to_s end # Returns a string of the object's date, time, zone and offset from UTC. # # Time.zone.now.httpdate # => "Thu, 04 Dec 2014 11:00:25 EST -05:00" def inspect "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}" end # Returns a string of the object's date and time in the ISO 8601 standard # format. # # Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00" def xmlschema(fraction_digits = 0) fraction = if fraction_digits.to_i > 0 (".%06i" % time.usec)[0, fraction_digits.to_i + 1] end "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}" end alias_method :iso8601, :xmlschema # Coerces time to a string for JSON encoding. The default format is ISO 8601. # You can get %Y/%m/%d %H:%M:%S +offset style by setting # <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt> # to +false+. # # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json # # => "2005-02-01T05:15:10.000-10:00" # # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json # # => "2005/02/01 05:15:10 -1000" def as_json(options = nil) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema(ActiveSupport::JSON::Encoding.time_precision) else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end def encode_with(coder) if coder.respond_to?(:represent_object) coder.represent_object(nil, utc) else coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ")) end end # Returns a string of the object's date and time in the format used by # HTTP requests. # # Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT" def httpdate utc.httpdate end # Returns a string of the object's date and time in the RFC 2822 standard # format. # # Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000" def rfc2822 to_s(:rfc822) end alias_method :rfc822, :rfc2822 # Returns a string of the object's date and time. # Accepts an optional <tt>format</tt>: # * <tt>:default</tt> - default value, mimics Ruby 1.9 Time#to_s format. # * <tt>:db</tt> - format outputs time in UTC :db time. See Time#to_formatted_s(:db). # * Any key in <tt>Time::DATE_FORMATS</tt> can be used. See active_support/core_ext/time/conversions.rb. def to_s(format = :default) if format == :db utc.to_s(format) elsif formatter = ::Time::DATE_FORMATS[format] formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) else "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format end end alias_method :to_formatted_s, :to_s # Replaces <tt>%Z</tt> directive with +zone before passing to Time#strftime, # so that zone information is correct. def strftime(format) format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}") getlocal(utc_offset).strftime(format) end # Use the time in UTC for comparisons. def <=>(other) utc <=> other end # Returns true if the current object's time is within the specified # +min+ and +max+ time. def between?(min, max) utc.between?(min, max) end # Returns true if the current object's time is in the past. def past? utc.past? end # Returns true if the current object's time falls within # the current day. def today? time.today? end # Returns true if the current object's time is in the future. def future? utc.future? end def eql?(other) utc.eql?(other) end def hash utc.hash end # Adds an interval of time to the current object's time and return that # value as a new TimeWithZone object. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 # now + 1000 # => Sun, 02 Nov 2014 01:43:08 EDT -04:00 # # If we're adding a Duration of variable length (i.e., years, months, days), # move forward from #time, otherwise move forward from #utc, for accuracy # when moving across DST boundaries. # # For instance, a time + 24.hours will advance exactly 24 hours, while a # time + 1.day will advance 23-25 hours, depending on the day. # # now + 24.hours # => Mon, 03 Nov 2014 00:26:28 EST -05:00 # now + 1.day # => Mon, 03 Nov 2014 01:26:28 EST -05:00 def +(other) if duration_of_variable_length?(other) method_missing(:+, other) else result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other) result.in_time_zone(time_zone) end end alias_method :since, :+ # Returns a new TimeWithZone object that represents the difference between # the current object's time and the +other+ time. # # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EST -05:00 # now - 1000 # => Sun, 02 Nov 2014 01:09:48 EST -05:00 # # If subtracting a Duration of variable length (i.e., years, months, days), # move backward from #time, otherwise move backward from #utc, for accuracy # when moving across DST boundaries. # # For instance, a time - 24.hours will go subtract exactly 24 hours, while a # time - 1.day will subtract 23-25 hours, depending on the day. # # now - 24.hours # => Sat, 01 Nov 2014 02:26:28 EDT -04:00 # now - 1.day # => Sat, 01 Nov 2014 01:26:28 EDT -04:00 def -(other) if other.acts_like?(:time) to_time - other.to_time elsif duration_of_variable_length?(other) method_missing(:-, other) else result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other) result.in_time_zone(time_zone) end end def ago(other) since(-other) end def advance(options) # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, # otherwise advance from #utc, for accuracy when moving across DST boundaries if options.values_at(:years, :weeks, :months, :days).any? method_missing(:advance, options) else utc.advance(options).in_time_zone(time_zone) end end %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name| class_eval <<-EOV, __FILE__, __LINE__ + 1 def #{method_name} # def month time.#{method_name} # time.month end # end EOV end def to_a [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone] end # Returns the object's date and time as a floating point number of seconds # since the Epoch (January 1, 1970 00:00 UTC). # # Time.zone.now.to_f # => 1417709320.285418 def to_f utc.to_f end # Returns the object's date and time as an integer number of seconds # since the Epoch (January 1, 1970 00:00 UTC). # # Time.zone.now.to_i # => 1417709320 def to_i utc.to_i end alias_method :tv_sec, :to_i # Returns the object's date and time as a rational number of seconds # since the Epoch (January 1, 1970 00:00 UTC). # # Time.zone.now.to_r # => (708854548642709/500000) def to_r utc.to_r end # Return an instance of Time in the system timezone. def to_time utc.to_time end def to_datetime utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) end # So that +self+ <tt>acts_like?(:time)</tt>. def acts_like_time? true end # Say we're a Time to thwart type checking. def is_a?(klass) klass == ::Time || super end alias_method :kind_of?, :is_a? def freeze period; utc; time # preload instance variables before freezing super end def marshal_dump [utc, time_zone.name, time] end def marshal_load(variables) initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc) end # respond_to_missing? is not called in some cases, such as when type conversion is # performed with Kernel#String def respond_to?(sym, include_priv = false) # ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow return false if sym.to_sym == :to_str super end # Ensure proxy class responds to all methods that underlying time instance # responds to. def respond_to_missing?(sym, include_priv) # consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime return false if sym.to_sym == :acts_like_date? time.respond_to?(sym, include_priv) end # Send the missing method to +time+ instance, and wrap result in a new # TimeWithZone with the existing +time_zone+. def method_missing(sym, *args, &block) wrap_with_time_zone time.__send__(sym, *args, &block) rescue NoMethodError => e raise e, e.message.sub(time.inspect, self.inspect), e.backtrace end private def get_period_and_ensure_valid_local_time(period) # we don't want a Time.local instance enforcing its own DST rules as well, # so transfer time values to a utc constructor if necessary @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc? begin period || @time_zone.period_for_local(@time) rescue ::TZInfo::PeriodNotFound # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again @time += 1.hour retry end end def transfer_time_values_to_utc_constructor(time) ::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1000)) end def duration_of_variable_length?(obj) ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) } end def wrap_with_time_zone(time) if time.acts_like?(:time) periods = time_zone.periods_for_local(time) self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil) elsif time.is_a?(Range) wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end) else time end end end end
# Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. module TrisanoAuth module Models module User reloadable! hook! 'User' module ClassMethods def set_default_admin_uid_with_auth(uid, options={}) auth_options = { :password => 'changeme', :password_confirmation => 'changeme', } options = options.merge(auth_options) set_default_admin_uid_without_auth(uid, options) end def load_default_users_with_auth(users) new_users = [] users.each do |u| auth_options = { "password" => 'changeme', "password_confirmation" => 'changeme', } new_users << u.merge(auth_options) end load_default_users_without_auth(new_users) end end def self.included(base) #TODO debt unless config_option(:auth_src_env) || config_option(:auth_src_header) base.acts_as_authentic do |c| c.login_field = 'user_name' c.logged_in_timeout = 10.minutes c.perishable_token_valid_for 1.day end base.class_eval do extend ClassMethods class << self alias_method_chain :set_default_admin_uid, :auth alias_method_chain :load_default_users, :auth end end end end end end end An admin can't create a user without providing a password:http://www.pivotaltracker.com/story/show/4394235 # Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. module TrisanoAuth module Models module User reloadable! hook! 'User' module ClassMethods def set_default_admin_uid_with_auth(uid, options={}) auth_options = { :password => 'changeme', :password_confirmation => 'changeme', } options = options.merge(auth_options) set_default_admin_uid_without_auth(uid, options) end def load_default_users_with_auth(users) new_users = [] users.each do |u| auth_options = { "password" => 'changeme', "password_confirmation" => 'changeme', } new_users << u.merge(auth_options) end load_default_users_without_auth(new_users) end def new(params = nil) user = super(params) random_string = ActiveSupport::SecureRandom.hex(16) user.password = random_string user.password_confirmation = random_string return user end end def self.included(base) #TODO debt unless config_option(:auth_src_env) || config_option(:auth_src_header) base.acts_as_authentic do |c| c.login_field = 'user_name' c.logged_in_timeout = 10.minutes c.perishable_token_valid_for 1.day end base.class_eval do extend ClassMethods class << self alias_method_chain :set_default_admin_uid, :auth alias_method_chain :load_default_users, :auth end end end end end end end
# encoding: utf-8 require_relative '../../models/map/presenter' require_relative '../../models/visualization/locator' class Admin::VisualizationsController < ApplicationController ssl_allowed :embed_map, :public_map, :show_protected_embed_map, :public_table ssl_required :index, :show, :protected_embed_map, :protected_public_map, :show_protected_public_map before_filter :login_required, only: [:index] skip_before_filter :browser_is_html5_compliant?, only: [:public_map, :embed_map, :track_embed, :show_protected_embed_map, :show_protected_public_map] skip_before_filter :verify_authenticity_token, only: [:show_protected_public_map, :show_protected_embed_map] def index @tables_count = current_user.tables.count @first_time = !current_user.dashboard_viewed? @just_logged_in = !!flash['logged'] current_user.view_dashboard update_user_last_activity end #index def show id = params.fetch(:id) return(redirect_to public_url_for(id)) unless current_user.present? @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization respond_to { |format| format.html } update_user_last_activity end #show def public_table id = params.fetch(:id) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) if @visualization.nil? || @visualization.private? return(redirect_to public_map_url_for(id)) if @visualization.derived? @vizjson = @visualization.to_vizjson @avatar_url = @visualization.user.gravatar(64) @disqus_shortname = @visualization.user.disqus_shortname.presence || 'cartodb' @public_tables_count = @visualization.user.table_count(::Table::PRIVACY_PUBLIC) @dependent_visualizations = @table.dependent_visualizations @nonpublic_vis_count = @table.dependent_visualizations.select{ |vis| vis.privacy != CartoDB::Visualization::Member::PRIVACY_PUBLIC }.count respond_to do |format| format.html { render 'public_table', layout: 'application_table_public' } end end #public_table def public_map id = params.fetch(:id) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization return(embed_forbidden) if @visualization.private? return(public_map_protected) if @visualization.password_protected? response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" @avatar_url = @visualization.user.gravatar(64) @disqus_shortname = @visualization.user.disqus_shortname.presence || 'cartodb' @visualization_count = @visualization.user.public_visualization_count @related_tables = @visualization.related_tables @public_tables_count = @visualization.user.table_count(::Table::PRIVACY_PUBLIC) @nonpublic_tables_count = @related_tables.select{|p| p.privacy != ::Table::PRIVACY_PUBLIC }.count respond_to do |format| format.html { render layout: false } format.js { render 'public_map', content_type: 'application/javascript' } end rescue embed_forbidden end #public_map def show_protected_public_map id = params.fetch(:id) submitted_password = params.fetch(:password) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization and @visualization.password_protected? and @visualization.has_password? if not @visualization.is_password_valid?(submitted_password) flash[:placeholder] = '*' * submitted_password.size() flash[:error] = "Invalid password" return(embed_protected) end response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" @protected_map_token = @visualization.get_auth_token() @avatar_url = @visualization.user.gravatar(64) @disqus_shortname = @visualization.user.disqus_shortname.presence || 'cartodb' @visualization_count = @visualization.user.public_visualization_count @related_tables = @visualization.related_tables @public_tables_count = @visualization.user.table_count(::Table::PRIVACY_PUBLIC) @nonpublic_tables_count = @related_tables.select{|p| p.privacy != ::Table::PRIVACY_PUBLIC }.count respond_to do |format| format.html { render 'public_map', layout: false } end rescue public_map_protected end #show_protected_public_map def show_protected_embed_map id = params.fetch(:id) submitted_password = params.fetch(:password) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization and @visualization.password_protected? and @visualization.has_password? if not @visualization.is_password_valid?(submitted_password) flash[:placeholder] = '*' * submitted_password.size() flash[:error] = "Invalid password" return(embed_protected) end response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" @protected_map_token = @visualization.get_auth_token() respond_to do |format| format.html { render 'embed_map', layout: false } end rescue embed_protected end #show_protected_embed_map def embed_map id = params.fetch(:id) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization return(embed_forbidden) if @visualization.private? return(embed_protected) if @visualization.password_protected? response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" respond_to do |format| format.html { render layout: false } format.js { render 'embed_map', content_type: 'application/javascript' } end rescue embed_forbidden end #embed_map # Renders input password view def embed_protected render 'embed_map_password', :layout => false end #embed_protected def public_map_protected render 'public_map_password', :layout => false end #public_map_protected def embed_forbidden render 'embed_map_error', layout: false, status: :forbidden end #embed_forbidden def track_embed response.headers['X-Cache-Channel'] = "embeds_google_analytics" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" render 'track', layout: false end #track_embed private def public_url_for(id) "/#{resource_base}/#{id}/public" end #public_url_for def public_map_url_for(id) "/#{resource_base}/#{id}/public_map" end #public_url_for def embed_map_url_for(id) "/#{resource_base}/#{id}/embed_map" end #public_url_for def resource_base return 'viz' if request.path_info =~ %r{/viz/} return 'tables' if request.path_info =~ %r{/tables/} end #resource_base def download_formats table, format format.sql { send_data table.to_sql, data_for(table, 'zip', 'zip') } format.kml { send_data table.to_kml, data_for(table, 'zip', 'kmz') } format.csv { send_data table.to_csv, data_for(table, 'zip', 'zip') } format.shp { send_data table.to_shp, data_for(table, 'octet-stream', 'zip') } end def data_for(table, type, extension) { type: "application/#{type}; charset=binary; header=present", disposition: "attachment; filename=#{table.name}.#{extension}" } end def update_user_last_activity return false unless current_user.present? current_user.set_last_active_time current_user.set_last_ip_address request.remote_ip end def pretty_404 render(file: "public/404", layout: false, status: 404) end #pretty_404 def locator CartoDB::Visualization::Locator.new end #locator end # VisualizationsController Gets the right count of vis # encoding: utf-8 require_relative '../../models/map/presenter' require_relative '../../models/visualization/locator' class Admin::VisualizationsController < ApplicationController ssl_allowed :embed_map, :public_map, :show_protected_embed_map, :public_table ssl_required :index, :show, :protected_embed_map, :protected_public_map, :show_protected_public_map before_filter :login_required, only: [:index] skip_before_filter :browser_is_html5_compliant?, only: [:public_map, :embed_map, :track_embed, :show_protected_embed_map, :show_protected_public_map] skip_before_filter :verify_authenticity_token, only: [:show_protected_public_map, :show_protected_embed_map] def index @tables_count = current_user.tables.count @first_time = !current_user.dashboard_viewed? @just_logged_in = !!flash['logged'] current_user.view_dashboard update_user_last_activity end #index def show id = params.fetch(:id) return(redirect_to public_url_for(id)) unless current_user.present? @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization respond_to { |format| format.html } update_user_last_activity end #show def public_table id = params.fetch(:id) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) if @visualization.nil? || @visualization.private? return(redirect_to public_map_url_for(id)) if @visualization.derived? @vizjson = @visualization.to_vizjson @avatar_url = @visualization.user.gravatar(64) @disqus_shortname = @visualization.user.disqus_shortname.presence || 'cartodb' @public_tables_count = @visualization.user.table_count(::Table::PRIVACY_PUBLIC) @non_dependent_visualizations = @table.non_dependent_visualizations.select{ |vis| vis.privacy == CartoDB::Visualization::Member::PRIVACY_PUBLIC } @dependent_visualizations = @table.dependent_visualizations.select{ |vis| vis.privacy == CartoDB::Visualization::Member::PRIVACY_PUBLIC } @total_visualizations = @non_dependent_visualizations + @dependent_visualizations @total_nonpublic_total_vis_count = @table.non_dependent_visualizations.select{ |vis| vis.privacy != CartoDB::Visualization::Member::PRIVACY_PUBLIC }.count + @table.dependent_visualizations.select{ |vis| vis.privacy != CartoDB::Visualization::Member::PRIVACY_PUBLIC }.count respond_to do |format| format.html { render 'public_table', layout: 'application_table_public' } end end #public_table def public_map id = params.fetch(:id) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization return(embed_forbidden) if @visualization.private? return(public_map_protected) if @visualization.password_protected? response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" @avatar_url = @visualization.user.gravatar(64) @disqus_shortname = @visualization.user.disqus_shortname.presence || 'cartodb' @visualization_count = @visualization.user.public_visualization_count @related_tables = @visualization.related_tables @public_tables_count = @visualization.user.table_count(::Table::PRIVACY_PUBLIC) @nonpublic_tables_count = @related_tables.select{|p| p.privacy != ::Table::PRIVACY_PUBLIC }.count respond_to do |format| format.html { render layout: false } format.js { render 'public_map', content_type: 'application/javascript' } end rescue embed_forbidden end #public_map def show_protected_public_map id = params.fetch(:id) submitted_password = params.fetch(:password) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization and @visualization.password_protected? and @visualization.has_password? if not @visualization.is_password_valid?(submitted_password) flash[:placeholder] = '*' * submitted_password.size() flash[:error] = "Invalid password" return(embed_protected) end response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" @protected_map_token = @visualization.get_auth_token() @avatar_url = @visualization.user.gravatar(64) @disqus_shortname = @visualization.user.disqus_shortname.presence || 'cartodb' @visualization_count = @visualization.user.public_visualization_count @related_tables = @visualization.related_tables @public_tables_count = @visualization.user.table_count(::Table::PRIVACY_PUBLIC) @nonpublic_tables_count = @related_tables.select{|p| p.privacy != ::Table::PRIVACY_PUBLIC }.count respond_to do |format| format.html { render 'public_map', layout: false } end rescue public_map_protected end #show_protected_public_map def show_protected_embed_map id = params.fetch(:id) submitted_password = params.fetch(:password) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization and @visualization.password_protected? and @visualization.has_password? if not @visualization.is_password_valid?(submitted_password) flash[:placeholder] = '*' * submitted_password.size() flash[:error] = "Invalid password" return(embed_protected) end response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" @protected_map_token = @visualization.get_auth_token() respond_to do |format| format.html { render 'embed_map', layout: false } end rescue embed_protected end #show_protected_embed_map def embed_map id = params.fetch(:id) @visualization, @table = locator.get(id, CartoDB.extract_subdomain(request)) return(pretty_404) unless @visualization return(embed_forbidden) if @visualization.private? return(embed_protected) if @visualization.password_protected? response.headers['X-Cache-Channel'] = "#{@visualization.varnish_key}:vizjson" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" respond_to do |format| format.html { render layout: false } format.js { render 'embed_map', content_type: 'application/javascript' } end rescue embed_forbidden end #embed_map # Renders input password view def embed_protected render 'embed_map_password', :layout => false end #embed_protected def public_map_protected render 'public_map_password', :layout => false end #public_map_protected def embed_forbidden render 'embed_map_error', layout: false, status: :forbidden end #embed_forbidden def track_embed response.headers['X-Cache-Channel'] = "embeds_google_analytics" response.headers['Cache-Control'] = "no-cache,max-age=86400,must-revalidate, public" render 'track', layout: false end #track_embed private def public_url_for(id) "/#{resource_base}/#{id}/public" end #public_url_for def public_map_url_for(id) "/#{resource_base}/#{id}/public_map" end #public_url_for def embed_map_url_for(id) "/#{resource_base}/#{id}/embed_map" end #public_url_for def resource_base return 'viz' if request.path_info =~ %r{/viz/} return 'tables' if request.path_info =~ %r{/tables/} end #resource_base def download_formats table, format format.sql { send_data table.to_sql, data_for(table, 'zip', 'zip') } format.kml { send_data table.to_kml, data_for(table, 'zip', 'kmz') } format.csv { send_data table.to_csv, data_for(table, 'zip', 'zip') } format.shp { send_data table.to_shp, data_for(table, 'octet-stream', 'zip') } end def data_for(table, type, extension) { type: "application/#{type}; charset=binary; header=present", disposition: "attachment; filename=#{table.name}.#{extension}" } end def update_user_last_activity return false unless current_user.present? current_user.set_last_active_time current_user.set_last_ip_address request.remote_ip end def pretty_404 render(file: "public/404", layout: false, status: 404) end #pretty_404 def locator CartoDB::Visualization::Locator.new end #locator end # VisualizationsController
require 'uri' class API::V1::ConversationsController < API::V1::BaseApiController def create Conversation.transaction do params = new_conversation_params if User.exists?(id: params[:started_by]) conversation = Conversation.new(started_by: params[:started_by]) if conversation.save ConversationUser.create(user: User.find(params[:started_by]), conversation: conversation) message = Message.new(sender_id: params[:started_by], text: params[:message]) ConversationMessage.create(conversation: conversation, message: message) users = User.where(id: params[:recipient_ids]) users.each { |user| ConversationUser.create(user: user, conversation: conversation) } render json: conversation, serializer: ConversationSerializer, status: 201 end else render_error_as_json(404, 'Not Found', "User with id '#{params[:started_by]}' does not exist") end end end def post_message conversation_id = extract_conversation_id_from_path if Conversation.exists?(id: conversation_id) params = new_conversation_message_params if ConversationUser.exists?(conversation_id: conversation_id, user_id: params[:sender_id]) message = Message.create(sender_id: params[:sender_id], text: params[:message]) ConversationMessage.create(conversation: Conversation.find(conversation_id), message: message) render json: message, serializer: MessageSerializer, status: 201 else render_error_as_json(404, 'Not Found', "User with id '#{params[:sender_id]}' is not part of conversation id '#{conversation_id}'") end else render_error_as_json(404, 'Not Found', "Conversation with id '#{conversation_id}' does not exist") end end def add_user conversation_id = extract_conversation_id_from_path if Conversation.exists?(id: conversation_id) params = new_conversation_user_params if ConversationUser.exists?(conversation_id: conversation_id, user_id: params[:user_id]) render_error_as_json(409, 'Conflict', "User with id '#{params[:user_id]}' is already part of conversation id '#{conversation_id}'") else if User.exists?(id: params[:user_id]) user = User.find(params[:user_id]) ConversationUser.create(user: user, conversation: Conversation.find(conversation_id)) render json: user, serializer: UserWithConversationsSerializer, status: 201 else render_error_as_json(404, 'Not Found', "User with id '#{params[:user_id]}' does not exist") end end else render_error_as_json(404, 'Not Found', "Conversation with id '#{conversation_id}' does not exist") end end def index render json: Conversation.all, each_serializer: ConversationSerializer end def show render json: Conversation.find(params[:conversation_id]), serializer: ConversationSerializer end def show_messages render json: Conversation.find(params[:conversation_id]), serializer: ConversationWithMessagesSerializer end def show_users render json: Conversation.find(params[:conversation_id]), serializer: ConversationWithUsersSerializer end private def new_conversation_params params.require(:conversation).require(:started_by) params.require(:conversation).require(:recipient_ids) params.require(:conversation).require(:message) params.require(:conversation).permit(:started_by, :message, :recipient_ids => []) end def new_conversation_message_params params.require(:conversation).require(:sender_id) params.require(:conversation).permit(:sender_id, :message) end def new_conversation_user_params params.require(:conversation).require(:user_id) params.require(:conversation).permit(:user_id) end def extract_conversation_id_from_path path_chunks = URI(request.fullpath).path.split('/') last_path_chunks = path_chunks.last(2) last_path_chunks.first end end Simplified few complex code areas require 'uri' class API::V1::ConversationsController < API::V1::BaseApiController def create Conversation.transaction do params = new_conversation_params if User.exists?(id: params[:started_by]) conversation = Conversation.new(started_by: params[:started_by]) if conversation.save create_conversation_users(conversation, params[:recipient_ids] << params[:started_by]) create_conversation_message(conversation, params[:started_by], params[:message]) render json: conversation, serializer: ConversationSerializer, status: 201 end else render_error_as_json(404, 'Not Found', "User with id '#{params[:started_by]}' does not exist") end end end def post_message conversation_id = extract_conversation_id_from_path if Conversation.exists?(id: conversation_id) params = new_conversation_message_params if ConversationUser.exists?(conversation_id: conversation_id, user_id: params[:sender_id]) render json: create_conversation_message(conversation_id, params[:sender_id], params[:message]), serializer: MessageSerializer, status: 201 else render_error_as_json(404, 'Not Found', "User with id '#{params[:sender_id]}' is not part of conversation id '#{conversation_id}'") end else render_error_as_json(404, 'Not Found', "Conversation with id '#{conversation_id}' does not exist") end end def add_user conversation_id = extract_conversation_id_from_path if Conversation.exists?(id: conversation_id) params = new_conversation_user_params if ConversationUser.exists?(conversation_id: conversation_id, user_id: params[:user_id]) render_error_as_json(409, 'Conflict', "User with id '#{params[:user_id]}' is already part of conversation id '#{conversation_id}'") else if User.exists?(id: params[:user_id]) user = User.find(params[:user_id]) ConversationUser.create(user: user, conversation: Conversation.find(conversation_id)) render json: user, serializer: UserWithConversationsSerializer, status: 201 else render_error_as_json(404, 'Not Found', "User with id '#{params[:user_id]}' does not exist") end end else render_error_as_json(404, 'Not Found', "Conversation with id '#{conversation_id}' does not exist") end end def index render json: Conversation.all, each_serializer: ConversationSerializer end def show render json: Conversation.find(params[:conversation_id]), serializer: ConversationSerializer end def show_messages render json: Conversation.find(params[:conversation_id]), serializer: ConversationWithMessagesSerializer end def show_users render json: Conversation.find(params[:conversation_id]), serializer: ConversationWithUsersSerializer end private def new_conversation_params params.require(:conversation).require(:started_by) params.require(:conversation).require(:recipient_ids) params.require(:conversation).require(:message) params.require(:conversation).permit(:started_by, :message, :recipient_ids => []) end def new_conversation_message_params params.require(:conversation).require(:sender_id) params.require(:conversation).permit(:sender_id, :message) end def new_conversation_user_params params.require(:conversation).require(:user_id) params.require(:conversation).permit(:user_id) end def extract_conversation_id_from_path path_chunks = URI(request.fullpath).path.split('/') last_path_chunks = path_chunks.last(2) last_path_chunks.first end def create_conversation_users(conversation, user_ids) users = User.where(id: user_ids) users.each { |user| ConversationUser.create(user: user, conversation: conversation) } end def create_conversation_message(conversation, sender_id, text) message = Message.new(sender_id: sender_id, text: text) if conversation.instance_of? Conversation ConversationMessage.create(conversation: conversation, message: message) elsif conversation.instance_of? String ConversationMessage.create(conversation: Conversation.find(conversation), message: message) end message end end
require_dependency "bamboo_user/application_controller" module BambooUser class SessionsController < ApplicationController skip_before_filter :fetch_logged_user, only: [:login, :reset_password, :validate_password_reset, :make_password] before_filter :fetch_model_reflection def login if request.post? if (user = @model.find_by(email: params[:user][:email]).try(:authenticate, params[:user][:password])) session[:user] = user.id cookies.permanent[:auth_token_p] = user.auth_token if params[:remember_me] redirect_to((BambooUser.always_redirect_to_login_path ? eval(BambooUser.after_login_path) : (session[:previous_url] || eval(BambooUser.after_login_path))), notice: "Invalid credentials in use.") and return end end render layout: BambooUser.login_screen_layout end def reset_password if request.post? class_sym = @model.name.underscore.to_sym @user = @model.find_by(email: params[@model.name.underscore.to_sym][:email]) if (@user) @user.request_reset_password! redirect_to(login_path, notice: 'An email with password reset link has been sent to registered email address. Please check') and return else flash[:notice] = "No registered user found with email '#{params[class_sym][:email]}'." end end @user ||= @model.new render(layout: BambooUser.signup_screen_layout) if request.get? end def make_password do_password_reset('new_signup') render(layout: BambooUser.signup_screen_layout) if request.get? end def validate_password_reset do_password_reset(params[:for]||'password_recovery') render(layout: BambooUser.signup_screen_layout) if request.get? end def do_password_reset(reset_for = 'password_recovery') _password_reset_token, @_email = Base64.urlsafe_decode64(params[:encoded_params]).try(:split, '||') class_sym = @model.name.underscore.to_sym @user = @model.find_by(email: @_email) if request.post? if (@user and @user.password_reset_token == _password_reset_token and ((Time.now - @user.password_reset_sent_at) <= 86400.0)) #reset-token shouldn't be more than 1 day(i.e 86400 seconds) old if (not params[class_sym][:password].blank?) and @user.perform_reset_password!(user_params(class_sym), reset_for) session[:previous_url] = nil #Otherwise it may re-take back to reset_password page wrongly, as its path can't be blacklisted as 'hard-coded' way in engine.rb if reset_for == 'password_recovery' redirect_to(login_path, notice: 'New password created successfully. Please login with updated credentials here.') and return elsif reset_for == 'new_signup' session[:user] = @user.id #cookies.permanent[:auth_token_p] = user.auth_token if params[:remember_me] #BambooUser.after_registration_success_callback({user: @user}) #This thing is taken care from @user.perform_reset_password! redirect_to((session[:previous_url] || eval(BambooUser.after_signup_path)), notice: 'Welcome') and return end else logger.debug(@user.errors.inspect) flash[:notice] = 'Failed to update. Please recheck the password' end else redirect_to(login_path, notice: 'Invalid password reset token in use or it is too old to be used.') and return end end end def logout session.clear cookies.delete(:auth_token_p) redirect_to eval(BambooUser.after_logout_path) end private def user_params(required_class_type = :user) params.require(required_class_type).permit(:email, :password, :password_confirmation) end end end minor adjustments rollback require_dependency "bamboo_user/application_controller" module BambooUser class SessionsController < ApplicationController skip_before_filter :fetch_logged_user, only: [:login, :reset_password, :validate_password_reset, :make_password] before_filter :fetch_model_reflection def login if request.post? if (user = @model.find_by(email: params[:user][:email]).try(:authenticate, params[:user][:password])) session[:user] = user.id cookies.permanent[:auth_token_p] = user.auth_token if params[:remember_me] redirect_to((BambooUser.always_redirect_to_login_path ? eval(BambooUser.after_login_path) : (session[:previous_url] || eval(BambooUser.after_login_path)))) and return end end render layout: BambooUser.login_screen_layout end def reset_password if request.post? class_sym = @model.name.underscore.to_sym @user = @model.find_by(email: params[@model.name.underscore.to_sym][:email]) if (@user) @user.request_reset_password! redirect_to(login_path, notice: 'An email with password reset link has been sent to registered email address. Please check') and return else flash[:notice] = "No registered user found with email '#{params[class_sym][:email]}'." end end @user ||= @model.new render(layout: BambooUser.signup_screen_layout) if request.get? end def make_password do_password_reset('new_signup') render(layout: BambooUser.signup_screen_layout) if request.get? end def validate_password_reset do_password_reset(params[:for]||'password_recovery') render(layout: BambooUser.signup_screen_layout) if request.get? end def do_password_reset(reset_for = 'password_recovery') _password_reset_token, @_email = Base64.urlsafe_decode64(params[:encoded_params]).try(:split, '||') class_sym = @model.name.underscore.to_sym @user = @model.find_by(email: @_email) if request.post? if (@user and @user.password_reset_token == _password_reset_token and ((Time.now - @user.password_reset_sent_at) <= 86400.0)) #reset-token shouldn't be more than 1 day(i.e 86400 seconds) old if (not params[class_sym][:password].blank?) and @user.perform_reset_password!(user_params(class_sym), reset_for) session[:previous_url] = nil #Otherwise it may re-take back to reset_password page wrongly, as its path can't be blacklisted as 'hard-coded' way in engine.rb if reset_for == 'password_recovery' redirect_to(login_path, notice: 'New password created successfully. Please login with updated credentials here.') and return elsif reset_for == 'new_signup' session[:user] = @user.id #cookies.permanent[:auth_token_p] = user.auth_token if params[:remember_me] #BambooUser.after_registration_success_callback({user: @user}) #This thing is taken care from @user.perform_reset_password! redirect_to((session[:previous_url] || eval(BambooUser.after_signup_path)), notice: 'Welcome') and return end else logger.debug(@user.errors.inspect) flash[:notice] = 'Failed to update. Please recheck the password' end else redirect_to(login_path, notice: 'Invalid password reset token in use or it is too old to be used.') and return end end end def logout session.clear cookies.delete(:auth_token_p) redirect_to eval(BambooUser.after_logout_path) end private def user_params(required_class_type = :user) params.require(required_class_type).permit(:email, :password, :password_confirmation) end end end
# encoding: utf-8 require 'common/format' require 'wrappers/timing' require 'meeting_event_reservation_matrix_creator' require 'meeting_relay_reservation_matrix_creator' require 'team_manager_validator' =begin = MeetingReservationsController - version: 6.058 - author: Steve A. =end class MeetingReservationsController < ApplicationController # Require authorization before invoking any of this controller's actions: before_action :authenticate_user! # Parse parameters: before_action :verify_meeting_and_association # Edits the matrix of reservations for the selected meeting, for the whole team # of the currently logged-in user. # # If the user is a team manager, the whole matrix of rows is editable. # # If no reservation rows are found, a new (empty but serialized on DB) matrix # of events reservations is created, having a single MeetingReservationRow for # each possibile event of the chosen meeting, for each and every one if the swimmers # currently registered to the current user's team affiliation. # # This is a POST-only action due to the implied row insertions. # No row deletions are currently permitted. This action recreates the whole matrix # *only* if no rows are found. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def edit_events # The creator will set-up a matrix of rows that can be edited and then persisted # with the #update action creator = MeetingEventReservationMatrixCreator.new( meeting: @meeting, team_affiliation: @team_affiliation, current_user: current_user ) # Launch the creator and send the diff file, if any: perform_matrix_creation( creator, current_user, 'event' ) # Setup is done. Now we need to collect the lists of reservations for each athlete: prepare_meeting_reservations( @meeting, @team_affiliation ) # Collect the created list of badge reservations prepare_events_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x event rows) of event reservations end #-- ------------------------------------------------------------------------- #++ # Edits the matrix of _relay_ reservations for the selected meeting, for the # whole team of the currently logged-in user. # # See #edit_events for detailed info. # def edit_relays # The creator will set-up a matrix of rows that can be edited and then persisted # with the #update action creator = MeetingRelayReservationMatrixCreator.new( meeting: @meeting, team_affiliation: @team_affiliation, current_user: current_user ) # Launch the creator and send the diff file, if any: perform_matrix_creation( creator, current_user, 'relay' ) # Setup is done. Now we need to collect the lists of reservations for each athlete: prepare_meeting_reservations( @meeting, @team_affiliation ) # Collect the created list of badge reservations prepare_relays_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x relays rows) of relay reservations end #-- ------------------------------------------------------------------------- #++ # POSTs the update for the matrix of reservations for the selected meeting, for the whole team # of the currently logged-in user. # # Posting updates for non-existing rows will fail silently. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def update_events # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#update_events -----" # logger.debug "> #{params.inspect}" # XXX Sample POST output: # <ActionController::Parameters {"utf8"=>"✓", # "authenticity_token"=>"<auth_string_token>", # "resNC_1"=>"false", "resCnf_1"=>"true", "chk_resCnf_1"=>"true", "evrChk_1"=>"false", "resNotes_1"=>"2 seats available", # "evrChk_2"=>"true", "chk_evrChk_2"=>"true", "evrChk_3"=>"false", "evrChk_4"=>"true", # "chk_evrChk_4"=>"true", "resNotes_1"=>"", "resNC_47"=>"true", "chk_resNC_47"=>"true", # "resCnf_47"=>"false", # # [...] # "commit"=>"Save", "id"=>"16216", "controller"=>"meeting_reservations", # "action"=>"update", "locale"=>"en"} permitted: false> perform_matrix_update( params, current_user ) # At the end of the update we expect to remain in edit mode: redirect_to( meeting_reservations_edit_events_url(id: @meeting.id) ) end #-- ------------------------------------------------------------------------- #++ # POSTs the update for the matrix of reservations for the selected meeting, for the whole team # of the currently logged-in user. # # Posting updates for non-existing rows will fail silently. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def update_relays # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#update_relays -----" # logger.debug "> #{params.inspect}" perform_matrix_update( params, current_user ) # At the end of the update we expect to remain in edit mode: redirect_to( meeting_reservations_edit_relays_url(id: @meeting.id) ) end #-- ------------------------------------------------------------------------- #++ # Shows the current matrix data for both _event_ and _relay_ reservations, # for the (currently) chseon meeting, team and logged-in user. # def show prepare_meeting_reservations( @meeting, @team_affiliation ) # Collect the created list of badge reservations if @meeting_reservations.count < 1 flash[:error] = I18n.t(:no_result_to_show) redirect_to( meetings_current_path() ) and return end prepare_events_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x event rows) of event reservations prepare_relays_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x relays rows) of relay reservations end #-- ------------------------------------------------------------------------- #++ # Prepares the PDF print-out for the event and relay reservations for the current # meeting. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def printout_event_sheet() # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#printout_event_sheet -----" # logger.debug "> #{params.inspect}" # Collect all events for this Meeting, respecting session and event order: @events = @meeting.meeting_events .joins(:meeting_session, :event_type) .includes(:meeting_session, :event_type) .order('meeting_sessions.session_order, event_order') .to_a # Collect all available event (both ind. and relays) reservations: @reservations_events = {} @reservations_relays = {} @events.each do |event| # *** RELAYS *** if event.event_type.is_a_relay # TODO WE NEED A DIFFERENT LAYOUT FOR THE RELAYS @reservations_relays[ event.id ] = MeetingRelayReservation.where( meeting_event_id: event.id, is_doing_this: true ).joins(:meeting_session, :meeting_event, :event_type, :swimmer) .includes(:meeting_session, :meeting_event, :event_type, :swimmer) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a # *** EVENTS *** else @reservations_events[ event.id ] = MeetingEventReservation.where( meeting_event_id: event.id, is_doing_this: true ).joins(:meeting_session, :meeting_event, :category_type, :gender_type, :event_type, :swimmer) .includes(:meeting_session, :meeting_event, :category_type, :gender_type, :event_type, :swimmer) .order('meeting_sessions.session_order, meeting_events.event_order, category_types.code, gender_types.code') .to_a end end # Collect all related swimmer reservations (to gather also notes): all_swimmer_ids = ( @reservations_events.values + @reservations_relays.values ) .flatten .map{ |res| res.swimmer_id } .uniq @meeting_reservations = MeetingReservation.where( meeting_id: @meeting.id, team_id: @team_affiliation.team_id, is_not_coming: false, swimmer_id: all_swimmer_ids ).joins(:swimmer).includes(:swimmer) # DEBUG # logger.debug "---------------" # logger.debug "@events:" # @events.each{ |ev| logger.debug ev.inspect } # logger.debug "---------------" # logger.debug "- available @meeting_reservations tot...: #{ @meeting_reservations.count }" # logger.debug "- available @reservations_events subarrays tot....: #{ @reservations_events.count }" # logger.debug "- available @reservations_relays subarrays tot....: #{ @reservations_relays.count }" # logger.debug "---------------" # logger.debug "@meeting_reservations:" # @meeting_reservations.each{ |r| logger.debug r.inspect } # logger.debug "---------------" # logger.debug "@reservations_events hash:" # @reservations_events.values.each_with_index do |re, idx| # logger.debug( "\r\nEvent #{idx+1}, tot.: #{re.count}" ) # logger.debug( re.inspect ) # end # logger.debug "---------------" # logger.debug "@reservations_relays hash:" # @reservations_relays.values.each_with_index do |re, idx| # logger.debug( "\r\nEvent #{idx+1}, tot.: #{re.count}" ) # logger.debug( re.inspect ) # end # logger.debug "---------------" if all_swimmer_ids.size < 1 flash[:error] = I18n.t(:no_detail_to_process) redirect_to( meetings_current_path() ) and return end # == OPTIONS setup + RENDERING phase == base_filename = "#{I18n.t('meeting_reservation.event_sheet_basefilename')}_#{@meeting.code}" filename = create_unique_filename( base_filename ) + '.pdf' options = { report_title: I18n.t('meeting_reservation.event_sheet_title'), meta_info_subject: 'passages collection model sheet printout', meta_info_keywords: "Goggles, #{base_filename}'", meeting: @meeting, team: @team_affiliation.team, events: @events, meeting_reservations: @meeting_reservations, reservations_events: @reservations_events, reservations_relays: @reservations_relays } send_data( # == Render layout & send data: PassagesCollectSheetLayout.render( options ), type: 'application/pdf', filename: filename ) end #-- ------------------------------------------------------------------------- #++ # GET + POST relay auto-configurator. # # GET: analyze and suggest the best relay(s) configuration depending upon the # current relay availability of each reserved swimmer. # # POST: accepts and updates the relay reservations, according to the suggested changes. # # See #edit_relays and #update_relays for more info. # def relayometer unless @is_valid_team_manager flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.invalid_team_manager_or_no_swimmer') redirect_to( meetings_current_path() ) and return end # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#relayometer -----" # logger.debug "> #{params.inspect}" # Collect all relay events for this Meeting, respecting session and event order: @events = @meeting.meeting_events .joins(:meeting_session, :event_type) .includes(:meeting_session, :event_type) .where('event_types.is_a_relay = 1') .order('meeting_sessions.session_order, event_order') .to_a # Collect the availability matrix (badges x relays rows) of relay reservations: @reservations_relays = {} @events.each do |event| @reservations_relays[ event.id ] = MeetingRelayReservation.where( meeting_event_id: event.id, is_doing_this: true ).joins(:meeting_session, :meeting_event, :event_type, :swimmer) .includes(:meeting_session, :meeting_event, :event_type, :swimmer) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a end # POST: Parse the chosen config changes from the POST parameters and apply them on the reservations: if request.post? # TODO / WIP # GET: Analyze current relay availability and propose some solutions: else # TODO / WIP end end #-- ------------------------------------------------------------------------- #++ private # Collects the list of @meeting_reservations for each Swimmer, given the specified # meeting and team_affiliation. # # === Params: # - meeting: a valid instance of Meeting # - team_affiliation: a valid instance of TeamAffiliation (capable of attending the Meeting) # # === Prepares: # - @meeting_reservations: ActiveRelation object (list of reservations for each Swimmer of the Team) # def prepare_meeting_reservations( meeting, team_affiliation ) @meeting_reservations = MeetingReservation.where( meeting_id: meeting.id, team_id: team_affiliation.team_id ).joins(:swimmer).includes(:swimmer).order('swimmers.complete_name') end # Collects the list of @reservations_events associated to the specified meeting # and team_affiliation. # # Assumes @meeting_reservations is already filled with a list of MeetingReservation rows. # # === Params: # - meeting: a valid instance of Meeting # - team_affiliation: a valid instance of TeamAffiliation (capable of attending the Meeting) # # === Prepares: # - @reservations_events: Hash with the structure { <MeetingReservation.id> => <MeetingEventReservation row> } # def prepare_events_reservations( meeting, team_affiliation ) # Get the list of rows of event reservations for each athlete: @reservations_events = {} @meeting_reservations.each do |reservation| @reservations_events[ reservation.id ] = MeetingEventReservation.where( meeting_id: meeting.id, swimmer_id: reservation.swimmer_id ).joins(:meeting_session, :meeting_event, :event_type) .includes(:meeting_session, :meeting_event, :event_type) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a # Assuming 'mer' is an item of the resulting array, this yields something # like: # mer.event_type.i18n_short for the event description # mer.meeting_session.scheduled_date for the scheduled date end end # Collects the list of @reservations_relays associated to the specified meeting # and team_affiliation. # # Assumes @meeting_reservations is already filled with a list of MeetingReservation rows. # # === Params: # - meeting: a valid instance of Meeting # - team_affiliation: a valid instance of TeamAffiliation (capable of attending the Meeting) # # === Prepares: # - @reservations_relays Hash with the structure { <MeetingReservation.id> => <MeetingRelayReservation row> } # def prepare_relays_reservations( meeting, team_affiliation ) # Get the list of rows of relay reservations for each athlete: @reservations_relays = {} @meeting_reservations.each do |reservation| @reservations_relays[ reservation.id ] = MeetingRelayReservation.where( meeting_id: meeting.id, swimmer_id: reservation.swimmer_id ).joins(:meeting_session, :meeting_event, :event_type) .includes(:meeting_session, :meeting_event, :event_type) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a # Assuming 'mrr' is an item of the resulting array, this yields something # like: # mrr.event_type.i18n_short for the event description # mrr.meeting_session.scheduled_date for the scheduled date end end #-- ------------------------------------------------------------------------- #++ # Calls the creator specified, then serializes the SQL diff file, whenever # any processed row or error exists. # def perform_matrix_creation( creator, current_user, entity_simple_description ) creator.call # Serialize creator.sql_diff_text_log in a dedicated log file: if creator.processed_rows > 0 || creator.total_errors > 0 # Create the SQL diff file, and send it, when operated remotely: output_dir = get_output_folder() file_name = get_timestamped_env_filename( "create_#{ entity_simple_description }_res_#{ @meeting.code }_#{ current_user.id }.diff.sql" ) full_sql_diff_path = File.join( output_dir, file_name ) serialize_and_deliver_diff_file( creator, "create #{ entity_simple_description } RESERVATIONS", full_sql_diff_path ) # TODO Alternatively, make an asynch job that sends a whole batch of edits via mail # Signal also locally if any error occurred during setup: if creator.total_errors > 0 flash[:error] = I18n.t('meeting_reservation.error_during_creation') # Everything ok? else # Only upon reservation sheet creation, signal to each possible interested # user that now he/she may be able to use the newly reservation sheet: interested_users = @meeting.tags_by_user_list .map{ |tag| User.find(tag.remove('u').to_i) } .select{ |user| user.id != current_user.id } interested_users.each do |user| NewsletterMailer.custom_mail( user, I18n.t("newsletter_mailer.new_reservations.subject"), I18n.t("newsletter_mailer.new_reservations.title"), I18n.t( "newsletter_mailer.new_reservations.contents", team_manager_name: current_user.get_full_name, meeting_name: @meeting.get_full_name, manage_url: meeting_reservations_edit_events_url(id: @meeting.id) ) ).deliver end end end end #-- ------------------------------------------------------------------------- #++ # Performs the update process given the parameters hash and the current user. # Works indipendently for both ind. events and relays (including badge reservations). # def perform_matrix_update( params, current_user ) # The updater will parse the parameter and update the corresponding rows, while # creating an SQL diff text to be serialized for database synchronization: updater = MeetingReservationMatrixUpdater.new( params, current_user ) updater.call # Serialize updater.sql_diff_text_log in a dedicated log file: if updater.processed_rows > 0 || updater.total_errors > 0 # Create the SQL diff file, and send it, when operated remotely: output_dir = get_output_folder() file_name = get_timestamped_env_filename( "update_event_res_#{ @meeting.code }_#{ current_user.id }.diff.sql" ) full_sql_diff_path = File.join( output_dir, file_name ) serialize_and_deliver_diff_file( updater, "update RESERVATIONS", full_sql_diff_path ) # TODO Alternatively, make an asynch job that sends a whole batch of edits via mail # Signal also locally if any error occurred during setup: if updater.total_errors > 0 flash[:error] = I18n.t('meeting_reservation.error_during_save') else flash[:info] = I18n.t('meeting_reservation.changes_saved') end end end #-- ------------------------------------------------------------------------- #++ # Creates the SQL diff file using an SqlConvertable-compatible instance (must respond # to #sql_diff_text_log) and sends the file via mail if the current environment # is in production mode. # def serialize_and_deliver_diff_file( sql_convertable, mail_title, full_diff_pathname ) File.open( full_diff_pathname, 'w' ) { |f| f.puts sql_convertable.sql_diff_text_log } base_filename = File.basename( full_diff_pathname ) logger.info( "\r\nLog file '#{ base_filename }' created" ) if Rails.env == 'production' # Send the DB diff file to the SysOp AgexMailer.action_notify_mail( current_user, mail_title, "User #{current_user} has edited remotely the reservations for his/hers team, meeting ID #{@meeting.id}.\r\nThe attached log file must be synchronized locally.", base_filename, full_diff_pathname ).deliver # Send an additional mail message to the related team manager users (except the current user): filtered_managers = @team_affiliation.team_managers.all.select{ |tm| tm.user_id != current_user.id } filtered_managers.each do |team_manager| NewsletterMailer.custom_mail( team_manager.user, I18n.t("newsletter_mailer.reservations.subject"), I18n.t("newsletter_mailer.reservations.title"), I18n.t( "newsletter_mailer.reservations.contents", user_name: current_user.get_full_name, meeting_name: @meeting.get_full_name, manage_url: meeting_reservations_edit_events_url(id: @meeting.id) ) ).deliver end end end #-- ------------------------------------------------------------------------- #++ # Verifies that a meeting id is provided as parameter and that the current user # is either associated to a swimmer or is the team_manager of a team. # Else, returns an invalid action request. # # Sets/assigns: # - @meeting, a valid Meeting instance # - @is_valid_team_manager, either +true+ or +false+ # - @swimmer, +nil+ only when no associated swimmer was found (allegedly, in this case @is_valid_team_manager should result true) # - @team_affiliation, a valid TeamAffiliation instance # - @team, a valid Team instance # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # def verify_meeting_and_association set_meeting_from_id unless ( @meeting ) flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.missing_meeting_id') redirect_to( meetings_current_path() ) and return end # To be a valid team manager (precisely, for editing & adding reservations), # a user must be: # - enabled to manage the season of the selected Meeting (...AND...) # - the meeting must still be 'reservation-manageable' @is_valid_team_manager = TeamManagerValidator.can_manage?( current_user, @meeting ) && TeamManagerValidator.is_reservation_manageable?( @meeting ) # (If the meeting is no more 'reservation-manageable', each view page widget # should be set as read-only, even if the page is still accessible because # of existing reservations.) # Detect if there's a swimmer associated: set_swimmer_from_current_user # Avoid creating useless new reservations for already closed meetings, # by redirecting elsewhere: if ( MeetingReservation.where( meeting_id: @meeting.id ).count == 0 ) && ( @meeting.meeting_individual_results.count > 0 || @meeting.are_results_acquired? ) flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.meeting_already_closed') redirect_to( meetings_current_path() ) and return end # Bail out unless the user is a valid team manager, or if a swimmer is checking # a meeting w/ reservations that do not belong to him/her: unless ( @is_valid_team_manager || ( @swimmer && TeamManagerValidator.any_reservations_for?(current_user, @meeting) ) ) flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.invalid_team_manager_or_no_swimmer') redirect_to( meetings_current_path() ) and return end # FIXME [Steve, 20161213] It could be possible to have a user that is defined as TeamManager # (for example, for ease of passages editing) for a couple of TeamAffiliations # both registered to the same season and thus eligible to manage the registrations # of different teams for the same meeting, while (for referential integrity) the # badge associated to the swimmer of the TeamManager allows him/her to take # part in the same meeting with only one affiliation. # # This is possibile because Team Managers are defined freely according # to user requests. # # THIS MUSt BE HANDLED BY THE QUERY BELOW AND ALL THE SWIMMERS FOR # ALL INVOLVED TEAMAFFILIATIONS SHOULD BE COLLECTED! if @is_valid_team_manager enabled_manager = current_user.team_managers.includes(:team_affiliation) .find{|tm| tm.team_affiliation.season_id == @meeting.season_id } @team_affiliation = enabled_manager.team_affiliation else # DEBUG # puts "\r\n--- @swimmer: #{ @swimmer.inspect }" # puts "--- @meeting: #{ @meeting.inspect }" enabled_badge = @swimmer.badges.includes(:team_affiliation) .find{|b| b.team_affiliation.season_id == @meeting.season_id } @team_affiliation = enabled_badge.team_affiliation end @team = @team_affiliation.team end #-- ------------------------------------------------------------------------- #++ end removed auto-mailing from relay reservations matrix creation # encoding: utf-8 require 'common/format' require 'wrappers/timing' require 'meeting_event_reservation_matrix_creator' require 'meeting_relay_reservation_matrix_creator' require 'team_manager_validator' =begin = MeetingReservationsController - version: 6.058 - author: Steve A. =end class MeetingReservationsController < ApplicationController # Require authorization before invoking any of this controller's actions: before_action :authenticate_user! # Parse parameters: before_action :verify_meeting_and_association # Edits the matrix of reservations for the selected meeting, for the whole team # of the currently logged-in user. # # If the user is a team manager, the whole matrix of rows is editable. # # If no reservation rows are found, a new (empty but serialized on DB) matrix # of events reservations is created, having a single MeetingReservationRow for # each possibile event of the chosen meeting, for each and every one if the swimmers # currently registered to the current user's team affiliation. # # This is a POST-only action due to the implied row insertions. # No row deletions are currently permitted. This action recreates the whole matrix # *only* if no rows are found. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def edit_events # The creator will set-up a matrix of rows that can be edited and then persisted # with the #update action creator = MeetingEventReservationMatrixCreator.new( meeting: @meeting, team_affiliation: @team_affiliation, current_user: current_user ) # Launch the creator and send the diff file, if any: perform_matrix_creation( creator, current_user, 'event' ) # Setup is done. Now we need to collect the lists of reservations for each athlete: prepare_meeting_reservations( @meeting, @team_affiliation ) # Collect the created list of badge reservations prepare_events_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x event rows) of event reservations end #-- ------------------------------------------------------------------------- #++ # Edits the matrix of _relay_ reservations for the selected meeting, for the # whole team of the currently logged-in user. # # See #edit_events for detailed info. # def edit_relays # The creator will set-up a matrix of rows that can be edited and then persisted # with the #update action creator = MeetingRelayReservationMatrixCreator.new( meeting: @meeting, team_affiliation: @team_affiliation, current_user: current_user ) # Launch the creator and send the diff file, if any: perform_matrix_creation( creator, current_user, 'relay' ) # Setup is done. Now we need to collect the lists of reservations for each athlete: prepare_meeting_reservations( @meeting, @team_affiliation ) # Collect the created list of badge reservations prepare_relays_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x relays rows) of relay reservations end #-- ------------------------------------------------------------------------- #++ # POSTs the update for the matrix of reservations for the selected meeting, for the whole team # of the currently logged-in user. # # Posting updates for non-existing rows will fail silently. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def update_events # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#update_events -----" # logger.debug "> #{params.inspect}" # XXX Sample POST output: # <ActionController::Parameters {"utf8"=>"✓", # "authenticity_token"=>"<auth_string_token>", # "resNC_1"=>"false", "resCnf_1"=>"true", "chk_resCnf_1"=>"true", "evrChk_1"=>"false", "resNotes_1"=>"2 seats available", # "evrChk_2"=>"true", "chk_evrChk_2"=>"true", "evrChk_3"=>"false", "evrChk_4"=>"true", # "chk_evrChk_4"=>"true", "resNotes_1"=>"", "resNC_47"=>"true", "chk_resNC_47"=>"true", # "resCnf_47"=>"false", # # [...] # "commit"=>"Save", "id"=>"16216", "controller"=>"meeting_reservations", # "action"=>"update", "locale"=>"en"} permitted: false> perform_matrix_update( params, current_user ) # At the end of the update we expect to remain in edit mode: redirect_to( meeting_reservations_edit_events_url(id: @meeting.id) ) end #-- ------------------------------------------------------------------------- #++ # POSTs the update for the matrix of reservations for the selected meeting, for the whole team # of the currently logged-in user. # # Posting updates for non-existing rows will fail silently. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def update_relays # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#update_relays -----" # logger.debug "> #{params.inspect}" perform_matrix_update( params, current_user ) # At the end of the update we expect to remain in edit mode: redirect_to( meeting_reservations_edit_relays_url(id: @meeting.id) ) end #-- ------------------------------------------------------------------------- #++ # Shows the current matrix data for both _event_ and _relay_ reservations, # for the (currently) chseon meeting, team and logged-in user. # def show prepare_meeting_reservations( @meeting, @team_affiliation ) # Collect the created list of badge reservations if @meeting_reservations.count < 1 flash[:error] = I18n.t(:no_result_to_show) redirect_to( meetings_current_path() ) and return end prepare_events_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x event rows) of event reservations prepare_relays_reservations( @meeting, @team_affiliation ) # collect the created matrix (badges x relays rows) of relay reservations end #-- ------------------------------------------------------------------------- #++ # Prepares the PDF print-out for the event and relay reservations for the current # meeting. # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # (when also a team-manager, the whole matrix of rows should be editable) # def printout_event_sheet() # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#printout_event_sheet -----" # logger.debug "> #{params.inspect}" # Collect all events for this Meeting, respecting session and event order: @events = @meeting.meeting_events .joins(:meeting_session, :event_type) .includes(:meeting_session, :event_type) .order('meeting_sessions.session_order, event_order') .to_a # Collect all available event (both ind. and relays) reservations: @reservations_events = {} @reservations_relays = {} @events.each do |event| # *** RELAYS *** if event.event_type.is_a_relay # TODO WE NEED A DIFFERENT LAYOUT FOR THE RELAYS @reservations_relays[ event.id ] = MeetingRelayReservation.where( meeting_event_id: event.id, is_doing_this: true ).joins(:meeting_session, :meeting_event, :event_type, :swimmer) .includes(:meeting_session, :meeting_event, :event_type, :swimmer) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a # *** EVENTS *** else @reservations_events[ event.id ] = MeetingEventReservation.where( meeting_event_id: event.id, is_doing_this: true ).joins(:meeting_session, :meeting_event, :category_type, :gender_type, :event_type, :swimmer) .includes(:meeting_session, :meeting_event, :category_type, :gender_type, :event_type, :swimmer) .order('meeting_sessions.session_order, meeting_events.event_order, category_types.code, gender_types.code') .to_a end end # Collect all related swimmer reservations (to gather also notes): all_swimmer_ids = ( @reservations_events.values + @reservations_relays.values ) .flatten .map{ |res| res.swimmer_id } .uniq @meeting_reservations = MeetingReservation.where( meeting_id: @meeting.id, team_id: @team_affiliation.team_id, is_not_coming: false, swimmer_id: all_swimmer_ids ).joins(:swimmer).includes(:swimmer) # DEBUG # logger.debug "---------------" # logger.debug "@events:" # @events.each{ |ev| logger.debug ev.inspect } # logger.debug "---------------" # logger.debug "- available @meeting_reservations tot...: #{ @meeting_reservations.count }" # logger.debug "- available @reservations_events subarrays tot....: #{ @reservations_events.count }" # logger.debug "- available @reservations_relays subarrays tot....: #{ @reservations_relays.count }" # logger.debug "---------------" # logger.debug "@meeting_reservations:" # @meeting_reservations.each{ |r| logger.debug r.inspect } # logger.debug "---------------" # logger.debug "@reservations_events hash:" # @reservations_events.values.each_with_index do |re, idx| # logger.debug( "\r\nEvent #{idx+1}, tot.: #{re.count}" ) # logger.debug( re.inspect ) # end # logger.debug "---------------" # logger.debug "@reservations_relays hash:" # @reservations_relays.values.each_with_index do |re, idx| # logger.debug( "\r\nEvent #{idx+1}, tot.: #{re.count}" ) # logger.debug( re.inspect ) # end # logger.debug "---------------" if all_swimmer_ids.size < 1 flash[:error] = I18n.t(:no_detail_to_process) redirect_to( meetings_current_path() ) and return end # == OPTIONS setup + RENDERING phase == base_filename = "#{I18n.t('meeting_reservation.event_sheet_basefilename')}_#{@meeting.code}" filename = create_unique_filename( base_filename ) + '.pdf' options = { report_title: I18n.t('meeting_reservation.event_sheet_title'), meta_info_subject: 'passages collection model sheet printout', meta_info_keywords: "Goggles, #{base_filename}'", meeting: @meeting, team: @team_affiliation.team, events: @events, meeting_reservations: @meeting_reservations, reservations_events: @reservations_events, reservations_relays: @reservations_relays } send_data( # == Render layout & send data: PassagesCollectSheetLayout.render( options ), type: 'application/pdf', filename: filename ) end #-- ------------------------------------------------------------------------- #++ # GET + POST relay auto-configurator. # # GET: analyze and suggest the best relay(s) configuration depending upon the # current relay availability of each reserved swimmer. # # POST: accepts and updates the relay reservations, according to the suggested changes. # # See #edit_relays and #update_relays for more info. # def relayometer unless @is_valid_team_manager flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.invalid_team_manager_or_no_swimmer') redirect_to( meetings_current_path() ) and return end # DEBUG # logger.debug "\r\n\r\n!! ------ #{self.class.name}#relayometer -----" # logger.debug "> #{params.inspect}" # Collect all relay events for this Meeting, respecting session and event order: @events = @meeting.meeting_events .joins(:meeting_session, :event_type) .includes(:meeting_session, :event_type) .where('event_types.is_a_relay = 1') .order('meeting_sessions.session_order, event_order') .to_a # Collect the availability matrix (badges x relays rows) of relay reservations: @reservations_relays = {} @events.each do |event| @reservations_relays[ event.id ] = MeetingRelayReservation.where( meeting_event_id: event.id, is_doing_this: true ).joins(:meeting_session, :meeting_event, :event_type, :swimmer) .includes(:meeting_session, :meeting_event, :event_type, :swimmer) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a end # POST: Parse the chosen config changes from the POST parameters and apply them on the reservations: if request.post? # TODO / WIP # GET: Analyze current relay availability and propose some solutions: else # TODO / WIP end end #-- ------------------------------------------------------------------------- #++ private # Collects the list of @meeting_reservations for each Swimmer, given the specified # meeting and team_affiliation. # # === Params: # - meeting: a valid instance of Meeting # - team_affiliation: a valid instance of TeamAffiliation (capable of attending the Meeting) # # === Prepares: # - @meeting_reservations: ActiveRelation object (list of reservations for each Swimmer of the Team) # def prepare_meeting_reservations( meeting, team_affiliation ) @meeting_reservations = MeetingReservation.where( meeting_id: meeting.id, team_id: team_affiliation.team_id ).joins(:swimmer).includes(:swimmer).order('swimmers.complete_name') end # Collects the list of @reservations_events associated to the specified meeting # and team_affiliation. # # Assumes @meeting_reservations is already filled with a list of MeetingReservation rows. # # === Params: # - meeting: a valid instance of Meeting # - team_affiliation: a valid instance of TeamAffiliation (capable of attending the Meeting) # # === Prepares: # - @reservations_events: Hash with the structure { <MeetingReservation.id> => <MeetingEventReservation row> } # def prepare_events_reservations( meeting, team_affiliation ) # Get the list of rows of event reservations for each athlete: @reservations_events = {} @meeting_reservations.each do |reservation| @reservations_events[ reservation.id ] = MeetingEventReservation.where( meeting_id: meeting.id, swimmer_id: reservation.swimmer_id ).joins(:meeting_session, :meeting_event, :event_type) .includes(:meeting_session, :meeting_event, :event_type) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a # Assuming 'mer' is an item of the resulting array, this yields something # like: # mer.event_type.i18n_short for the event description # mer.meeting_session.scheduled_date for the scheduled date end end # Collects the list of @reservations_relays associated to the specified meeting # and team_affiliation. # # Assumes @meeting_reservations is already filled with a list of MeetingReservation rows. # # === Params: # - meeting: a valid instance of Meeting # - team_affiliation: a valid instance of TeamAffiliation (capable of attending the Meeting) # # === Prepares: # - @reservations_relays Hash with the structure { <MeetingReservation.id> => <MeetingRelayReservation row> } # def prepare_relays_reservations( meeting, team_affiliation ) # Get the list of rows of relay reservations for each athlete: @reservations_relays = {} @meeting_reservations.each do |reservation| @reservations_relays[ reservation.id ] = MeetingRelayReservation.where( meeting_id: meeting.id, swimmer_id: reservation.swimmer_id ).joins(:meeting_session, :meeting_event, :event_type) .includes(:meeting_session, :meeting_event, :event_type) .order('meeting_sessions.session_order, meeting_events.event_order') .to_a # Assuming 'mrr' is an item of the resulting array, this yields something # like: # mrr.event_type.i18n_short for the event description # mrr.meeting_session.scheduled_date for the scheduled date end end #-- ------------------------------------------------------------------------- #++ # Calls the creator specified, then serializes the SQL diff file, whenever # any processed row or error exists. # def perform_matrix_creation( creator, current_user, entity_simple_description ) creator.call # Serialize creator.sql_diff_text_log in a dedicated log file: if creator.processed_rows > 0 || creator.total_errors > 0 # Create the SQL diff file, and send it, when operated remotely: output_dir = get_output_folder() file_name = get_timestamped_env_filename( "create_#{ entity_simple_description }_res_#{ @meeting.code }_#{ current_user.id }.diff.sql" ) full_sql_diff_path = File.join( output_dir, file_name ) serialize_and_deliver_diff_file( creator, "create #{ entity_simple_description } RESERVATIONS", full_sql_diff_path ) # TODO Alternatively, make an asynch job that sends a whole batch of edits via mail # Signal also locally if any error occurred during setup: if creator.total_errors > 0 flash[:error] = I18n.t('meeting_reservation.error_during_creation') # Everything ok? # Only upon main reservation sheet creation, signal to each possible interested # user that now he/she may be able to use the newly reservation sheet: elsif entity_simple_description != 'relay' interested_users = @meeting.tags_by_user_list .map{ |tag| User.find(tag.remove('u').to_i) } .select{ |user| user.id != current_user.id } interested_users.each do |user| NewsletterMailer.custom_mail( user, I18n.t("newsletter_mailer.new_reservations.subject"), I18n.t("newsletter_mailer.new_reservations.title"), I18n.t( "newsletter_mailer.new_reservations.contents", team_manager_name: current_user.get_full_name, meeting_name: @meeting.get_full_name, manage_url: meeting_reservations_edit_events_url(id: @meeting.id) ) ).deliver end end end end #-- ------------------------------------------------------------------------- #++ # Performs the update process given the parameters hash and the current user. # Works indipendently for both ind. events and relays (including badge reservations). # def perform_matrix_update( params, current_user ) # The updater will parse the parameter and update the corresponding rows, while # creating an SQL diff text to be serialized for database synchronization: updater = MeetingReservationMatrixUpdater.new( params, current_user ) updater.call # Serialize updater.sql_diff_text_log in a dedicated log file: if updater.processed_rows > 0 || updater.total_errors > 0 # Create the SQL diff file, and send it, when operated remotely: output_dir = get_output_folder() file_name = get_timestamped_env_filename( "update_event_res_#{ @meeting.code }_#{ current_user.id }.diff.sql" ) full_sql_diff_path = File.join( output_dir, file_name ) serialize_and_deliver_diff_file( updater, "update RESERVATIONS", full_sql_diff_path ) # TODO Alternatively, make an asynch job that sends a whole batch of edits via mail # Signal also locally if any error occurred during setup: if updater.total_errors > 0 flash[:error] = I18n.t('meeting_reservation.error_during_save') else flash[:info] = I18n.t('meeting_reservation.changes_saved') end end end #-- ------------------------------------------------------------------------- #++ # Creates the SQL diff file using an SqlConvertable-compatible instance (must respond # to #sql_diff_text_log) and sends the file via mail if the current environment # is in production mode. # def serialize_and_deliver_diff_file( sql_convertable, mail_title, full_diff_pathname ) File.open( full_diff_pathname, 'w' ) { |f| f.puts sql_convertable.sql_diff_text_log } base_filename = File.basename( full_diff_pathname ) logger.info( "\r\nLog file '#{ base_filename }' created" ) if Rails.env == 'production' # Send the DB diff file to the SysOp AgexMailer.action_notify_mail( current_user, mail_title, "User #{current_user} has edited remotely the reservations for his/hers team, meeting ID #{@meeting.id}.\r\nThe attached log file must be synchronized locally.", base_filename, full_diff_pathname ).deliver # Send an additional mail message to the related team manager users (except the current user): filtered_managers = @team_affiliation.team_managers.all.select{ |tm| tm.user_id != current_user.id } filtered_managers.each do |team_manager| NewsletterMailer.custom_mail( team_manager.user, I18n.t("newsletter_mailer.reservations.subject"), I18n.t("newsletter_mailer.reservations.title"), I18n.t( "newsletter_mailer.reservations.contents", user_name: current_user.get_full_name, meeting_name: @meeting.get_full_name, manage_url: meeting_reservations_edit_events_url(id: @meeting.id) ) ).deliver end end end #-- ------------------------------------------------------------------------- #++ # Verifies that a meeting id is provided as parameter and that the current user # is either associated to a swimmer or is the team_manager of a team. # Else, returns an invalid action request. # # Sets/assigns: # - @meeting, a valid Meeting instance # - @is_valid_team_manager, either +true+ or +false+ # - @swimmer, +nil+ only when no associated swimmer was found (allegedly, in this case @is_valid_team_manager should result true) # - @team_affiliation, a valid TeamAffiliation instance # - @team, a valid Team instance # # == Params: # id: the meeting id to be processed # # == Implied parameters: # current_user: user must be logged-in and either be a team-manager or have an # associated swimmer (must be a "goggler"). # def verify_meeting_and_association set_meeting_from_id unless ( @meeting ) flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.missing_meeting_id') redirect_to( meetings_current_path() ) and return end # To be a valid team manager (precisely, for editing & adding reservations), # a user must be: # - enabled to manage the season of the selected Meeting (...AND...) # - the meeting must still be 'reservation-manageable' @is_valid_team_manager = TeamManagerValidator.can_manage?( current_user, @meeting ) && TeamManagerValidator.is_reservation_manageable?( @meeting ) # (If the meeting is no more 'reservation-manageable', each view page widget # should be set as read-only, even if the page is still accessible because # of existing reservations.) # Detect if there's a swimmer associated: set_swimmer_from_current_user # Avoid creating useless new reservations for already closed meetings, # by redirecting elsewhere: if ( MeetingReservation.where( meeting_id: @meeting.id ).count == 0 ) && ( @meeting.meeting_individual_results.count > 0 || @meeting.are_results_acquired? ) flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.meeting_already_closed') redirect_to( meetings_current_path() ) and return end # Bail out unless the user is a valid team manager, or if a swimmer is checking # a meeting w/ reservations that do not belong to him/her: unless ( @is_valid_team_manager || ( @swimmer && TeamManagerValidator.any_reservations_for?(current_user, @meeting) ) ) flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.invalid_team_manager_or_no_swimmer') redirect_to( meetings_current_path() ) and return end # FIXME [Steve, 20161213] It could be possible to have a user that is defined as TeamManager # (for example, for ease of passages editing) for a couple of TeamAffiliations # both registered to the same season and thus eligible to manage the registrations # of different teams for the same meeting, while (for referential integrity) the # badge associated to the swimmer of the TeamManager allows him/her to take # part in the same meeting with only one affiliation. # # This is possibile because Team Managers are defined freely according # to user requests. # # THIS MUSt BE HANDLED BY THE QUERY BELOW AND ALL THE SWIMMERS FOR # ALL INVOLVED TEAMAFFILIATIONS SHOULD BE COLLECTED! if @is_valid_team_manager enabled_manager = current_user.team_managers.includes(:team_affiliation) .find{|tm| tm.team_affiliation.season_id == @meeting.season_id } @team_affiliation = enabled_manager.team_affiliation else # DEBUG # puts "\r\n--- @swimmer: #{ @swimmer.inspect }" # puts "--- @meeting: #{ @meeting.inspect }" enabled_badge = @swimmer.badges.includes(:team_affiliation) .find{|b| b.team_affiliation.season_id == @meeting.season_id } @team_affiliation = enabled_badge.team_affiliation end @team = @team_affiliation.team end #-- ------------------------------------------------------------------------- #++ end
module GobiertoPeople class PersonDecorator < BaseDecorator def initialize(person) @object = person end def contact_email person_contact_method_for("Email", "service_url") end def twitter_handle person_contact_method_for("Twitter", "service_handle") end def twitter_url person_contact_method_for("Twitter", "service_url") end def facebook_handle person_contact_method_for("Facebook", "service_handle") end def facebook_url person_contact_method_for("Facebook", "service_url") end def linkedin_handle person_contact_method_for("LinkedIn", "service_handle") end def linkedin_url person_contact_method_for("LinkedIn", "service_url") end def instagram_handle person_contact_method_for("Instagram", "service_handle") end def instagram_url person_contact_method_for("Instagram", "service_url") end def trips_url person_custom_link_for('Viajes') end def gifts_url person_custom_link_for('Obsequios') end def content_blocks_for_bio(site_id) object.content_blocks(site_id).where.not(internal_id: GobiertoCommon::DynamicContent::CONTACT_BLOCK_ID) end def has_bio_or_cv? bio.present? || bio_url.present? end def has_biographic_blocks? content_blocks_for_bio(site_id).any? { |block| block.records.any? } end def has_biographic_data? has_bio_or_cv? || has_biographic_blocks? end def has_posts? posts.active.any? end def has_statements? statements.active.any? end def meetings_with_interest_groups(start_date: nil, end_date: nil) QueryWithEvents.new(source: events.with_interest_group.published, start_date: start_date, end_date: end_date) end def interest_groups_count(start_date: nil, end_date: nil) meetings_with_interest_groups(start_date: start_date, end_date: end_date).select(:interest_group_id).distinct.count end private def person_contact_method_for(service_name, attribute_name) person_contact_methods.detect do |contact_method| contact_method["service_name"] == service_name end.try(:[], attribute_name) end def person_custom_link_for(service_name) content_block = object.content_blocks.find_by(internal_id: GobiertoCommon::DynamicContent::CUSTOM_LINKS_BLOCK_ID) if content_block payloads = content_block.records.pluck(:payload) service_payload = payloads.detect { |payload| payload['service_name'] == service_name } return service_payload['service_url'] if service_payload && valid_url?(service_payload['service_url']) end nil end def valid_url?(url) /http.*\..*/.match(url) end protected def person_contact_methods @person_contact_methods ||= begin if content_block = object.content_blocks.find_by(internal_id: GobiertoCommon::DynamicContent::CONTACT_BLOCK_ID) content_block.records.pluck(:payload) else [] end end end end end Add historical_charges_names to PersonDecorator module GobiertoPeople class PersonDecorator < BaseDecorator def initialize(person) @object = person end def contact_email person_contact_method_for("Email", "service_url") end def twitter_handle person_contact_method_for("Twitter", "service_handle") end def twitter_url person_contact_method_for("Twitter", "service_url") end def facebook_handle person_contact_method_for("Facebook", "service_handle") end def facebook_url person_contact_method_for("Facebook", "service_url") end def linkedin_handle person_contact_method_for("LinkedIn", "service_handle") end def linkedin_url person_contact_method_for("LinkedIn", "service_url") end def instagram_handle person_contact_method_for("Instagram", "service_handle") end def instagram_url person_contact_method_for("Instagram", "service_url") end def trips_url person_custom_link_for('Viajes') end def gifts_url person_custom_link_for('Obsequios') end def content_blocks_for_bio(site_id) object.content_blocks(site_id).where.not(internal_id: GobiertoCommon::DynamicContent::CONTACT_BLOCK_ID) end def has_bio_or_cv? bio.present? || bio_url.present? end def has_biographic_blocks? content_blocks_for_bio(site_id).any? { |block| block.records.any? } end def has_biographic_data? has_bio_or_cv? || has_biographic_blocks? end def has_posts? posts.active.any? end def has_statements? statements.active.any? end def meetings_with_interest_groups(start_date: nil, end_date: nil) QueryWithEvents.new(source: events.with_interest_group.published, start_date: start_date, end_date: end_date) end def interest_groups_count(start_date: nil, end_date: nil) meetings_with_interest_groups(start_date: start_date, end_date: end_date).select(:interest_group_id).distinct.count end def historical_charges_names historical_charges.reverse_sorted end private def person_contact_method_for(service_name, attribute_name) person_contact_methods.detect do |contact_method| contact_method["service_name"] == service_name end.try(:[], attribute_name) end def person_custom_link_for(service_name) content_block = object.content_blocks.find_by(internal_id: GobiertoCommon::DynamicContent::CUSTOM_LINKS_BLOCK_ID) if content_block payloads = content_block.records.pluck(:payload) service_payload = payloads.detect { |payload| payload['service_name'] == service_name } return service_payload['service_url'] if service_payload && valid_url?(service_payload['service_url']) end nil end def valid_url?(url) /http.*\..*/.match(url) end protected def person_contact_methods @person_contact_methods ||= begin if content_block = object.content_blocks.find_by(internal_id: GobiertoCommon::DynamicContent::CONTACT_BLOCK_ID) content_block.records.pluck(:payload) else [] end end end end end
Fork twitter agent to create google calendar publish agent module Agents class GoogleCalendarPublishAgent < Agent include LiquidInterpolatable cannot_be_scheduled! description <<-MD The GoogleCalendarPublishAgent creates events on your google calendar. Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent. MD def validate_options errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present? end def working? event_created_within?(options['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs? end def default_options { 'expected_update_period_in_days' => "10", 'calendar_id' => '?', 'message' => "{{text}}" } end def receive(incoming_events) incoming_events.each do |event| text = interpolate_string(options['message'], event.payload) calendar_event = publish text create_event :payload => { 'success' => true, 'published_calendar_event' => text, 'tweet_id' => calendar_event.id, 'agent_id' => event.agent_id, 'event_id' => event.id } end end def publish(text) calendar = GoogleCalendar.new(options, Rails.logger) calender.publish_as(options['calendar_id'], text) end end end
module Effective module EffectiveDatatable module Format BLANK = ''.freeze private def format(collection) # We want to use the render :collection for each column that renders partials rendered = {} columns.each do |name, opts| if opts[:partial] && state[:visible][name] locals = { datatable: self, column: columns[name], controller_namespace: controller_namespace }.merge(actions_col_locals(opts)).merge(resource_col_locals(opts)) rendered[name] = (view.render( partial: opts[:partial], as: (opts[:partial_as] || :resource), collection: collection.map { |row| row[opts[:index]] }, formats: :html, locals: locals, spacer_template: '/effective/datatables/spacer_template', ) || '').split('EFFECTIVEDATATABLESSPACER') end end collection.each_with_index do |row, row_index| columns.each do |name, opts| next unless state[:visible][name] index = opts[:index] value = row[index] row[index] = ( if opts[:format] && rendered.key?(name) dsl_tool.instance_exec(value, row, rendered[name][row_index], &opts[:format]) elsif opts[:format] dsl_tool.instance_exec(value, row, &opts[:format]) elsif opts[:partial] rendered[name][row_index] else format_column(value, opts) end ) end end end def format_column(value, column) return if value.nil? || (column[:resource] && value.blank?) unless column[:as] == :email return value if value.kind_of?(String) end case column[:as] when :boolean case value when true ; 'Yes' when false ; 'No' end when :currency view.number_to_currency(value) when :date (value.strftime('%F') rescue BLANK) when :datetime (value.strftime('%F %H:%M') rescue BLANK) when :decimal value when :duration view.number_to_duration(value) when :effective_addresses value.to_html when :effective_obfuscation value when :effective_roles value.join(', ') when :email view.mail_to(value) when :integer value when :percentage case value when Integer ; "#{value}%" when Numeric ; view.number_to_percentage(value * 100, precision: 2) end when :price case value when Integer ; view.number_to_currency(value / 100.0) # an Integer representing the number of cents when Numeric ; view.number_to_currency(value) end when :time (value.strftime('%H:%M') rescue BLANK) else value.to_s end end def actions_col_locals(opts) return {} unless opts[:as] == :actions { actions_col_locals: opts[:actions].merge(effective_resource: resource) } end def resource_col_locals(opts) return {} unless (resource = opts[:resource]).present? locals = { name: opts[:name], effective_resource: resource, show_action: false, edit_action: false } case opts[:action] when :edit locals[:edit_action] = (resource.routes[:edit] && EffectiveDatatables.authorized?(view.controller, :edit, resource.klass)) when :show locals[:show_action] = (resource.routes[:show] && EffectiveDatatables.authorized?(view.controller, :show, resource.klass)) when false # Nothing else # Fallback to defaults - check edit then show if resource.routes[:edit] && EffectiveDatatables.authorized?(view.controller, :edit, resource.klass) locals[:edit_action] = true elsif resource.routes[:show] && EffectiveDatatables.authorized?(view.controller, :show, resource.klass) locals[:show_action] = true end end locals end end # / Rendering end end rendering resource actions mostly module Effective module EffectiveDatatable module Format BLANK = ''.freeze private def format(collection) # We want to use the render :collection for each column that renders partials rendered = {} columns.each do |name, opts| next if opts[:as] == :actions if opts[:partial] && state[:visible][name] locals = { datatable: self, column: columns[name], controller_namespace: controller_namespace }.merge(resource_col_locals(opts)) rendered[name] = (view.render( partial: opts[:partial], as: (opts[:partial_as] || :resource), collection: collection.map { |row| row[opts[:index]] }, formats: :html, locals: locals, spacer_template: '/effective/datatables/spacer_template', ) || '').split('EFFECTIVEDATATABLESSPACER') end end collection.each_with_index do |row, row_index| columns.each do |name, opts| next unless state[:visible][name] index = opts[:index] value = row[index] row[index] = ( if opts[:format] && rendered.key?(name) dsl_tool.instance_exec(value, row, rendered[name][row_index], &opts[:format]) elsif opts[:format] dsl_tool.instance_exec(value, row, &opts[:format]) elsif opts[:as] == :actions atts = opts[:actions].merge(effective_resource: resource, partial: :dropleft) view.render_resource_actions(value, **atts) elsif opts[:partial] rendered[name][row_index] else format_column(value, opts) end ) end end end def format_column(value, column) return if value.nil? || (column[:resource] && value.blank?) unless column[:as] == :email return value if value.kind_of?(String) end case column[:as] when :boolean case value when true ; 'Yes' when false ; 'No' end when :currency view.number_to_currency(value) when :date (value.strftime('%F') rescue BLANK) when :datetime (value.strftime('%F %H:%M') rescue BLANK) when :decimal value when :duration view.number_to_duration(value) when :effective_addresses value.to_html when :effective_obfuscation value when :effective_roles value.join(', ') when :email view.mail_to(value) when :integer value when :percentage case value when Integer ; "#{value}%" when Numeric ; view.number_to_percentage(value * 100, precision: 2) end when :price case value when Integer ; view.number_to_currency(value / 100.0) # an Integer representing the number of cents when Numeric ; view.number_to_currency(value) end when :time (value.strftime('%H:%M') rescue BLANK) else value.to_s end end def resource_col_locals(opts) return {} unless (resource = opts[:resource]).present? locals = { name: opts[:name], effective_resource: resource, show_action: false, edit_action: false } case opts[:action] when :edit locals[:edit_action] = (resource.routes[:edit] && EffectiveDatatables.authorized?(view.controller, :edit, resource.klass)) when :show locals[:show_action] = (resource.routes[:show] && EffectiveDatatables.authorized?(view.controller, :show, resource.klass)) when false # Nothing else # Fallback to defaults - check edit then show if resource.routes[:edit] && EffectiveDatatables.authorized?(view.controller, :edit, resource.klass) locals[:edit_action] = true elsif resource.routes[:show] && EffectiveDatatables.authorized?(view.controller, :show, resource.klass) locals[:show_action] = true end end locals end end # / Rendering end end
module Shopping class CartPurchaseProcessor < BaseProcessor after_show do user_id = result.resource.cart.user_id rescue nil if !user_id.present? || user_id != resource_owner_id raise Shopping::NotAuthorizedError.new('not authorized', resource_klass: Shopping::CartPurchase) end end def create_resource cart_id = params[:data][:attributes][:cart_id] if !(cart = Cart.find(cart_id)) || !cart.user_id.present? || cart.user_id != resource_owner_id raise Shopping::NotAuthorizedError.new('not authorized', resource_klass: Shopping::CartPurchase) end other_cart = Cart.where(origin: cart.origin, failed_at: nil, purchased_at: nil, user_id: cart.user_id).where.not(id: cart.id).first if other_cart.present? && other_cart.cart_purchases.incomplete.exists? raise Shopping::PurchaseInProgressError.new("cannot purchase this cart while another purchase is in progress", resource_klass: Shopping::CartPurchase) end begin service = Shopping.config.purchase_cart_service_class.new(cart_id, params[:data][:attributes]) service.perform! rescue ActiveRecord::RecordNotFound => e return json_api_error(400, JSONAPI::Exceptions::BadRequest.new(e)) rescue => e return json_api_error(500, JSONAPI::Exceptions::InternalServerError.new(e, internal_server_error_overrides)) end resource = resource_klass.create(context) result = resource.replace_fields({type: 'cart_purchases', attributes: params[:data][:attributes]}) return JSONAPI::ResourceOperationResult.new((result == :completed ? :created : :accepted), resource, result_options) end private def json_api_error(status, exn) JSONAPI::ErrorsOperationResult.new(status, exn.errors, {}) end def internal_server_error_overrides if Rails.env.test? {} else { meta: {} } end end end end Reorder resource creation to prevent race condition module Shopping class CartPurchaseProcessor < BaseProcessor after_show do user_id = result.resource.cart.user_id rescue nil if !user_id.present? || user_id != resource_owner_id raise Shopping::NotAuthorizedError.new('not authorized', resource_klass: Shopping::CartPurchase) end end def create_resource cart_id = params[:data][:attributes][:cart_id] if !(cart = Cart.find(cart_id)) || !cart.user_id.present? || cart.user_id != resource_owner_id raise Shopping::NotAuthorizedError.new('not authorized', resource_klass: Shopping::CartPurchase) end other_cart = Cart.where(origin: cart.origin, failed_at: nil, purchased_at: nil, user_id: cart.user_id).where.not(id: cart.id).first if other_cart.present? && other_cart.cart_purchases.incomplete.exists? raise Shopping::PurchaseInProgressError.new("cannot purchase this cart while another purchase is in progress", resource_klass: Shopping::CartPurchase) end begin resource = resource_klass.create(context) result = resource.replace_fields({type: 'cart_purchases', attributes: params[:data][:attributes]}) service = Shopping.config.purchase_cart_service_class.new(cart_id, params[:data][:attributes]) service.perform! return JSONAPI::ResourceOperationResult.new((result == :completed ? :created : :accepted), resource, result_options) rescue ActiveRecord::RecordNotFound => e return json_api_error(400, JSONAPI::Exceptions::BadRequest.new(e)) rescue => e return json_api_error(500, JSONAPI::Exceptions::InternalServerError.new(e, internal_server_error_overrides)) end return JSONAPI::ResourceOperationResult.new((result == :completed ? :created : :accepted), resource, result_options) end private def json_api_error(status, exn) JSONAPI::ErrorsOperationResult.new(status, exn.errors, {}) end def internal_server_error_overrides if Rails.env.test? {} else { meta: {} } end end end end
#!/usr/bin/ruby -W0 # encoding: utf-8 module JPCalendar require 'date' class JPDate < Date def monday(w) self + 7 * w.to_i - ((self - 1).wday + 6) % 7 - 1 end def spring_day case year when 1900..2099 dy = year - 1900 Date.new(year, 3, (21.4471 + 0.242377*dy - dy/4).to_i) end end def autumn_day case year when 1900..2099 dy = year - 1900 Date.new(year, 9, (23.8896 + 0.242032*dy - dy/4).to_i) end end end class JPHoliday HOLIDAYS = [ {month:4, day:10, term:1959..1959, name:'結婚の儀'}, {month:2, day:24, term:1989..1989, name:'大喪の礼'}, {month:11, day:12, term:1990..1990, name:'即位の礼'}, {month:6, day:9, term:1993..1993, name:'結婚の儀'}, {month:1, day:1, term: 0..9999, name:'元旦'}, {month:1, day:15, term: 0..1999, name:'成人の日'}, {month:1, day:'monday 2', term:2000..9999, name:'成人の日'}, {month:2, day:11, term:1967..9999, name:'建国記念日'}, {month:3, day:'spring_day',term:1900..2099, name:'春分の日'}, {month:4, day:29, term: 0..1988, name:'天皇誕生日'}, {month:4, day:29, term:1989..2006, name:'みどりの日'}, {month:4, day:29, term:2007..9999, name:'昭和の日'}, {month:5, day:3 , term: 0..9999, name:'憲法記念日'}, {month:5, day:4 , term:2007..9999, name:'みどりの日'}, {month:5, day:5 , term: 0..9999, name:'こどもの日'}, {month:7, day:20, term:1996..2002, name:'海の日'}, {month:7, day:'monday 3', term:2003..9999, name:'海の日'}, {month:8, day:11, term:2016..9999, name:'山の日'}, {month:9, day:15, term:1966..2002, name:'敬老の日'}, {month:9, day:'monday 3', term:2003..9999, name:'敬老の日'}, {month:9, day:'autumn_day',term:1900..2099, name:'秋分の日'}, {month:10, day:10, term:1966..1999, name:'体育の日'}, {month:10, day:'monday 2', term:2000..9999, name:'体育の日'}, {month:11, day:3, term: 0..9999, name:'文化の日'}, {month:11, day:23, term: 0..9999, name:'勤労感謝の日'}, {month:12, day:23, term:1989..9999, name:'天皇誕生日'}, ] def initialize(y) # 有効な祝日を取り出し、日付を追加する enable_holidays = HOLIDAYS.select {|h| h[:term].include?(y)}.map do |h| case h[:day] when Fixnum {date: Date.new(y, h[:month], h[:day])}.merge(h) when String {date: JPDate.new(y, h[:month]).send(*h[:day].split)}.merge(h) end end enable_dates = enable_holidays.map {|h| h[:date]} # 振替休日を判定 enable_dates.each do |date| if date.wday == 0 while enable_dates.include?(date) date += 1 end enable_holidays << {date:date, name:'振替休日'} end end # 国民の休日を判定 enable_dates.each_cons(2) do |a, b| if b.day - a.day == 2 && (a + 1).wday != 0 && !enable_holidays.map {|h| h[:date]}.include?(a + 1) enable_holidays << {date:a + 1, name:'国民の休日'} end end @holidays_database = enable_holidays.map {|h| [h[:date], h[:name]]}.sort end def lookup(*args) case args.first when Fixnum @holidays_database.assoc(Date.new(*args)) when Date @holidays_database.assoc(*args) when String @holidays_database.assoc(Date.parse(*args)) end end end # class JPHoliday end # module JPCalendar module JcalEx refine String do def length_ja half_lenght = count(" -~") full_length = (length - half_lenght) * 2 half_lenght + full_length end def ljust_ja(width, padstr=' ') n = [0, width - length_ja].max self + padstr * n end def rjust_ja(width, padstr=' ') n = [0, width - length_ja].max padstr * n + self end def center_ja(width, padstr=' ') n = [0, width - length_ja].max padstr * (n/2) + self end end end using JcalEx module Jcal include JPCalendar module_function def render_matrix(y, m) start_date = Date.new(y, m) - Date.new(y, m).wday end_date = Date.new(y, m, -1) + (6 - Date.new(y, m, -1).wday) date_list = start_date..end_date holiday = JPHoliday.new(y) puts sprintf("%4d年 %2d月", y, m).center_ja(16 * 7) header = %w(日 月 火 水 木 金 土).map {|s| s.rjust_ja(16)} header[0] = "\e[31m" + header[0] + "\e[0m" header[6] = "\e[36m" + header[6] + "\e[0m" print header.join, "\n" date_list.each_slice(7) do |week| week.each do |date| today_marker = date == Date.today ? "\e[7m" : '' holiday_name = holiday.lookup(date).last.rjust_ja(14) rescue ' ' * 14 case when date.month != m printf "\e[37m%s%s%2d\e[0m", holiday_name, today_marker, date.day when holiday.lookup(date) printf "\e[31m%s%s%2d\e[0m", holiday_name, today_marker, date.day when date.wday == 0 printf "\e[31m%s%s%2d\e[0m", holiday_name, today_marker, date.day when date.wday == 6 printf "\e[36m%s%s%2d\e[0m", holiday_name, today_marker, date.day else printf "%s%s%2d\e[0m", holiday_name, today_marker, date.day end end puts end puts end def render_list(y, col) week_ja = %w(日 月 火 水 木 金 土) date366 = (Date.new(2004, 1, 1)..Date.new(2004, 12, 31)).to_a list366 = Array.new(366, '') (y...y + col).each do |y| holiday = JPHoliday.new(y) date366.each_with_index do |date, i| date = Date.new(y, date.month, date.day) rescue nil today_marker = (date == Date.today) ? "\e[7m" : '' rescue '' holiday_name = holiday.lookup(date).last.ljust_ja(12) rescue ' ' * 12 case when date == nil list366[i] += sprintf("\e[ 0m%s%s%s\e[0m", ' ' * 10, ' ' * 2, holiday_name) when holiday.lookup(date) list366[i] += sprintf("\e[31m%s%s%s\e[0;31m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) when date.wday == 0 list366[i] += sprintf("\e[31m%s%s%s\e[0;31m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) when date.wday == 6 list366[i] += sprintf("\e[36m%s%s%s\e[0;36m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) else list366[i] += sprintf("\e[ 0m%s%s%s\e[0; 0m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) end end end list366.each {|list| puts list} end def matrix(base_year, start_month, end_month=start_month) base_year -= 1 if start_month <= 0 start_month, end_month = *[start_month, end_month].map {|i| i %= 12; i == 0 ? 12 : i} if start_month <= end_month (start_month..end_month).each {|i| render_matrix(base_year , i)} else (start_month..12 ).each {|i| render_matrix(base_year , i)} ( 1..end_month).each {|i| render_matrix(base_year + 1, i)} end end def list(base_year, column) render_list(base_year, [column, 10].min) end end # module Jcal require 'optparse' # オプション解析 options = {} OptionParser.new do |opt| opt.banner = 'Usage: jcal [options] [yyyy|mm] [yyyy|mm]' opt.separator('') opt.on('-y[NUM]', 'List NUM years.(0-10)') {|v| options[:years] = v.to_i} opt.on('-m[NUM]', 'Show NUM months.(0-12)') {|v| options[:months] = v.to_i} opt.separator('') opt.on('Example:', ' jcal # Show monthly calendar of this month.', ' jcal 8 # Show monthly calendar of Aug.', ' jcal 8 2 # Show monthly calendar from Aug. to Feb. of next year.', ' jcal 2010 # Show all monthly calendar of 2010.', ' jcal -y # Show all monthly calendar of this year.', ' jcal -y5 # List from this year to after 5 years.', ' jcal 2011 2012 # List from 2011 to 2012.', ' jcal -m # Show monthly calendar from last month to next month.', ' jcal -m6 2010 1 # Show monthly calendar from Jan.2010 to Jun.2010.', ) begin opt.parse!(ARGV) rescue => e puts e exit end end # 引数解析 y = [] m = [] (0..1).each {|i| ARGV[i] && (ARGV[i].to_i > 12 ? y << ARGV[i].to_i : m << ARGV[i].to_i)} m.map! {|i| i == 0 ? Date.today.month : i} m = [1, 12] if y.size == 1 && m.empty? && !options.key?(:months)# 西暦1・月0・-mなしなら、12カ月分表示 options[:years] ||= (y[1] - y[0]).abs + 1 if y.size == 2 # 西暦2なら、-yに期間を追加 m[0] ||= Date.today.month y[0] ||= Date.today.year m = [m[0] - 1, m[0] + 1] if options.key?(:months) && options[:months] == 0 # -m引数なしは、前月から翌月まで表示 m = [m[0] , m[0] + options[:months] - 1] if options.key?(:months) && options[:months] > 0 # -m引数ありは、指定した月数分を表示 m = [1, 12] if options.key?(:years) && options[:years] <= 1 # -y指定期間が1年以下なら、12カ月分表示 (y[0] = options[:years]; options[:years] = 0) if options.key?(:years) && options[:years] >= 1900 # -y西暦なら、西暦と解釈 if options.key?(:years) && options[:years] >= 2 Jcal::list(y.min, options[:years]) else Jcal::matrix(y.min, *m) end オプション優先で引数解析を行う #!/usr/bin/ruby -W0 # encoding: utf-8 module JPCalendar require 'date' class JPDate < Date def monday(w) self + 7 * w.to_i - ((self - 1).wday + 6) % 7 - 1 end def spring_day case year when 1900..2099 dy = year - 1900 Date.new(year, 3, (21.4471 + 0.242377*dy - dy/4).to_i) end end def autumn_day case year when 1900..2099 dy = year - 1900 Date.new(year, 9, (23.8896 + 0.242032*dy - dy/4).to_i) end end end class JPHoliday HOLIDAYS = [ {month:4, day:10, term:1959..1959, name:'結婚の儀'}, {month:2, day:24, term:1989..1989, name:'大喪の礼'}, {month:11, day:12, term:1990..1990, name:'即位の礼'}, {month:6, day:9, term:1993..1993, name:'結婚の儀'}, {month:1, day:1, term: 0..9999, name:'元旦'}, {month:1, day:15, term: 0..1999, name:'成人の日'}, {month:1, day:'monday 2', term:2000..9999, name:'成人の日'}, {month:2, day:11, term:1967..9999, name:'建国記念日'}, {month:3, day:'spring_day',term:1900..2099, name:'春分の日'}, {month:4, day:29, term: 0..1988, name:'天皇誕生日'}, {month:4, day:29, term:1989..2006, name:'みどりの日'}, {month:4, day:29, term:2007..9999, name:'昭和の日'}, {month:5, day:3 , term: 0..9999, name:'憲法記念日'}, {month:5, day:4 , term:2007..9999, name:'みどりの日'}, {month:5, day:5 , term: 0..9999, name:'こどもの日'}, {month:7, day:20, term:1996..2002, name:'海の日'}, {month:7, day:'monday 3', term:2003..9999, name:'海の日'}, {month:8, day:11, term:2016..9999, name:'山の日'}, {month:9, day:15, term:1966..2002, name:'敬老の日'}, {month:9, day:'monday 3', term:2003..9999, name:'敬老の日'}, {month:9, day:'autumn_day',term:1900..2099, name:'秋分の日'}, {month:10, day:10, term:1966..1999, name:'体育の日'}, {month:10, day:'monday 2', term:2000..9999, name:'体育の日'}, {month:11, day:3, term: 0..9999, name:'文化の日'}, {month:11, day:23, term: 0..9999, name:'勤労感謝の日'}, {month:12, day:23, term:1989..9999, name:'天皇誕生日'}, ] def initialize(y) # 有効な祝日を取り出し、日付を追加する enable_holidays = HOLIDAYS.select {|h| h[:term].include?(y)}.map do |h| case h[:day] when Fixnum {date: Date.new(y, h[:month], h[:day])}.merge(h) when String {date: JPDate.new(y, h[:month]).send(*h[:day].split)}.merge(h) end end enable_dates = enable_holidays.map {|h| h[:date]} # 振替休日を判定 enable_dates.each do |date| if date.wday == 0 while enable_dates.include?(date) date += 1 end enable_holidays << {date:date, name:'振替休日'} end end # 国民の休日を判定 enable_dates.each_cons(2) do |a, b| if b.day - a.day == 2 && (a + 1).wday != 0 && !enable_holidays.map {|h| h[:date]}.include?(a + 1) enable_holidays << {date:a + 1, name:'国民の休日'} end end @holidays_database = enable_holidays.map {|h| [h[:date], h[:name]]}.sort end def lookup(*args) case args.first when Fixnum @holidays_database.assoc(Date.new(*args)) when Date @holidays_database.assoc(*args) when String @holidays_database.assoc(Date.parse(*args)) end end end # class JPHoliday end # module JPCalendar module JcalEx refine String do def length_ja half_lenght = count(" -~") full_length = (length - half_lenght) * 2 half_lenght + full_length end def ljust_ja(width, padstr=' ') n = [0, width - length_ja].max self + padstr * n end def rjust_ja(width, padstr=' ') n = [0, width - length_ja].max padstr * n + self end def center_ja(width, padstr=' ') n = [0, width - length_ja].max padstr * (n/2) + self end end end using JcalEx module Jcal include JPCalendar module_function def render_matrix(y, m) start_date = Date.new(y, m) - Date.new(y, m).wday end_date = Date.new(y, m, -1) + (6 - Date.new(y, m, -1).wday) date_list = start_date..end_date holiday = JPHoliday.new(y) puts sprintf("%4d年 %2d月", y, m).center_ja(16 * 7) header = %w(日 月 火 水 木 金 土).map {|s| s.rjust_ja(16)} header[0] = "\e[31m" + header[0] + "\e[0m" header[6] = "\e[36m" + header[6] + "\e[0m" print header.join, "\n" date_list.each_slice(7) do |week| week.each do |date| today_marker = date == Date.today ? "\e[7m" : '' holiday_name = holiday.lookup(date).last.rjust_ja(14) rescue ' ' * 14 case when date.month != m printf "\e[37m%s%s%2d\e[0m", holiday_name, today_marker, date.day when holiday.lookup(date) printf "\e[31m%s%s%2d\e[0m", holiday_name, today_marker, date.day when date.wday == 0 printf "\e[31m%s%s%2d\e[0m", holiday_name, today_marker, date.day when date.wday == 6 printf "\e[36m%s%s%2d\e[0m", holiday_name, today_marker, date.day else printf "%s%s%2d\e[0m", holiday_name, today_marker, date.day end end puts end puts end def render_list(y, col) week_ja = %w(日 月 火 水 木 金 土) date366 = (Date.new(2004, 1, 1)..Date.new(2004, 12, 31)).to_a list366 = Array.new(366, '') (y...y + col).each do |y| holiday = JPHoliday.new(y) date366.each_with_index do |date, i| date = Date.new(y, date.month, date.day) rescue nil today_marker = (date == Date.today) ? "\e[7m" : '' rescue '' holiday_name = holiday.lookup(date).last.ljust_ja(12) rescue ' ' * 12 case when date == nil list366[i] += sprintf("\e[ 0m%s%s%s\e[0m", ' ' * 10, ' ' * 2, holiday_name) when holiday.lookup(date) list366[i] += sprintf("\e[31m%s%s%s\e[0;31m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) when date.wday == 0 list366[i] += sprintf("\e[31m%s%s%s\e[0;31m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) when date.wday == 6 list366[i] += sprintf("\e[36m%s%s%s\e[0;36m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) else list366[i] += sprintf("\e[ 0m%s%s%s\e[0; 0m%s\e[0m",today_marker , date.to_s, week_ja[date.wday], holiday_name) end end end list366.each {|list| puts list} end def matrix(base_year, start_month, end_month=start_month) base_year -= 1 if start_month <= 0 start_month, end_month = *[start_month, end_month].map {|i| i %= 12; i == 0 ? 12 : i} if start_month <= end_month (start_month..end_month).each {|i| render_matrix(base_year , i)} else (start_month..12 ).each {|i| render_matrix(base_year , i)} ( 1..end_month).each {|i| render_matrix(base_year + 1, i)} end end def list(base_year, column) render_list(base_year, [column, 10].min) end end # module Jcal require 'optparse' # オプション解析 options = {} OptionParser.new do |opt| opt.banner = 'Usage: jcal [options] [yyyy|mm] [yyyy|mm]' opt.separator('') opt.on('-y[NUM]', 'List NUM years.(0-10)') {|v| options[:years] = v.to_i} opt.on('-m[NUM]', 'Show NUM months.(0-12)') {|v| options[:months] = v.to_i} opt.separator('') opt.on('Example:', ' jcal # Show monthly calendar of this month.', ' jcal 8 # Show monthly calendar of Aug.', ' jcal 8 2 # Show monthly calendar from Aug. to Feb. of next year.', ' jcal 2010 # Show all monthly calendar of 2010.', ' jcal -y # Show all monthly calendar of this year.', ' jcal -y5 # List from this year to after 5 years.', ' jcal 2011 2012 # List from 2011 to 2012.', ' jcal -m # Show monthly calendar from last month to next month.', ' jcal -m6 2010 1 # Show monthly calendar from Jan.2010 to Jun.2010.', ) begin opt.parse!(ARGV) rescue => e puts e exit end end # 引数解析 y = [] m = [] (0..1).each {|i| ARGV[i] && (ARGV[i].to_i > 12 ? y << ARGV[i].to_i : m << ARGV[i].to_i)} m.map! {|i| i == 0 ? Date.today.month : i} m = [1, 12] if y.size == 1 && m.empty? && options.empty? # 西暦1個・月0個・オプションなしは、12カ月分表示 y[0] ||= Date.today.year m[0] ||= Date.today.month m = [m[0] - 1, m[0] + 1] if options.key?(:months) && options[:months] == 0 # -m引数なしは、前月から翌月まで表示 m = [m[0] , m[0] + options[:months] - 1] if options.key?(:months) && options[:months] > 0 # -m引数ありは、指定した月数分を表示 (y[0] = options[:years]; options[:years] = 0) if options.key?(:years) && options[:years] >= 1900 # -y西暦なら、西暦と解釈 m = [1, 12] if options.key?(:years) && options[:years] <= 1 # -y指定期間が1年以下は、12カ月分表示 options[:years] ||= (y[1] - y[0]).abs + 1 if y.size == 2 && options.empty? # 西暦2個・月0個・オプションなしは、-yに期間を追加 if options.key?(:years) && options[:years] >= 2 Jcal::list(y.min, options[:years]) else Jcal::matrix(y[0], *m) end
#!/usr/bin/env ruby # # Push ioping stats into graphite # === # # Copyright 2014 Mitsutoshi Aoe <maoe@foldr.in> # # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. require 'rubygems' if RUBY_VERSION < '1.9.0' require 'sensu-plugin/metric/cli' require 'socket' class IOPingMetrics < Sensu::Plugin::Metric::CLI::Graphite option :destination, :short => '-d DEVICE|FILE|DIRECTORY', :description => 'Destination device, file or directory', :required => true option :name, :short => '-n NAME', :description => 'Name of the series', :required => true option :count, :short => '-c COUNT', :description => 'Stop after count requests', :default => 1, :proc => Proc.new {|s| s.to_i } option :interval, :short => '-i INTERVAL', :description => 'Interval between requests in seconds', :default => 1.0, :proc => Proc.new {|s| s.to_f } option :cached, :short => '-C', :description => 'Use cached I/O', :boolean => true, :default => false option :direct, :short => '-D', :description => 'Use direct I/O', :boolean => true, :default => false option :scheme, :description => 'Metric naming scheme, text to prepend to metric', :short => '-s SCHEME', :long => '--scheme SCHEME', :default => Socket.gethostname def run stats = ioping_stats(config[:server]) critical "Failed to get/parse ioping output" if stats.nil? stats.each do |key, value| output([config[:scheme], :ioping, config[:name], key].join('.'), value) end ok end def ioping_stats(servers) options = [] options << "-C" if config[:cached] options << "-D" if config[:direct] output = `ioping #{options.join(' ')} -c #{config[:count]} -i #{config[:interval]} #{config[:destination]}` parse_ioping(output) end def parse_ioping(str) stats = parse_0_8(str) stats = parse_0_6(str) if stats.nil? stats end NUMBER = /\d+(?:\.\d+)?/ TIME_UNIT = /(?:us|ms|s|min|hour|day)/ TIME_UNITS = { 'us' => 1e-6, 'ms' => 1e-3, 's' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60 } STATS_HEADER = /min\/avg\/max\/mdev/ def parse_0_6(str) value = /#{NUMBER}/ sep = /\// pattern = /^#{STATS_HEADER} = (#{value})#{sep}(#{value})#{sep}(#{value})#{sep}(#{value}) (#{TIME_UNIT})$/ str.scan(pattern).each do |scanned| min, avg, max, mdev, time_unit = scanned time_unit = TIME_UNITS[time_unit] if scanned.all? && time_unit return { :min => min.to_f * time_unit, :avg => avg.to_f * time_unit, :max => max.to_f * time_unit, :mdev => mdev.to_f * time_unit } end end nil end def parse_0_8(str) value = /(#{NUMBER}) (#{TIME_UNIT})\s/ sep = /\/\s/ pattern = /^#{STATS_HEADER} = #{value}#{sep}#{value}#{sep}#{value}#{sep}#{value}$/ str.scan(pattern).each do |scanned| values = [] units = [] scanned.each_with_index do |val, idx| if idx.even? values[idx/2] = val.to_f else units[idx/2] = TIME_UNITS[val] end end if values.all? && units.all? return { :min => values[0] * units[0], :avg => values[1] * units[1], :max => values[2] * units[2], :mdev => values[3] * units[3] } end end nil end end ioping-metrics.rb: Set executable #!/usr/bin/env ruby # # Push ioping stats into graphite # === # # Copyright 2014 Mitsutoshi Aoe <maoe@foldr.in> # # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. require 'rubygems' if RUBY_VERSION < '1.9.0' require 'sensu-plugin/metric/cli' require 'socket' class IOPingMetrics < Sensu::Plugin::Metric::CLI::Graphite option :destination, :short => '-d DEVICE|FILE|DIRECTORY', :description => 'Destination device, file or directory', :required => true option :name, :short => '-n NAME', :description => 'Name of the series', :required => true option :count, :short => '-c COUNT', :description => 'Stop after count requests', :default => 1, :proc => Proc.new {|s| s.to_i } option :interval, :short => '-i INTERVAL', :description => 'Interval between requests in seconds', :default => 1.0, :proc => Proc.new {|s| s.to_f } option :cached, :short => '-C', :description => 'Use cached I/O', :boolean => true, :default => false option :direct, :short => '-D', :description => 'Use direct I/O', :boolean => true, :default => false option :scheme, :description => 'Metric naming scheme, text to prepend to metric', :short => '-s SCHEME', :long => '--scheme SCHEME', :default => Socket.gethostname def run stats = ioping_stats(config[:server]) critical "Failed to get/parse ioping output" if stats.nil? stats.each do |key, value| output([config[:scheme], :ioping, config[:name], key].join('.'), value) end ok end def ioping_stats(servers) options = [] options << "-C" if config[:cached] options << "-D" if config[:direct] output = `ioping #{options.join(' ')} -c #{config[:count]} -i #{config[:interval]} #{config[:destination]}` parse_ioping(output) end def parse_ioping(str) stats = parse_0_8(str) stats = parse_0_6(str) if stats.nil? stats end NUMBER = /\d+(?:\.\d+)?/ TIME_UNIT = /(?:us|ms|s|min|hour|day)/ TIME_UNITS = { 'us' => 1e-6, 'ms' => 1e-3, 's' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60 } STATS_HEADER = /min\/avg\/max\/mdev/ def parse_0_6(str) value = /#{NUMBER}/ sep = /\// pattern = /^#{STATS_HEADER} = (#{value})#{sep}(#{value})#{sep}(#{value})#{sep}(#{value}) (#{TIME_UNIT})$/ str.scan(pattern).each do |scanned| min, avg, max, mdev, time_unit = scanned time_unit = TIME_UNITS[time_unit] if scanned.all? && time_unit return { :min => min.to_f * time_unit, :avg => avg.to_f * time_unit, :max => max.to_f * time_unit, :mdev => mdev.to_f * time_unit } end end nil end def parse_0_8(str) value = /(#{NUMBER}) (#{TIME_UNIT})\s/ sep = /\/\s/ pattern = /^#{STATS_HEADER} = #{value}#{sep}#{value}#{sep}#{value}#{sep}#{value}$/ str.scan(pattern).each do |scanned| values = [] units = [] scanned.each_with_index do |val, idx| if idx.even? values[idx/2] = val.to_f else units[idx/2] = TIME_UNITS[val] end end if values.all? && units.all? return { :min => values[0] * units[0], :avg => values[1] * units[1], :max => values[2] * units[2], :mdev => values[3] * units[3] } end end nil end end
#!/usr/bin/env macruby framework 'Foundation' require 'fileutils' require 'optparse' include FileUtils options = {} OptionParser.new do |opts| opts.banner = "Usage: setup.rb [options]" opts.on("-p", "--httpPort PORT", "Port for jenkins HTTP Interface") do |p| options[:port] = p end end.parse! unless ENV['USER'] == 'root' NSLog('You need to run this script as root.') exit end JENKINS_DOWNLOAD_URL = 'http://mirrors.jenkins-ci.org/war/latest/jenkins.war' JENKINS_INSTALL_DIR = '/Library/Application Support/Jenkins' JENKINS_WAR_FILE = File.join( JENKINS_INSTALL_DIR, 'jenkins.war' ) JENKINS_HOME_DIR = File.join( JENKINS_INSTALL_DIR, 'working_dir' ) JENKINS_LOG_DIR = '/Library/Logs/Jenkins' def write_file filename, &block File.open( filename, 'w', &block ) end ### Setup directories NSLog('Creating data and logging directories') mkdir_p [JENKINS_INSTALL_DIR, JENKINS_HOME_DIR, JENKINS_LOG_DIR] ### Download and install the .war file NSLog('Downloading the latest release of Jenkins') jenkins_url = NSURL.alloc.initWithString JENKINS_DOWNLOAD_URL jenkins_war = NSMutableData.dataWithContentsOfURL jenkins_url raise 'Failed to download Jenkins' if jenkins_war.nil? NSLog('Installing Jenkins') write_file(JENKINS_WAR_FILE) { |file| file.write String.new(jenkins_war) } ### Launchd setup NSLog('Creating launchd plist') LAUNCHD_LABEL = 'org.jenkins-ci.jenkins' LAUNCHD_DIRECTORY = '/Library/LaunchDaemons' LAUNCHD_FILE = "#{LAUNCHD_LABEL}.plist" LAUNCHD_PATH = File.join(LAUNCHD_DIRECTORY, LAUNCHD_FILE) arguments = [ '/usr/bin/java', '-jar', JENKINS_WAR_FILE ] arguments << "--httpPort=#{options[:port]}" if options.has_key?(:port) LAUNCHD_SCRIPT = { 'Label' => LAUNCHD_LABEL, 'RunAtLoad' => true, 'EnvironmentVariables' => { 'JENKINS_HOME' => JENKINS_HOME_DIR }, 'StandardOutPath' => File.join(JENKINS_LOG_DIR, 'jenkins.log'), 'StandardErrorPath' => File.join(JENKINS_LOG_DIR, 'jenkins-error.log'), 'Program' => '/usr/bin/java', 'ProgramArguments' => arguments # @todo Maybe setup Bonjour using the Socket key } NSLog('Installing launchd plist') write_file File.join(JENKINS_INSTALL_DIR, LAUNCHD_FILE) do |file| file.write LAUNCHD_SCRIPT.to_plist end NSLog('Starting launchd job for Jenkins') if File::exists?( LAUNCHD_PATH ) rm LAUNCHD_PATH end ln_s File.join(JENKINS_INSTALL_DIR, LAUNCHD_FILE), LAUNCHD_PATH `sudo launchctl load #{LAUNCHD_PATH}` `sudo launchctl start #{LAUNCHD_LABEL}` NSLog('Jenkins install complete.') Check if root user earlier #!/usr/bin/env macruby framework 'Foundation' require 'fileutils' require 'optparse' include FileUtils unless ENV['USER'] == 'root' NSLog('You need to run this script as root.') exit end options = {} OptionParser.new do |opts| opts.banner = "Usage: setup.rb [options]" opts.on("-p", "--httpPort PORT", "Port for jenkins HTTP Interface") do |p| options[:port] = p end end.parse! JENKINS_DOWNLOAD_URL = 'http://mirrors.jenkins-ci.org/war/latest/jenkins.war' JENKINS_INSTALL_DIR = '/Library/Application Support/Jenkins' JENKINS_WAR_FILE = File.join( JENKINS_INSTALL_DIR, 'jenkins.war' ) JENKINS_HOME_DIR = File.join( JENKINS_INSTALL_DIR, 'working_dir' ) JENKINS_LOG_DIR = '/Library/Logs/Jenkins' def write_file filename, &block File.open( filename, 'w', &block ) end ### Setup directories NSLog('Creating data and logging directories') mkdir_p [JENKINS_INSTALL_DIR, JENKINS_HOME_DIR, JENKINS_LOG_DIR] ### Download and install the .war file NSLog('Downloading the latest release of Jenkins') jenkins_url = NSURL.alloc.initWithString JENKINS_DOWNLOAD_URL jenkins_war = NSMutableData.dataWithContentsOfURL jenkins_url raise 'Failed to download Jenkins' if jenkins_war.nil? NSLog('Installing Jenkins') write_file(JENKINS_WAR_FILE) { |file| file.write String.new(jenkins_war) } ### Launchd setup NSLog('Creating launchd plist') LAUNCHD_LABEL = 'org.jenkins-ci.jenkins' LAUNCHD_DIRECTORY = '/Library/LaunchDaemons' LAUNCHD_FILE = "#{LAUNCHD_LABEL}.plist" LAUNCHD_PATH = File.join(LAUNCHD_DIRECTORY, LAUNCHD_FILE) arguments = [ '/usr/bin/java', '-jar', JENKINS_WAR_FILE ] arguments << "--httpPort=#{options[:port]}" if options.has_key?(:port) LAUNCHD_SCRIPT = { 'Label' => LAUNCHD_LABEL, 'RunAtLoad' => true, 'EnvironmentVariables' => { 'JENKINS_HOME' => JENKINS_HOME_DIR }, 'StandardOutPath' => File.join(JENKINS_LOG_DIR, 'jenkins.log'), 'StandardErrorPath' => File.join(JENKINS_LOG_DIR, 'jenkins-error.log'), 'Program' => '/usr/bin/java', 'ProgramArguments' => arguments # @todo Maybe setup Bonjour using the Socket key } NSLog('Installing launchd plist') write_file File.join(JENKINS_INSTALL_DIR, LAUNCHD_FILE) do |file| file.write LAUNCHD_SCRIPT.to_plist end NSLog('Starting launchd job for Jenkins') if File::exists?( LAUNCHD_PATH ) rm LAUNCHD_PATH end ln_s File.join(JENKINS_INSTALL_DIR, LAUNCHD_FILE), LAUNCHD_PATH `sudo launchctl load #{LAUNCHD_PATH}` `sudo launchctl start #{LAUNCHD_LABEL}` NSLog('Jenkins install complete.')
class Shark < Formula desc "Machine leaning library" homepage "http://shark-project.sourceforge.net/" url "https://github.com/Shark-ML/Shark/archive/v3.0.0.tar.gz" sha256 "b8b3bc9dca52369d4cc432b99ebdd37450056eb1b6ce86070996f16ea44d09ea" bottle do cellar :any sha256 "6cb63ae691b9b0876ae7343ee0145c3be23354a2fcdb40a524415367e65cecaf" => :el_capitan sha256 "b2a62a4cadb5a226aac9742947d8a739596ea2cc3ca8945795d781743d3be7ba" => :yosemite sha256 "e6b8a30aa855933b744a2939eb5826d5156e4a134aaa93d2bab3ab99f4f9f681" => :mavericks end depends_on "cmake" => :build depends_on "boost" def install system "cmake", ".", *std_cmake_args system "make", "install" end test do (testpath/"data.csv").write <<-EOS.undent 1 1 0 2 2 1 EOS (testpath/"test.cpp").write <<-EOS.undent #include <shark/Data/Csv.h> using namespace shark; int main() { ClassificationDataset data; importCSV(data, "data.csv", LAST_COLUMN, ' '); } EOS system ENV.cxx, "test.cpp", "-o", "test", "-I#{include}", "-L#{lib}", "-lshark", "-lboost_serialization" system "./test" end end shark 3.1.0 use boost 1.60.0 Closes #3916. Signed-off-by: ilovezfs <fbd54dbbcf9e596abad4ccdc4dfc17f80ebeaee2@icloud.com> class Shark < Formula desc "Machine leaning library" homepage "http://image.diku.dk/shark/" url "https://github.com/Shark-ML/Shark/archive/v3.1.0.tar.gz" sha256 "e36399b0720c69e6cb930786a8b099ac74707d71bc836a132424fa2282e368b4" bottle do cellar :any sha256 "6cb63ae691b9b0876ae7343ee0145c3be23354a2fcdb40a524415367e65cecaf" => :el_capitan sha256 "b2a62a4cadb5a226aac9742947d8a739596ea2cc3ca8945795d781743d3be7ba" => :yosemite sha256 "e6b8a30aa855933b744a2939eb5826d5156e4a134aaa93d2bab3ab99f4f9f681" => :mavericks end depends_on "cmake" => :build depends_on "homebrew/versions/boost160" def install system "cmake", ".", *std_cmake_args system "make", "install" end test do (testpath/"data.csv").write <<-EOS.undent 1 1 0 2 2 1 EOS (testpath/"test.cpp").write <<-EOS.undent #include <shark/Data/Csv.h> using namespace shark; int main() { ClassificationDataset data; importCSV(data, "data.csv", LAST_COLUMN, ' '); } EOS system ENV.cxx, "test.cpp", "-o", "test", "-L#{lib}", "-lshark", "-L#{Formula["boost160"].lib}", "-lboost_serialization", "-I#{Formula["boost160"].include}" system "./test" end end
Plugin.create(:worldon) do # spell系 # 投稿 defspell(:compose, :worldon_for_mastodon, condition: -> (world) { true }) do |world, body:, **opts| # TODO: PostBoxから渡ってくるoptsを適当に変換する if opts[:visibility].nil? opts.delete :visibility end world.post(body, opts) end defspell(:compose, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { true } ) do |world, status, body:, **opts| # TODO: PostBoxから渡ってくるoptsを適当に変換する if opts[:visibility].nil? opts.delete :visibility end status_id = status.id _status_id = PM::API.get_local_status_id(world, status) if !_status_id.nil? status_id = _status_id opts[:in_reply_to_id] = status_id hash = world.post(body, opts) if hash.nil? warn "投稿に失敗したかもしれません" pp hash $stdout.flush nil else new_status = PM::Status.build(world.domain, [hash]).first Plugin.call(:posted, world, [new_status]) Plugin.call(:update, world, [new_status]) new_status end else warn "返信先Statusが#{world.domain}内に見つかりませんでした:#{status.url}" nil end end # ふぁぼ defevent :worldon_favorite, prototype: [PM::World, PM::Status] # ふぁぼる on_worldon_favorite do |world, status| # TODO: guiなどの他plugin向け通知イベントの調査 status_id = PM::API.get_local_status_id(world, status.actual_status) if !status_id.nil? Plugin.call(:before_favorite, world, world.account, status) ret = PM::API.call(:post, world.domain, '/api/v1/statuses/' + status_id.to_s + '/favourite', world.access_token) if ret.nil? || ret[:error] Plugin.call(:fail_favorite, world, world.account, status) else status.actual_status.favourited = true Plugin.call(:favorite, world, world.account, status) end end end defspell(:favorite, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { !status.actual_status.favorite? } # TODO: favorite?の引数にworldを取って正しく判定できるようにする ) do |world, status| Plugin.call(:worldon_favorite, world, status.actual_status) end defspell(:favorited, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { status.actual_status.favorite? } # TODO: worldを使って正しく判定する ) do |world, status| Delayer::Deferred.new.next { status.actual_status.favorite? # TODO: 何を返せばいい? } end # ブーストイベント defevent :worldon_share, prototype: [PM::World, PM::Status] # ブースト on_worldon_share do |world, status| world.reblog(status).next{|shared| Plugin.call(:posted, world, [shared]) Plugin.call(:update, world, [shared]) } end defspell(:share, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { status.rebloggable? } # TODO: rebloggable?の引数にworldを取って正しく判定できるようにする ) do |world, status| world.reblog status end defspell(:shared, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { status.actual_status.shared? } # TODO: worldを使って正しく判定する ) do |world, status| Delayer::Deferred.new.next { status.actual_status.shared? # TODO: 何を返せばいい? } end end カスタム投稿コマンド(作業中) Plugin.create(:worldon) do # command custom_postable = Proc.new do |opt| world, = Plugin.filtering(:world_current, nil) world.class.slug == :worldon_for_mastodon && opt.widget.editable? end command( :worldon_custom_post, name: 'カスタム投稿', condition: custom_postable, visible: true, icon: Skin['post.png'], role: :postbox ) do |opt| i_postbox = opt.widget postbox, = Plugin.filtering(:gui_get_gtk_widget, i_postbox) body = postbox.widget_post.buffer.text #to_list = postbox.all_options[:to] # private methodなので無理 dialog "カスタム投稿" do # オプションを並べる input "CW警告文", :spoiler_text self[:body] = body multitext "本文", :body boolean "メディアを閲覧注意としてマークする(添付メディアがある場合のみ)", :sensitive vis_opts = { public: '公開', unlisted: '未収載', private: '非公開', direct: 'ダイレクト', } select "公開範囲", :visibility do option :public, "公開" option :unlisted, "未収載" option :private, "非公開" option :direct, "ダイレクト" end fileselect "添付メディア1", :media1 fileselect "添付メディア2", :media2 fileselect "添付メディア3", :media3 fileselect "添付メディア4", :media4 end.next do |result| # 投稿 # まず画像をアップロード # 画像がアップロードできたらcompose spellを起動 end end # spell系 # 投稿 defspell(:compose, :worldon_for_mastodon, condition: -> (world) { true }) do |world, body:, **opts| # TODO: PostBoxから渡ってくるoptsを適当に変換する if opts[:visibility].nil? opts.delete :visibility end world.post(body, opts) end defspell(:compose, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { true } ) do |world, status, body:, **opts| # TODO: PostBoxから渡ってくるoptsを適当に変換する if opts[:visibility].nil? opts.delete :visibility end status_id = status.id _status_id = PM::API.get_local_status_id(world, status) if !_status_id.nil? status_id = _status_id opts[:in_reply_to_id] = status_id hash = world.post(body, opts) if hash.nil? warn "投稿に失敗したかもしれません" pp hash $stdout.flush nil else new_status = PM::Status.build(world.domain, [hash]).first Plugin.call(:posted, world, [new_status]) Plugin.call(:update, world, [new_status]) new_status end else warn "返信先Statusが#{world.domain}内に見つかりませんでした:#{status.url}" nil end end # ふぁぼ defevent :worldon_favorite, prototype: [PM::World, PM::Status] # ふぁぼる on_worldon_favorite do |world, status| # TODO: guiなどの他plugin向け通知イベントの調査 status_id = PM::API.get_local_status_id(world, status.actual_status) if !status_id.nil? Plugin.call(:before_favorite, world, world.account, status) ret = PM::API.call(:post, world.domain, '/api/v1/statuses/' + status_id.to_s + '/favourite', world.access_token) if ret.nil? || ret[:error] Plugin.call(:fail_favorite, world, world.account, status) else status.actual_status.favourited = true Plugin.call(:favorite, world, world.account, status) end end end defspell(:favorite, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { !status.actual_status.favorite? } # TODO: favorite?の引数にworldを取って正しく判定できるようにする ) do |world, status| Plugin.call(:worldon_favorite, world, status.actual_status) end defspell(:favorited, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { status.actual_status.favorite? } # TODO: worldを使って正しく判定する ) do |world, status| Delayer::Deferred.new.next { status.actual_status.favorite? # TODO: 何を返せばいい? } end # ブーストイベント defevent :worldon_share, prototype: [PM::World, PM::Status] # ブースト on_worldon_share do |world, status| world.reblog(status).next{|shared| Plugin.call(:posted, world, [shared]) Plugin.call(:update, world, [shared]) } end defspell(:share, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { status.rebloggable? } # TODO: rebloggable?の引数にworldを取って正しく判定できるようにする ) do |world, status| world.reblog status end defspell(:shared, :worldon_for_mastodon, :worldon_status, condition: -> (world, status) { status.actual_status.shared? } # TODO: worldを使って正しく判定する ) do |world, status| Delayer::Deferred.new.next { status.actual_status.shared? # TODO: 何を返せばいい? } end end
module RouterFingerprint def load_data() $routers = {} File.read( 'data' ).split("\n").each do |ln| splits = ln.split(',') $routers.store( splits.first, splits.last ) end end end include RouterFingerprint load_data() simple match method require 'digest/md5' module RouterFingerprint def load_data() $routers = {} File.read( 'data' ).split("\n").each do |ln| splits = ln.split(',') $routers.store( splits.first, splits.last ) end end def match( host, port = 80 ) raw_html = `curl -s "http://#{host}:#{port}/"` $routers.key( Digest::MD5.hexdigest( raw_html ) ) end end include RouterFingerprint load_data()
# Load the bundled environment require "rubygems" require "bundler/setup" class Video require_relative 'logging' include Logging require_relative 'exif_thing' # require 'exif' require 'ffprober' require 'time' require 'fileutils' require 'mediainfo' def initialize(videopath, photopath, gmetrix_dir) @videopath = videopath @photopath = photopath @gmetrix_dir = gmetrix_dir end def process if contains_photo? logger.info " found in video #{@videopath}" # Now, we need to find the right GMetrix gmetrix_file_path = nil gmetrix_file_creation_time = Time.new(1980, 1,1,12,0,0) Dir.glob(File.join(@gmetrix_dir, "*.fit")).each do |fit_file_path| creation_time = fit_creation_time(fit_file_path) if creation_time && creation_time < photo_creation_time && creation_time > gmetrix_file_creation_time gmetrix_file_path = fit_file_path gmetrix_file_creation_time = creation_time end end logger.debug "gmetrix_file_path : #{gmetrix_file_path}" # Then, we generate the .srt file if gmetrix_file_path @subtitles_path = FitThing.new(gmetrix_file_path).generate_srt(start_time, output_duration, output_dir) end # Cut the video cut_around if gmetrix_file_path # And we add the subtitles from the .srt file to the video add_subtitles("#{output_path}.MP4") FileUtils.rm "#{output_path}.MP4" FileUtils.mv "subtitled.MP4", "#{output_path}.MP4" end end end def duration video_stream.duration.to_i end private def add_subtitles(video_path) video = escape_path_for_command_line(video_path) subtitles = escape_path_for_command_line(@subtitles_path) flags = "-loglevel error -hide_banner" command = "ffmpeg -i #{video} #{flags} -vf subtitles=#{subtitles}:force_style='Alignment=7' subtitled.MP4" logger.debug "Issuing command: #{command}" system command FileUtils.rm @subtitles_path end # Cuts the current video around the photo def cut_around FileUtils.mkdir_p(output_dir) if !File.exist?("#{output_path}.MP4") logger.info " creating clip..." time_in_video = start_time - video_creation_time time_in_video = 0 if time_in_video < 0 cut_video(@videopath, time_in_video) else logger.warn " clip '#{"#{output_path}.MP4"}' already exists; skipping" end end def cut_video(path, start) video = escape_path_for_command_line(path) output = "#{escape_path_for_command_line(output_path)}.MP4" flags = "-loglevel error -hide_banner" arguments = "-ss #{start} -t #{output_duration}" command = "ffmpeg -i #{video} #{flags} #{arguments} #{output}" logger.debug "Issuing command: #{command}" system command end def probe @probe ||= Ffprober::Parser.from_file(@videopath) end def video_stream probe.video_streams[0] end def video_creation_time # File.birthtime(@videopath) @video_creation_time = @video_creation_time || Time.at(MediaInfo.from(@videopath).video.encoded_date) end def photo_creation_time # File.birthtime(@photopath) @photo_creation_time = @photo_creation_time || ExifThing.new(@photopath).creation_time end def fit_creation_time(fit_file_path) # File.birthtime(fit_file_path) FitThing.new(fit_file_path).creation_time end def contains_photo? if photo_creation_time < video_creation_time return false elsif photo_creation_time > video_creation_time + self.duration.to_i return false else return true end end def output_path @output_path ||= "#{File.join(output_dir, File.basename(@photopath, ".jpg"))}" end def start_time @start_time ||= photo_creation_time - leadtime end def output_duration Settings.duration end def leadtime Settings.leadtime end def output_dir Settings.output_dir end def escape_path_for_command_line(path) output = path.gsub(' ', '\ ') output.gsub!('(', '\(') output.gsub!(')', '\)') output end end # puts Video.new('sample data/VIRB0782-2.MP4', 'sample data/VIRB0784.jpg', 'sample data').creation_time fixed subtitled path # Load the bundled environment require "rubygems" require "bundler/setup" class Video require_relative 'logging' include Logging require_relative 'exif_thing' # require 'exif' require 'ffprober' require 'time' require 'fileutils' require 'mediainfo' def initialize(videopath, photopath, gmetrix_dir) @videopath = videopath @photopath = photopath @gmetrix_dir = gmetrix_dir end def process if contains_photo? logger.info " found in video #{@videopath}" # Now, we need to find the right GMetrix gmetrix_file_path = nil gmetrix_file_creation_time = Time.new(1980, 1,1,12,0,0) Dir.glob(File.join(@gmetrix_dir, "*.fit")).each do |fit_file_path| creation_time = fit_creation_time(fit_file_path) if creation_time && creation_time < photo_creation_time && creation_time > gmetrix_file_creation_time gmetrix_file_path = fit_file_path gmetrix_file_creation_time = creation_time end end logger.debug "gmetrix_file_path : #{gmetrix_file_path}" # Then, we generate the .srt file if gmetrix_file_path @subtitles_path = FitThing.new(gmetrix_file_path).generate_srt(start_time, output_duration, output_dir) end # Cut the video cut_around if gmetrix_file_path # And we add the subtitles from the .srt file to the video add_subtitles("#{output_path}.MP4") FileUtils.rm "#{output_path}.MP4" FileUtils.mv subtitled_path, "#{output_path}.MP4" end end end def duration video_stream.duration.to_i end private def add_subtitles(video_path) video = escape_path_for_command_line(video_path) subtitles = escape_path_for_command_line(@subtitles_path) flags = "-loglevel error -hide_banner" command = "ffmpeg -i #{video} #{flags} -vf subtitles=#{subtitles}:force_style='Alignment=7' #{subtitled_path}" logger.debug "Issuing command: #{command}" system command FileUtils.rm @subtitles_path end # Cuts the current video around the photo def cut_around FileUtils.mkdir_p(output_dir) if !File.exist?("#{output_path}.MP4") logger.info " creating clip..." time_in_video = start_time - video_creation_time time_in_video = 0 if time_in_video < 0 cut_video(@videopath, time_in_video) else logger.warn " clip '#{"#{output_path}.MP4"}' already exists; skipping" end end def cut_video(path, start) video = escape_path_for_command_line(path) output = "#{escape_path_for_command_line(output_path)}.MP4" flags = "-loglevel error -hide_banner" arguments = "-ss #{start} -t #{output_duration}" command = "ffmpeg -i #{video} #{flags} #{arguments} #{output}" logger.debug "Issuing command: #{command}" system command end def probe @probe ||= Ffprober::Parser.from_file(@videopath) end def video_stream probe.video_streams[0] end def video_creation_time # File.birthtime(@videopath) @video_creation_time = @video_creation_time || Time.at(MediaInfo.from(@videopath).video.encoded_date) end def photo_creation_time # File.birthtime(@photopath) @photo_creation_time = @photo_creation_time || ExifThing.new(@photopath).creation_time end def fit_creation_time(fit_file_path) # File.birthtime(fit_file_path) FitThing.new(fit_file_path).creation_time end def contains_photo? if photo_creation_time < video_creation_time return false elsif photo_creation_time > video_creation_time + self.duration.to_i return false else return true end end def output_path @output_path ||= "#{File.join(output_dir, File.basename(@photopath, ".jpg"))}" end def start_time @start_time ||= photo_creation_time - leadtime end def output_duration Settings.duration end def leadtime Settings.leadtime end def output_dir Settings.output_dir end def subtitled_path unless @subtitled_path tmp_dir = File.join(output_dir, 'tmp') FileUtils.mkdir_p(tmp_dir) output_path = File.join(tmp_dir,'subtitled.mp4') end @subtitled_path end def escape_path_for_command_line(path) output = path.gsub(' ', '\ ') output.gsub!('(', '\(') output.gsub!(')', '\)') output end end # puts Video.new('sample data/VIRB0782-2.MP4', 'sample data/VIRB0784.jpg', 'sample data').creation_time
# Picross main program # Version 0.2 require 'observer' require 'json' require 'curb' load './class/bmp.class.rb' load './class/crypt.class.rb' load './class/registre.class.rb' load './class/grille.class.rb' load './class/objetgui.class.rb' load './class/fenetre.class.rb' load './class/button.class.rb' load './class/saisie.class.rb' load './class/text.class.rb' load './class/render.class.rb' # Classe de "haut-niveau" utilise les briques fondamentales # Permet de jouer au Picross class Jeu FAST_GAME = "Partie rapide" ADVENTURE = "Aventure" QUIT = "Quitter" BACK = "Retour" URL_FETCH = "http://hop3x.univ-lemans.fr/picross/levels.json" def initialize() @kRender = Render::Game.new @kRender.game_scenes.add_observer(self) #Pattern Observable @kRegistre = Registre.creer("picross-b.db") @currentGame = nil @kMainMenu = Fenetre.creer("Menu principal", 0, 0, 0, 640, 480) @kInGame = Fenetre.creer("Jeu", 0, 0, 0, 640, 480) @kAbout = Fenetre.creer("À propos", 0, 0, 0, 640, 480) @kMessage = Fenetre.creer("Information(s)", 0, 0, 0, 640, 480) @nombreErreurs = 10 # Récupère les statistiques du disque local getStats # Si on ne dispose d'aucun niveau, on install ceux présent sur le disque install if @nLevel == nil || @nLevel == 0 puts "Programme chargée avec #{@nLevel} niveau(x).." #@kMainMenu.ajouterComposant(Audio.creer("Env", "ressources/son/BackgroundMusicLoop/BackgroundMusicLoop_BPM100.wav", true, 1, 1, 0, 0, 0)) end def fetchOnline request = Curl.get(URL_FETCH) return false if request.status != "200 OK" || request.status != "301 OK" return request.body_str end def getStats # Récupération des données @lastLevel = @kRegistre.getValue("lastLevel") || "1" @coins = @kRegistre.getValue("coins") || "0" @nTry = @kRegistre.getValue("try") || "0" @nWin = @kRegistre.getValue("win") || "0" @nLevel = @kRegistre.getValue("nbLevels") || "0" # Convertir vers fixnum @lastLevel = @lastLevel.to_i if @lastLevel != nil @coins = @coins.to_i if @coins != nil @nTry = @nTry.to_i if @nTry != nil @nWin = @nWin.to_i if @nWin != nil @nLevel = @nLevel.to_i if @nLevel != nil end def sauvegarde @kRegistre.addParam("sauvegarde-mat", @currentGame.matriceDeJeu.to_json) @kRegistre.addParam("sauvegarde-err", @currentGame.nbErreur.to_s) end def reprendre matriceJeu = @kRegistre.getValue("sauvegarde-mat") nbErreur = @kRegistre.getValue("sauvegarde-err") if (matriceJeu != nil && nbErreur != nil) @kRegistre.deleteParam("sauvegarde-err") @kRegistre.deleteParam("sauvegarde-mat") @nombreErreurs = nbErreur.to_i return JSON.load(matriceJeu) else return nil end end # Ajout une tentative dans statistiques def addTry @nTry += 1 @kRegistre.updateParam("try", @nTry.to_s) end # Ajout une victoire dans statistiques def addWin @nWin += 1 @lastLevel += 1 @kRegistre.updateParam("win", @nWin.to_s) @kRegistre.updateParam("lastLevel", @lastLevel.to_s) end # Ajout de l'argent dans statistiques def addCoin(unNombreGems) @coins+=unNombreGems @kRegistre.updateParam("coins", @coins.to_s) end # Récupére la matrice du dernier niveau def getMatrice @lastLevel = 1 if @lastLevel == nil JSON.load(@kRegistre.getValue("level_#{@lastLevel}")) end # Installation des niveaux présent sur le disque (local) def install onlineLevels = fetchOnline uneListeNiveau = Dir["ressources/images/imagesPicross/BMP24bitsRVB/*.bmp"].sort i = 1 if onlineLevels != false # Si les niveaux sont disponible en ligne puts "Installation des niveaux depuis le serveur distant.." arrayLevels = JSON.load(onlineLevels) arrayLevels.each do |level| @kRegistre.addParam("level_#{i}", level.to_json) i+=1 end else # Récupération hors ligne puts "Installation des niveaux depuis le disque local.. (hors ligne)" uneListeNiveau.each do |unNiveau| @kRegistre.addParam("level_#{i}", BMP::Reader.creer(unNiveau).getMatrice.to_json) i+=1 end end # On sauvegarde le nombre de niveau chargé @nLevel = i @kRegistre.addParam("nbLevels", i.to_s) @kRegistre.addParam("coins", "0") @kRegistre.addParam("try", "0") @kRegistre.addParam("win", "0") @kRegistre.addParam("lastLevel", "1") end # Prépare la boite pour affichage statistiques def addStatBox(unContexteCible) stat_support = Image.creer("Stat-background", "ressources/images/GUI/box/boxNormal.png", 480, 20, 1) libell_coins = Text.creer("coins", "Gems : #{@coins||0}", 10, 500, 50, 2) libell_try = Text.creer("try", "Essai : #{@nTry||0}", 10, 500, 60, 2) libell_win = Text.creer("win", "Victoire: #{@nWin||0}", 10, 500, 70, 2) libell_avancement = Text.creer("avancement", "Niveau: #{@lastLevel||0}/#{@nLevel||0}", 10, 500, 80, 2) unContexteCible.ajouterComposant(stat_support, libell_coins, libell_try, libell_win, libell_avancement) end def initializeMessage(unMessage) @kMessage.supprimeTout # Image de fond background = Image.creer("Background", "ressources/images/GUI/Prototypes/background-6.png", 0, 0, 0) # Information sur version libell_alpha = Text.creer("beta-1", "beta-preview 1", 15, 100, 120, 1) # Placement du titre libell_title = Text.creer("title", "Picross B", 50, 100, 100, 1) libell_title.setPolice "ressources/ttf/Starjedi.ttf" #Police d'écriture spéciale pour le titre libell_message = Text.creer("message", unMessage, 20, 100, 230, 1) btn_ok = Boutton.creer("OK", 50, 400, 1, 0, 0) addStatBox @kMessage @kMessage.ajouterComposant background, libell_alpha, libell_title, libell_message, btn_ok end # Préparation de la fenêtre À propos def initializeAbout @kAbout.supprimeTout # Image de fond background = Image.creer("Background", "ressources/images/GUI/Prototypes/background-6.png", 0, 0, 0) # Information sur version libell_alpha = Text.creer("beta-1", "beta-preview 1", 15, 100, 120, 1) # Placement du titre libell_title = Text.creer("title", "Picross B", 50, 100, 100, 1) libell_title.setPolice "ressources/ttf/Starjedi.ttf" #Police d'écriture spéciale pour le titre libell_line1 = Text.creer("about_1", "Jeu de Picross Grpe B", 12, 100, 200, 1) libell_line2 = Text.creer("about_2", "Projet de semestre 6 en L3 SPI", 12, 100, 215, 1) libell_line3 = Text.creer("about_3", "Moteur Jeu: Houssam",12, 100, 230, 1) libell_line4 = Text.creer("about_4", "RenduGL: Ahmed", 12, 100, 245, 1) libell_line5 = Text.creer("about_5", "Registre: Victorien, Ahmed",12, 100, 260, 1) libell_line6 = Text.creer("about_6", "Cryptage: Baptiste", 12,100, 275, 1) libell_line7 = Text.creer("about_7", "TDA GUI: Antoine, Ahmed",12, 100, 290, 1) libell_line8 = Text.creer("about_8", "BMP: Marius",12, 100, 305, 1) libell_line9 = Text.creer("about_9", "Recherches: Matthis",12, 100, 320, 1) btn_quit = Boutton.creer("Retour", 50, 400, 1, 0, 0) addStatBox @kAbout @kAbout.ajouterComposant background, libell_alpha, libell_title, libell_line1, libell_line2, libell_line3, libell_line4, libell_line5, libell_line6, libell_line7, libell_line8, libell_line9, btn_quit end # Préparation du menu principal def initializeMainMenu() @kMainMenu.supprimeTout # Image de fond background = Image.creer("Background", "ressources/images/GUI/Prototypes/background-5.png", 0, 0, 0) # Information sur version libell_alpha = Text.creer("beta-1", "beta-preview 1", 15, 250, 170, 1) # Statistique addStatBox @kMainMenu # Placement du titre libell_title = Text.creer("title", "Picross B", 50, 250, 150, 1) libell_title.setPolice "ressources/ttf/Starjedi.ttf" #Police d'écriture spéciale pour le titre # Création des boutons btn_aventure = Boutton.creer("Aventure", 40, 50, 1, 0, 0) btn_newGame = Boutton.creer("Partie rapide", 40, 100, 1, 0, 0) btn_params = Boutton.creer("Parametres", 40, 150, 1, 0, 0) btn_about = Boutton.creer("À propos", 40, 200, 1, 0, 0) btn_quit = Boutton.creer("Quitter", 40, 250, 1, 0, 0) # Ajout des composants sur la fenêtre primaire @kMainMenu.ajouterComposant(background, libell_alpha, libell_title ,btn_aventure, btn_newGame, btn_params,btn_about ,btn_quit) end # Préparation du jeu "rapide" def initializeGame @kInGame.supprimeTout background = Image.creer("Background", "ressources/maps/Couloirs-Resized.png", 0, 0, 0) libell_niveau = Text.creer("niveau", "Niveau #{@lastLevel}", 19, 50, 40, 1) libell_niveau.setPolice "ressources/ttf/Starjedi.ttf" # Statistique addStatBox @kInGame myMat = getMatrice @currentGame = Grille.grille(myMat) repriseData = reprendre if repriseData != nil @currentGame.restorer repriseData else addTry # Ajout +1 aux essai (statistiques) end support_grille = Image.creer("Grille", "ressources/images/Grilles/v3/g#{myMat.length}x#{myMat.length}.png", 120, 120, 1) btn_quit = Boutton.creer("Abandonner", 50, 430, 1, 0, 0) btn_help = Boutton.creer("Aide", 150, 430, 1, 0, 0) btn_save = Boutton.creer("Sauvegarder", 250, 430, 1, 0, 0) @kInGame.ajouterComposant(background, libell_niveau, support_grille) # On place des élements "case" pour grille inHautPosX = 244 inHautPosY = 245 (1..myMat.length).step(1) do |n| (1..myMat.length).step(1) do |j| spriteCase = Sprite.creer("case", "ressources/images/Grilles/Cases.png", 8, 1, inHautPosX, inHautPosY, 2, 0, 0) spriteCase.arr_data = [n, j] if repriseData != nil && repriseData[n-1][j-1] == 1 spriteCase.deplacer 2, 0 else spriteCase.deplacer 1, 0 end @kInGame.ajouterComposant(spriteCase) inHautPosX += 16 end inHautPosX = 244 inHautPosY += 16 end # Positionnement des indices Haut inHautPosX = 250 inHautPosY = 120 @currentGame.indicesHaut.each do |indice| indice.each do |nb| @kInGame.ajouterComposant(Text.creer("ind-#{inHautPosX}-#{inHautPosY}", "#{nb}", 15, inHautPosX, inHautPosY, 2)) inHautPosY += 16 end inHautPosX += 16 inHautPosY = 120 end # Positionnement des indices Coté inHautPosX = 120 inHautPosY = 240 @currentGame.indicesCote.each do |indice| indice.each do |nb| @kInGame.ajouterComposant(Text.creer("ind-#{inHautPosX}-#{inHautPosY}", "#{nb}", 15, inHautPosX, inHautPosY, 2)) inHautPosX += 16 end inHautPosY += 16 inHautPosX = 120 end # Ajout des sprites pour case noir et blanche @kInGame.ajouterComposant(btn_quit, btn_help, btn_save) end # Lance le jeu avec le menu principal def lanceToi initializeMainMenu #Préparation du menu principal @kRender.prepare @kMainMenu #Rendu des objets end def actionOnMessage(unTypeEvenement, unComposantCible, unTexteEntree=nil) return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == "OK") initializeMainMenu @kRender.prepare @kMainMenu end end # Gestion des actions sur le menu principal def actionOnMenu(unTypeEvenement, unComposantCible, unTexteEntree=nil) # Gestion des événements sur menu principal return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == FAST_GAME) #Si le joueur clique sur "Partie rapide" #On charge le plateau initializeGame #On recharge le rendu @kRender.end_scene @kInGame elsif (btn_cible_libell == "Quitter") #On met fin au programme exit elsif (btn_cible_libell == "À propos") #On charge la fenêtre à propos initializeAbout @kRender.end_scene @kAbout elsif (btn_cible_libell == "Aventure") initializeMessage "Désolé, le mode aventure à été désactivée!" @kRender.end_scene @kMessage end end # Gestion des actions sur le plateau de jeu def actionOnGame(unTypeEvenement, unComposantCible, unTexteEntree=nil) # Gestion des événements sur menu principal return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == "Abandonner") #Si le joueur clique sur "Retour" depuis la séance de jeu #On charge le menu principal initializeMainMenu #On recharge le rendu @kRender.end_scene @kMainMenu elsif (unComposantCible.designation == "case" && unComposantCible.arr_data != [-1, -1]) # On tente de noirsir la case if @currentGame.noirsirCase unComposantCible.arr_data[0], unComposantCible.arr_data[1] @kRender.game_scenes.animateSprite unComposantCible @kRender.game_scenes.instantSound "ressources/son/pop.wav" else @kRender.game_scenes.instantSound "ressources/son/beep.wav" end # On vérifie que l'état de la partie if @currentGame.terminer? #On ajoute une victoire addWin addCoin @currentGame.calculeScore initializeMessage "Vous avez réussi à résoudre la grille niveau n°#{@lastLevel-1} !" @kRender.end_scene @kMessage end elsif (btn_cible_libell == "Aide") #On vérifie que le joueur a suffisament de credit if (@coins > 100*@lastLevel) caseCible = @currentGame.demanderAide if (caseCible != [-1, -1]) @currentGame.noirsirCase caseCible[0], caseCible[1] @kRender.game_scenes.instantSound "ressources/son/pop.wav" end end elsif (btn_cible_libell == "Quitter") #On met fin au programme exit elsif (btn_cible_libell == "Sauvegarder") #On sauvegarde l'état de la partie if sauvegarde initializeMessage "La partie a été sauvegardée avec succès, à bientôt!" @kRender.end_scene @kMessage else initializeMessage "Une erreur est survenue lors de la sauvegarde" @kRender.end_scene @kMessage end end end # Gestion des événements sur fenêtre À propos def actionOnAbout(unTypeEvenement, unComposantCible, unTexteEntree=nil) # Gestion des événements sur menu principal return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == "Retour") initializeMainMenu @kRender.end_scene @kMainMenu end end # Méthode de reception signal pour pattern observateur def update(unTypeEvenement, unComposantCible, unTexteEntree=nil) #puts "Attention: Evenement Trigger #{unComposantCible.designation} sur typeEvenement = #{unTypeEvenement} avec contexte = #{@kRender.getContext.designation}" #On redirige vers la méthode concernée if @kRender.getContext.designation == "Menu principal" actionOnMenu unTypeEvenement, unComposantCible elsif @kRender.getContext.designation == "Jeu" actionOnGame unTypeEvenement, unComposantCible elsif @kRender.getContext.designation == "À propos" actionOnAbout unTypeEvenement, unComposantCible elsif @kRender.getContext.designation == "Information(s)" actionOnMessage unTypeEvenement, unComposantCible end end private :addWin, :addTry, :addCoin, :initializeMainMenu, :initializeMessage, :initializeGame, :initializeAbout, :actionOnMessage, :actionOnAbout, :actionOnMessage, :actionOnGame, :actionOnMenu, :sauvegarde, :reprendre end #Lancement #puts OpenSSL::Cipher.ciphers kJeu = Jeu.new kJeu.lanceToi Améliorations diverses # Picross main program # Version 0.2 require 'observer' require 'json' require 'curb' load './class/bmp.class.rb' load './class/crypt.class.rb' load './class/registre.class.rb' load './class/grille.class.rb' load './class/objetgui.class.rb' load './class/fenetre.class.rb' load './class/button.class.rb' load './class/saisie.class.rb' load './class/text.class.rb' load './class/render.class.rb' # Classe de "haut-niveau" utilise les briques fondamentales # Permet de jouer au Picross class Jeu FAST_GAME = "Partie rapide" ADVENTURE = "Aventure" QUIT = "Quitter" BACK = "Retour" URL_FETCH = "http://hop3x.univ-lemans.fr/picross/levels.json" def initialize() @kRender = Render::Game.new @kRender.game_scenes.add_observer(self) #Pattern Observable @kRegistre = Registre.creer("picross-b.db") @currentGame = nil @kMainMenu = Fenetre.creer("Menu principal", 0, 0, 0, 640, 480) @kInGame = Fenetre.creer("Jeu", 0, 0, 0, 640, 480) @kAbout = Fenetre.creer("À propos", 0, 0, 0, 640, 480) @kMessage = Fenetre.creer("Information(s)", 0, 0, 0, 640, 480) @nombreErreurs = 10 # Récupère les statistiques du disque local getStats # Si on ne dispose d'aucun niveau, on install ceux présent sur le disque install if @nLevel == nil || @nLevel == 0 puts "Programme chargée avec #{@nLevel} niveau(x).." #@kMainMenu.ajouterComposant(Audio.creer("Env", "ressources/son/BackgroundMusicLoop/BackgroundMusicLoop_BPM100.wav", true, 1, 1, 0, 0, 0)) end def fetchOnline request = Curl.get(URL_FETCH) return false if request.status != "200 OK" || request.status != "301 OK" return request.body_str end def getStats # Récupération des données @lastLevel = @kRegistre.getValue("lastLevel") || "1" @coins = @kRegistre.getValue("coins") || "0" @nTry = @kRegistre.getValue("try") || "0" @nWin = @kRegistre.getValue("win") || "0" @nLevel = @kRegistre.getValue("nbLevels") || "0" # Convertir vers fixnum @lastLevel = @lastLevel.to_i if @lastLevel != nil @coins = @coins.to_i if @coins != nil @nTry = @nTry.to_i if @nTry != nil @nWin = @nWin.to_i if @nWin != nil @nLevel = @nLevel.to_i if @nLevel != nil end def sauvegarde @kRegistre.addParam("sauvegarde-mat", @currentGame.matriceDeJeu.to_json) @kRegistre.addParam("sauvegarde-err", @currentGame.nbErreur.to_s) end def reprendre matriceJeu = @kRegistre.getValue("sauvegarde-mat") nbErreur = @kRegistre.getValue("sauvegarde-err") if (matriceJeu != nil && nbErreur != nil) @kRegistre.deleteParam("sauvegarde-err") @kRegistre.deleteParam("sauvegarde-mat") @nombreErreurs = nbErreur.to_i return JSON.load(matriceJeu) else return nil end end # Ajout une tentative dans statistiques def addTry @nTry += 1 @kRegistre.updateParam("try", @nTry.to_s) end # Ajout une victoire dans statistiques def addWin @nWin += 1 @lastLevel += 1 @kRegistre.updateParam("win", @nWin.to_s) @kRegistre.updateParam("lastLevel", @lastLevel.to_s) end # Ajout de l'argent dans statistiques def addCoin(unNombreGems) @coins+=unNombreGems @kRegistre.updateParam("coins", @coins.to_s) end # Récupére la matrice du dernier niveau def getMatrice @lastLevel = 1 if @lastLevel == nil JSON.load(@kRegistre.getValue("level_#{@lastLevel}")) end # Installation des niveaux présent sur le disque (local) def install onlineLevels = fetchOnline uneListeNiveau = Dir["ressources/images/imagesPicross/BMP24bitsRVB/*.bmp"].sort i = 1 if onlineLevels != false # Si les niveaux sont disponible en ligne puts "Installation des niveaux depuis le serveur distant.." arrayLevels = JSON.load(onlineLevels) arrayLevels.each do |level| @kRegistre.addParam("level_#{i}", level.to_json) i+=1 end else # Récupération hors ligne puts "Installation des niveaux depuis le disque local.. (hors ligne)" uneListeNiveau.each do |unNiveau| @kRegistre.addParam("level_#{i}", BMP::Reader.creer(unNiveau).getMatrice.to_json) i+=1 end end # On sauvegarde le nombre de niveau chargé @nLevel = i @kRegistre.addParam("nbLevels", i.to_s) @kRegistre.addParam("coins", "0") @kRegistre.addParam("try", "0") @kRegistre.addParam("win", "0") @kRegistre.addParam("lastLevel", "1") end # Prépare la boite pour affichage statistiques def addStatBox(unContexteCible) stat_support = Image.creer("Stat-background", "ressources/images/GUI/box/boxNormal.png", 480, 20, 1) libell_coins = Text.creer("coins", "Gems : #{@coins||0}", 10, 500, 50, 2) libell_try = Text.creer("try", "Essai : #{@nTry||0}", 10, 500, 60, 2) libell_win = Text.creer("win", "Victoire: #{@nWin||0}", 10, 500, 70, 2) libell_avancement = Text.creer("avancement", "Niveau: #{@lastLevel||0}/#{@nLevel||0}", 10, 500, 80, 2) unContexteCible.ajouterComposant(stat_support, libell_coins, libell_try, libell_win, libell_avancement) end def initializeMessage(unMessage) @kMessage.supprimeTout # Image de fond background = Image.creer("Background", "ressources/images/GUI/Prototypes/background-6.png", 0, 0, 0) # Information sur version libell_alpha = Text.creer("beta-1", "beta-preview 1", 15, 100, 120, 1) # Placement du titre libell_title = Text.creer("title", "Picross B", 50, 100, 100, 1) libell_title.setPolice "ressources/ttf/Starjedi.ttf" #Police d'écriture spéciale pour le titre libell_message = Text.creer("message", unMessage, 20, 100, 230, 1) btn_ok = Boutton.creer("OK", 50, 400, 1, 0, 0) addStatBox @kMessage @kMessage.ajouterComposant background, libell_alpha, libell_title, libell_message, btn_ok end # Préparation de la fenêtre À propos def initializeAbout @kAbout.supprimeTout # Image de fond background = Image.creer("Background", "ressources/images/GUI/Prototypes/background-6.png", 0, 0, 0) # Information sur version libell_alpha = Text.creer("beta-1", "beta-preview 1", 15, 100, 120, 1) # Placement du titre libell_title = Text.creer("title", "Picross B", 50, 100, 100, 1) libell_title.setPolice "ressources/ttf/Starjedi.ttf" #Police d'écriture spéciale pour le titre libell_line1 = Text.creer("about_1", "Jeu de Picross Grpe B", 12, 100, 200, 1) libell_line2 = Text.creer("about_2", "Projet de semestre 6 en L3 SPI", 12, 100, 215, 1) libell_line3 = Text.creer("about_3", "Moteur Jeu: Houssam",12, 100, 230, 1) libell_line4 = Text.creer("about_4", "RenduGL: Ahmed", 12, 100, 245, 1) libell_line5 = Text.creer("about_5", "Registre: Victorien, Ahmed",12, 100, 260, 1) libell_line6 = Text.creer("about_6", "Cryptage: Baptiste", 12,100, 275, 1) libell_line7 = Text.creer("about_7", "TDA GUI: Antoine, Ahmed",12, 100, 290, 1) libell_line8 = Text.creer("about_8", "BMP: Marius",12, 100, 305, 1) libell_line9 = Text.creer("about_9", "Recherches: Matthis",12, 100, 320, 1) btn_quit = Boutton.creer("Retour", 50, 400, 1, 0, 0) addStatBox @kAbout @kAbout.ajouterComposant background, libell_alpha, libell_title, libell_line1, libell_line2, libell_line3, libell_line4, libell_line5, libell_line6, libell_line7, libell_line8, libell_line9, btn_quit end # Préparation du menu principal def initializeMainMenu() @kMainMenu.supprimeTout # Image de fond background = Image.creer("Background", "ressources/images/GUI/Prototypes/background-5.png", 0, 0, 0) # Information sur version libell_alpha = Text.creer("beta-1", "beta-preview 1", 15, 250, 170, 1) # Statistique addStatBox @kMainMenu # Placement du titre libell_title = Text.creer("title", "Picross B", 50, 250, 150, 1) libell_title.setPolice "ressources/ttf/Starjedi.ttf" #Police d'écriture spéciale pour le titre # Création des boutons btn_aventure = Boutton.creer("Aventure", 40, 50, 1, 0, 0) btn_newGame = Boutton.creer("Partie rapide", 40, 100, 1, 0, 0) btn_params = Boutton.creer("Parametres", 40, 150, 1, 0, 0) btn_about = Boutton.creer("À propos", 40, 200, 1, 0, 0) btn_quit = Boutton.creer("Quitter", 40, 250, 1, 0, 0) # Ajout des composants sur la fenêtre primaire @kMainMenu.ajouterComposant(background, libell_alpha, libell_title ,btn_aventure, btn_newGame, btn_params,btn_about ,btn_quit) end # Préparation du jeu "rapide" def initializeGame @kInGame.supprimeTout background = Image.creer("Background", "ressources/maps/Couloirs-Resized.png", 0, 0, 0) libell_niveau = Text.creer("niveau", "Niveau #{@lastLevel}", 19, 50, 40, 1) libell_niveau.setPolice "ressources/ttf/Starjedi.ttf" # Statistique addStatBox @kInGame myMat = getMatrice @currentGame = Grille.grille(myMat) repriseData = reprendre if repriseData != nil @currentGame.restorer repriseData else addTry # Ajout +1 aux essai (statistiques) @nombreErreurs = 10 end libell_erreur = Text.creer("essais", "Essai(s): #{@nombreErreurs} restant(s)", 15, 50, 90, 1) support_grille = Image.creer("Grille", "ressources/images/Grilles/v3/g#{myMat.length}x#{myMat.length}.png", 120, 120, 1) btn_quit = Boutton.creer("Abandonner", 50, 430, 1, 0, 0) btn_help = Boutton.creer("Aide", 150, 430, 1, 0, 0) btn_save = Boutton.creer("Sauvegarder", 250, 430, 1, 0, 0) @kInGame.ajouterComposant(background, libell_niveau, libell_erreur, support_grille) # On place des élements "case" pour grille inHautPosX = 244 inHautPosY = 245 (1..myMat.length).step(1) do |n| (1..myMat.length).step(1) do |j| spriteCase = Sprite.creer("case", "ressources/images/Grilles/Cases.png", 8, 1, inHautPosX, inHautPosY, 2, 0, 0) spriteCase.arr_data = [n, j] if repriseData != nil && repriseData[n-1][j-1] == 1 spriteCase.deplacer 2, 0 else spriteCase.deplacer 1, 0 end @kInGame.ajouterComposant(spriteCase) inHautPosX += 16 end inHautPosX = 244 inHautPosY += 16 end # Positionnement des indices Haut inHautPosX = 250 inHautPosY = 120 @currentGame.indicesHaut.each do |indice| indice.each do |nb| @kInGame.ajouterComposant(Text.creer("ind-#{inHautPosX}-#{inHautPosY}", "#{nb}", 15, inHautPosX, inHautPosY, 2)) inHautPosY += 16 end inHautPosX += 16 inHautPosY = 120 end # Positionnement des indices Coté inHautPosX = 120 inHautPosY = 240 @currentGame.indicesCote.each do |indice| indice.each do |nb| @kInGame.ajouterComposant(Text.creer("ind-#{inHautPosX}-#{inHautPosY}", "#{nb}", 15, inHautPosX, inHautPosY, 2)) inHautPosX += 16 end inHautPosY += 16 inHautPosX = 120 end # Ajout des sprites pour case noir et blanche @kInGame.ajouterComposant(btn_quit, btn_help, btn_save) end # Lance le jeu avec le menu principal def lanceToi initializeMainMenu #Préparation du menu principal @kRender.prepare @kMainMenu #Rendu des objets end def actionOnMessage(unTypeEvenement, unComposantCible, unTexteEntree=nil) return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == "OK") initializeMainMenu @kRender.prepare @kMainMenu end end # Gestion des actions sur le menu principal def actionOnMenu(unTypeEvenement, unComposantCible, unTexteEntree=nil) # Gestion des événements sur menu principal return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == FAST_GAME) #Si le joueur clique sur "Partie rapide" #On charge le plateau initializeGame #On recharge le rendu @kRender.end_scene @kInGame elsif (btn_cible_libell == "Quitter") #On met fin au programme exit elsif (btn_cible_libell == "À propos") #On charge la fenêtre à propos initializeAbout @kRender.end_scene @kAbout elsif (btn_cible_libell == "Aventure") initializeMessage "Désolé, le mode aventure à été désactivée!" @kRender.end_scene @kMessage end end # Gestion des actions sur le plateau de jeu def actionOnGame(unTypeEvenement, unComposantCible, unTexteEntree=nil) # Gestion des événements sur menu principal return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == "Abandonner") #Si le joueur clique sur "Retour" depuis la séance de jeu #On charge le menu principal initializeMainMenu #On recharge le rendu @kRender.end_scene @kMainMenu elsif (unComposantCible.designation == "case" && unComposantCible.arr_data != [-1, -1]) # On tente de noirsir la case if @currentGame.noirsirCase unComposantCible.arr_data[0], unComposantCible.arr_data[1] @kRender.game_scenes.animateSprite unComposantCible @kRender.game_scenes.instantSound "ressources/son/pop.wav" else @kRender.game_scenes.instantSound "ressources/son/beep.wav" @nombreErreurs -= 1 if @nombreErreurs == 0 initializeMessage "Vous avez perdu, votre nombre de tentative est écoulée!" @kRender.end_scene @kMessage else nouveauLibellEssais = @kRender.game_scenes.getVertexIDFromName("essais") nouveauLibellEssais.contenu = "Essai(s): #{@nombreErreurs} restant(s)" @kRender.game_scenes.updateComposant nouveauLibellEssais end end # On vérifie que l'état de la partie if @currentGame.terminer? #On ajoute une victoire addWin addCoin @currentGame.calculeScore initializeMessage "Vous avez réussi à résoudre la grille niveau n°#{@lastLevel-1} ! (+ #{@currentGame.calculeScore} Gems)" @kRender.end_scene @kMessage end elsif (btn_cible_libell == "Aide") #On vérifie que le joueur a suffisament de credit if (@coins > 100*@lastLevel) caseCible = @currentGame.demanderAide if (caseCible != [-1, -1]) @currentGame.noirsirCase caseCible[0], caseCible[1] @kRender.game_scenes.instantSound "ressources/son/pop.wav" end end elsif (btn_cible_libell == "Quitter") #On met fin au programme exit elsif (btn_cible_libell == "Sauvegarder") #On sauvegarde l'état de la partie if sauvegarde initializeMessage "La partie a été sauvegardée avec succès, à bientôt!" @kRender.end_scene @kMessage else initializeMessage "Une erreur est survenue lors de la sauvegarde" @kRender.end_scene @kMessage end end end # Gestion des événements sur fenêtre À propos def actionOnAbout(unTypeEvenement, unComposantCible, unTexteEntree=nil) # Gestion des événements sur menu principal return if unTypeEvenement != 1 # On ne recherche que le clique souris btn_cible_libell = unComposantCible.designation if (btn_cible_libell == "Retour") initializeMainMenu @kRender.end_scene @kMainMenu end end # Méthode de reception signal pour pattern observateur def update(unTypeEvenement, unComposantCible, unTexteEntree=nil) #puts "Attention: Evenement Trigger #{unComposantCible.designation} sur typeEvenement = #{unTypeEvenement} avec contexte = #{@kRender.getContext.designation}" #On redirige vers la méthode concernée if @kRender.getContext.designation == "Menu principal" actionOnMenu unTypeEvenement, unComposantCible elsif @kRender.getContext.designation == "Jeu" actionOnGame unTypeEvenement, unComposantCible elsif @kRender.getContext.designation == "À propos" actionOnAbout unTypeEvenement, unComposantCible elsif @kRender.getContext.designation == "Information(s)" actionOnMessage unTypeEvenement, unComposantCible end end private :addWin, :addTry, :addCoin, :initializeMainMenu, :initializeMessage, :initializeGame, :initializeAbout, :actionOnMessage, :actionOnAbout, :actionOnMessage, :actionOnGame, :actionOnMenu, :sauvegarde, :reprendre end #Lancement #puts OpenSSL::Cipher.ciphers kJeu = Jeu.new kJeu.lanceToi
5e23a31c-2d48-11e5-b005-7831c1c36510 5e2a2c59-2d48-11e5-b2ab-7831c1c36510 5e2a2c59-2d48-11e5-b2ab-7831c1c36510
76bb2f9c-2d48-11e5-8b36-7831c1c36510 76c3c71c-2d48-11e5-8ef8-7831c1c36510 76c3c71c-2d48-11e5-8ef8-7831c1c36510
require 'sinatra' require 'whois' require 'json' require 'ostruct' require 'digest' require 'yaml' require 'simpleidn' CONFIG = YAML.load_file("config.yml") unless defined? CONFIG set :port => CONFIG['port'], :bind => CONFIG['bind'] set :cache => CONFIG['cache'] class DiskFetcher # Taken from https://developer.yahoo.com/ruby/ruby-cache.html def initialize(cache_dir='/tmp') @cache_dir = cache_dir end def whois(domain, max_age=0) file = Digest::MD5.hexdigest(domain) file_path = File.join("", @cache_dir, file) if File.exists? file_path return File.new(file_path).read if Time.now-File.mtime(file_path)<max_age end @whois = Whois.lookup(domain).to_s.force_encoding('utf-8').encode File.open(file_path, "w") do |data| data << @whois end @whois end end before do response['Access-Control-Allow-Origin'] = '*' end ["/:domain", "/"].each do |path| get path do begin domain = SimpleIDN.to_ascii(params[:domain]) {:result => DiskFetcher.new.whois(domain, settings.cache)}.to_json rescue Exception => e {:error => e}.to_json end end end Refactor ruby code (re)Make DiskFetcher a global method, convert whois() to a function require 'sinatra' require 'whois' require 'json' require 'ostruct' require 'digest' require 'yaml' require 'simpleidn' CONFIG = YAML.load_file("config.yml") unless defined? CONFIG set :port => CONFIG['port'] || 4567 set :bind => CONFIG['bind'] || "0.0.0.0" set :cache => CONFIG['cache'] || 600 class DiskFetcher # Taken from https://developer.yahoo.com/ruby/ruby-cache.html def initialize(cache_dir='/tmp') @cache_dir = cache_dir end def fetch(domain, max_age=0, func) file = Digest::MD5.hexdigest(domain) file_path = File.join("", @cache_dir, file) if File.exists? file_path return File.new(file_path).read if Time.now-File.mtime(file_path)<max_age end result = func.call(domain) File.open(file_path, "w") do |data| data << result end result end end $whois = Proc.new do |domain| Whois.lookup(domain).to_s.force_encoding('utf-8').encode end before do response['Access-Control-Allow-Origin'] = '*' end ["/:domain", "/"].each do |path| get path do begin domain = SimpleIDN.to_ascii(params[:domain]) {:result => DiskFetcher.new.fetch(domain, settings.cache, $whois)}.to_json rescue Exception => e {:error => e}.to_json end end end
require "sinatra" require 'net/http' require "open-uri" require "json" 105020109 API_VERSIONS = { 236 => {'BUILD_ID' => 125103468, 'CC_API_VERSION' => '2.55.0'}, 235 => {'BUILD_ID' => 123491350, 'CC_API_VERSION' => '2.54.0'}, 234 => {'BUILD_ID' => 121031369, 'CC_API_VERSION' => '2.53.0'}, 233 => {'BUILD_ID' => 116758428, 'CC_API_VERSION' => '2.52.0'}, 232 => {'BUILD_ID' => 115991017, 'CC_API_VERSION' => '2.52.0'}, 231 => {'BUILD_ID' => 110284023, 'CC_API_VERSION' => '2.51.0'}, 230 => {'BUILD_ID' => 105020109, 'CC_API_VERSION' => '2.48.0'}, 229 => {'BUILD_ID' => 103428675, 'CC_API_VERSION' => '2.47.0'}, 228 => {'BUILD_ID' => 102155078, 'CC_API_VERSION' => '2.47.0'}, 227 => {'BUILD_ID' => 98370576, 'CC_API_VERSION' => '2.46.0'}, 226 => {'BUILD_ID' => 94057175, 'CC_API_VERSION' => '2.44.0'}, 225 => {'BUILD_ID' => 90981793, 'CC_API_VERSION' => '2.43.0'}, 224 => {'BUILD_ID' => 88916778, 'CC_API_VERSION' => '2.42.0'}, 223 => {'BUILD_ID' => 88916778, 'CC_API_VERSION' => '2.42.0'}, 222 => {'BUILD_ID' => 85641576, 'CC_API_VERSION' => '2.41.0'}, 221 => {'BUILD_ID' => 85167498, 'CC_API_VERSION' => '2.40.0'}, 220 => {'BUILD_ID' => 84006459, 'CC_API_VERSION' => '2.39.0'}, 219 => {'BUILD_ID' => 83029259, 'CC_API_VERSION' => '2.37.0'}, 218 => {'BUILD_ID' => 79900811, 'CC_API_VERSION' => '2.36.0'}, 217 => {'BUILD_ID' => 78125812, 'CC_API_VERSION' => '2.35.0'}, 215 => {'BUILD_ID' => 74335342, 'CC_API_VERSION' => '2.34.0'}, 214 => {'BUILD_ID' => 72920095, 'CC_API_VERSION' => '2.33.0'}, 213 => {'BUILD_ID' => 69811325, 'CC_API_VERSION' => '2.33.0'}, 212 => {'BUILD_ID' => 67117720, 'CC_API_VERSION' => '2.29.0'}, 211 => {'BUILD_ID' => 65314847, 'CC_API_VERSION' => '2.28.0'}, 210 => {'BUILD_ID' => 63419982, 'CC_API_VERSION' => '2.27.0'}, 209 => {'BUILD_ID' => 62731063, 'CC_API_VERSION' => '2.27.0'}, 208 => {'BUILD_ID' => 61698265, 'CC_API_VERSION' => '2.25.0'}, 207 => {'BUILD_ID' => 58532799, 'CC_API_VERSION' => '2.25.0'}, 206 => {'BUILD_ID' => 57530258, 'CC_API_VERSION' => '2.24.0'}, 205 => {'BUILD_ID' => 55212903, 'CC_API_VERSION' => '2.23.0'}, 204 => {'BUILD_ID' => 54949372, 'CC_API_VERSION' => '2.23.0'}, 203 => {'BUILD_ID' => 53876287, 'CC_API_VERSION' => '2.23.0'}, 202 => {'BUILD_ID' => 53235349, 'CC_API_VERSION' => '2.22.0'}, 201 => {'BUILD_ID' => 52833659, 'CC_API_VERSION' => '2.22.0'}, 200 => {'BUILD_ID' => 50698978, 'CC_API_VERSION' => '2.22.0'}, 199 => {'BUILD_ID' => 50433011, 'CC_API_VERSION' => '2.22.0'}, 198 => {'BUILD_ID' => 50144686, 'CC_API_VERSION' => '2.22.0'}, 197 => {'BUILD_ID' => 48526348, 'CC_API_VERSION' => '2.21.0'}, 196 => {'BUILD_ID' => 47595973, 'CC_API_VERSION' => '2.21.0'}, 195 => {'BUILD_ID' => 44998082, 'CC_API_VERSION' => '2.19.0'}, 194 => {'BUILD_ID' => 41997426, 'CC_API_VERSION' => '2.18.0'}, 193 => {'BUILD_ID' => 40945705, 'CC_API_VERSION' => '2.18.0'}, 192 => {'BUILD_ID' => 40015178, 'CC_API_VERSION' => '2.17.0'} } def template <<EOS <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <script src='//code.jquery.com/jquery-2.1.3.js'></script> <script src='//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'></script> </head> <body> <%= header %> <%= content %> </body> </html> EOS end def header_template <<EOS <div class="btn-group"> <a class="btn btn-info" href="/<%= current_version %>/"> Home </a> <button type='button' class='btn btn-default dropdown-toggle' data-toggle='dropdown' aria-expanded='false'> <strong>Version </strong> <%= current_version %> <%= current_cc_api_version %> <span class='caret'></span> </button> <ul class='dropdown-menu'> <%= links %> <li class="divider"></li> <%= release_candidate_link %> </ul> </div> <div class="btn-group"> <a class="btn btn-success" href="http://v3-apidocs.cloudfoundry.org/" target="blank">Version 3 - Experimental</a> </div> EOS end def latest_release_num API_VERSIONS.keys.max end get '/' do # Redirect to latest known docs redirect "/#{latest_release_num}/" end get %r{/latest-release(/.*)?} do |docs_path| redirect "/#{latest_release_num}#{docs_path}" end get %r{/release-candidate(/.*)?} do |docs_path| s3_base_url = "https://s3.amazonaws.com/cc-api-docs/release-candidate" docs_path = "/" unless docs_path html_content = fetch_html_from_s3(s3_base_url, docs_path, 'release-candidate') modify_html(html_content, docs_path, 'release-candidate') end get %r{/(\d+)(/.*)?} do |version, docs_path| cf_release_version = version.to_i rescue nil docs_path = "/" unless docs_path travis_build_id = API_VERSIONS[cf_release_version]["BUILD_ID"] s3_base_url = "https://s3.amazonaws.com/cc-api-docs/#{travis_build_id}" html_content = fetch_html_from_s3(s3_base_url, docs_path, cf_release_version) modify_html(html_content, docs_path, cf_release_version) end def fetch_html_from_s3(s3_base_url, docs_path, cf_release_version) docs_path = "/index.html" if docs_path == "/" s3_url = s3_base_url + docs_path begin puts "Fetching artifacts from #{s3_url}" html_content = URI.parse(s3_url).read rescue => e if e.message =~ /not found/i halt 404, erb(template, locals: { header: version_links_html(cf_release_version, API_VERSIONS.keys, docs_path), content: "Not Found" }) end halt 500, 'Error encountered retrieving API docs.' end return html_content end def modify_html(html_content, docs_path, cf_release_version) # change all local HTML links to include cf-release version html_content.gsub!( /\bhref=\"/, "href=\"/#{cf_release_version}/" ) html_body = html_content.gsub(/.*<body>/, '').gsub(/<\/body>.*/, '') locals = { content: html_body, header: version_links_html(cf_release_version, API_VERSIONS.keys, docs_path) } erb template, locals: locals end def version_links_html(current_version, all_versions, current_path) links = all_versions.sort.reverse.map do |version| link_for(version, current_version, current_path) end.join(" ") locals = { links: links, release_candidate_link: link_for('release-candidate', current_version, current_path), current_version: current_version, current_cc_api_version: get_cc_api_version(current_version, true) } erb header_template, locals: locals end def get_cc_api_version(version, bolded = false) return "" unless version.is_a?(Fixnum) num = API_VERSIONS[version.to_i]["CC_API_VERSION"] prefix = bolded ? "<strong>- CC API VERSION</strong>" : "- CC API VERSION" "#{prefix} #{num}" end def link_for(version, current_version, current_path) cc_api_version = get_cc_api_version(version) version == current_version ? "<li><a href='#'> <strong>#{version} #{cc_api_version}</strong> </a></li>" : "<li><a href=\"/#{version}#{current_path}\">#{version} #{cc_api_version}</a></li>" end Bump to CF 237 - CAPI 2.56.0 require "sinatra" require 'net/http' require "open-uri" require "json" 105020109 API_VERSIONS = { 237 => {'BUILD_ID' => 129583505, 'CC_API_VERSION' => '2.56.0'}, 236 => {'BUILD_ID' => 125103468, 'CC_API_VERSION' => '2.55.0'}, 235 => {'BUILD_ID' => 123491350, 'CC_API_VERSION' => '2.54.0'}, 234 => {'BUILD_ID' => 121031369, 'CC_API_VERSION' => '2.53.0'}, 233 => {'BUILD_ID' => 116758428, 'CC_API_VERSION' => '2.52.0'}, 232 => {'BUILD_ID' => 115991017, 'CC_API_VERSION' => '2.52.0'}, 231 => {'BUILD_ID' => 110284023, 'CC_API_VERSION' => '2.51.0'}, 230 => {'BUILD_ID' => 105020109, 'CC_API_VERSION' => '2.48.0'}, 229 => {'BUILD_ID' => 103428675, 'CC_API_VERSION' => '2.47.0'}, 228 => {'BUILD_ID' => 102155078, 'CC_API_VERSION' => '2.47.0'}, 227 => {'BUILD_ID' => 98370576, 'CC_API_VERSION' => '2.46.0'}, 226 => {'BUILD_ID' => 94057175, 'CC_API_VERSION' => '2.44.0'}, 225 => {'BUILD_ID' => 90981793, 'CC_API_VERSION' => '2.43.0'}, 224 => {'BUILD_ID' => 88916778, 'CC_API_VERSION' => '2.42.0'}, 223 => {'BUILD_ID' => 88916778, 'CC_API_VERSION' => '2.42.0'}, 222 => {'BUILD_ID' => 85641576, 'CC_API_VERSION' => '2.41.0'}, 221 => {'BUILD_ID' => 85167498, 'CC_API_VERSION' => '2.40.0'}, 220 => {'BUILD_ID' => 84006459, 'CC_API_VERSION' => '2.39.0'}, 219 => {'BUILD_ID' => 83029259, 'CC_API_VERSION' => '2.37.0'}, 218 => {'BUILD_ID' => 79900811, 'CC_API_VERSION' => '2.36.0'}, 217 => {'BUILD_ID' => 78125812, 'CC_API_VERSION' => '2.35.0'}, 215 => {'BUILD_ID' => 74335342, 'CC_API_VERSION' => '2.34.0'}, 214 => {'BUILD_ID' => 72920095, 'CC_API_VERSION' => '2.33.0'}, 213 => {'BUILD_ID' => 69811325, 'CC_API_VERSION' => '2.33.0'}, 212 => {'BUILD_ID' => 67117720, 'CC_API_VERSION' => '2.29.0'}, 211 => {'BUILD_ID' => 65314847, 'CC_API_VERSION' => '2.28.0'}, 210 => {'BUILD_ID' => 63419982, 'CC_API_VERSION' => '2.27.0'}, 209 => {'BUILD_ID' => 62731063, 'CC_API_VERSION' => '2.27.0'}, 208 => {'BUILD_ID' => 61698265, 'CC_API_VERSION' => '2.25.0'}, 207 => {'BUILD_ID' => 58532799, 'CC_API_VERSION' => '2.25.0'}, 206 => {'BUILD_ID' => 57530258, 'CC_API_VERSION' => '2.24.0'}, 205 => {'BUILD_ID' => 55212903, 'CC_API_VERSION' => '2.23.0'}, 204 => {'BUILD_ID' => 54949372, 'CC_API_VERSION' => '2.23.0'}, 203 => {'BUILD_ID' => 53876287, 'CC_API_VERSION' => '2.23.0'}, 202 => {'BUILD_ID' => 53235349, 'CC_API_VERSION' => '2.22.0'}, 201 => {'BUILD_ID' => 52833659, 'CC_API_VERSION' => '2.22.0'}, 200 => {'BUILD_ID' => 50698978, 'CC_API_VERSION' => '2.22.0'}, 199 => {'BUILD_ID' => 50433011, 'CC_API_VERSION' => '2.22.0'}, 198 => {'BUILD_ID' => 50144686, 'CC_API_VERSION' => '2.22.0'}, 197 => {'BUILD_ID' => 48526348, 'CC_API_VERSION' => '2.21.0'}, 196 => {'BUILD_ID' => 47595973, 'CC_API_VERSION' => '2.21.0'}, 195 => {'BUILD_ID' => 44998082, 'CC_API_VERSION' => '2.19.0'}, 194 => {'BUILD_ID' => 41997426, 'CC_API_VERSION' => '2.18.0'}, 193 => {'BUILD_ID' => 40945705, 'CC_API_VERSION' => '2.18.0'}, 192 => {'BUILD_ID' => 40015178, 'CC_API_VERSION' => '2.17.0'} } def template <<EOS <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <script src='//code.jquery.com/jquery-2.1.3.js'></script> <script src='//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'></script> </head> <body> <%= header %> <%= content %> </body> </html> EOS end def header_template <<EOS <div class="btn-group"> <a class="btn btn-info" href="/<%= current_version %>/"> Home </a> <button type='button' class='btn btn-default dropdown-toggle' data-toggle='dropdown' aria-expanded='false'> <strong>Version </strong> <%= current_version %> <%= current_cc_api_version %> <span class='caret'></span> </button> <ul class='dropdown-menu'> <%= links %> <li class="divider"></li> <%= release_candidate_link %> </ul> </div> <div class="btn-group"> <a class="btn btn-success" href="http://v3-apidocs.cloudfoundry.org/" target="blank">Version 3 - Experimental</a> </div> EOS end def latest_release_num API_VERSIONS.keys.max end get '/' do # Redirect to latest known docs redirect "/#{latest_release_num}/" end get %r{/latest-release(/.*)?} do |docs_path| redirect "/#{latest_release_num}#{docs_path}" end get %r{/release-candidate(/.*)?} do |docs_path| s3_base_url = "https://s3.amazonaws.com/cc-api-docs/release-candidate" docs_path = "/" unless docs_path html_content = fetch_html_from_s3(s3_base_url, docs_path, 'release-candidate') modify_html(html_content, docs_path, 'release-candidate') end get %r{/(\d+)(/.*)?} do |version, docs_path| cf_release_version = version.to_i rescue nil docs_path = "/" unless docs_path travis_build_id = API_VERSIONS[cf_release_version]["BUILD_ID"] s3_base_url = "https://s3.amazonaws.com/cc-api-docs/#{travis_build_id}" html_content = fetch_html_from_s3(s3_base_url, docs_path, cf_release_version) modify_html(html_content, docs_path, cf_release_version) end def fetch_html_from_s3(s3_base_url, docs_path, cf_release_version) docs_path = "/index.html" if docs_path == "/" s3_url = s3_base_url + docs_path begin puts "Fetching artifacts from #{s3_url}" html_content = URI.parse(s3_url).read rescue => e if e.message =~ /not found/i halt 404, erb(template, locals: { header: version_links_html(cf_release_version, API_VERSIONS.keys, docs_path), content: "Not Found" }) end halt 500, 'Error encountered retrieving API docs.' end return html_content end def modify_html(html_content, docs_path, cf_release_version) # change all local HTML links to include cf-release version html_content.gsub!( /\bhref=\"/, "href=\"/#{cf_release_version}/" ) html_body = html_content.gsub(/.*<body>/, '').gsub(/<\/body>.*/, '') locals = { content: html_body, header: version_links_html(cf_release_version, API_VERSIONS.keys, docs_path) } erb template, locals: locals end def version_links_html(current_version, all_versions, current_path) links = all_versions.sort.reverse.map do |version| link_for(version, current_version, current_path) end.join(" ") locals = { links: links, release_candidate_link: link_for('release-candidate', current_version, current_path), current_version: current_version, current_cc_api_version: get_cc_api_version(current_version, true) } erb header_template, locals: locals end def get_cc_api_version(version, bolded = false) return "" unless version.is_a?(Fixnum) num = API_VERSIONS[version.to_i]["CC_API_VERSION"] prefix = bolded ? "<strong>- CC API VERSION</strong>" : "- CC API VERSION" "#{prefix} #{num}" end def link_for(version, current_version, current_path) cc_api_version = get_cc_api_version(version) version == current_version ? "<li><a href='#'> <strong>#{version} #{cc_api_version}</strong> </a></li>" : "<li><a href=\"/#{version}#{current_path}\">#{version} #{cc_api_version}</a></li>" end
4bd9363d-2d48-11e5-b9bd-7831c1c36510 4bde8db3-2d48-11e5-ba63-7831c1c36510 4bde8db3-2d48-11e5-ba63-7831c1c36510
class Expression def self.create(variable_terminals=['x'], depth=0) r = rand if r < 0.33 BinaryExpression.new(variable_terminals, depth) elsif r < 0.67 BinaryExpression.new(variable_terminals, depth) else IfElseExpression.new(variable_terminals, depth) end end def initialize(variable_terminals, depth) @operator = get_operator @operand_1 = get_operand(variable_terminals, depth) end def get_operand(variable_terminals, depth) if rand > (1/(2**depth) + 0.05) op = Terminal.new(variable_terminals) else op = Expression.create(variable_terminals, depth + 1) end return op end end class Terminal def initialize(variable_terminals) if is_variable? @terminal = variable_terminals.sample else @terminal = (10 * rand).round(1) if make_number_negative? @terminal = -1 * @terminal end end end def is_variable? coin_toss_is_heads? end def make_number_negative? coin_toss_is_heads? end def coin_toss_is_heads? rand > 0.5 end def to_s @terminal.to_s end end class IfElseExpression < Expression def initialize(variable_terminals, depth) super @operand_2 = get_operand(variable_terminals, depth) @conditional = ConditionalExpression.new(variable_terminals, depth) end def get_operator end def to_s "( " + @conditional.to_s + " ? " + @operand_1.to_s + " : " + @operand_2.to_s + " )" end end class BinaryExpression < Expression def initialize(variable_terminals, depth) super @operand_2 = get_operand(variable_terminals, depth) end def get_operator ['+', '-', '*', '/', '**'].sample end def to_s "( " + @operand_1.to_s + " " + @operator.to_s + " " + @operand_2.to_s + " )" end end class ConditionalExpression < BinaryExpression def get_operator ['<', '<=', '>', '>='].sample end end class UnaryExpression < Expression def get_operator '-' end def to_s "( " + @operator.to_s + " " + @operand_1.to_s + " )" end end 10.times do e = Expression.create puts e.to_s end rename IfElseExpression to TernaryExpression class Expression def self.create(variable_terminals=['x'], depth=0) r = rand if r < 0.33 BinaryExpression.new(variable_terminals, depth) elsif r < 0.67 BinaryExpression.new(variable_terminals, depth) else TernaryExpression.new(variable_terminals, depth) end end def initialize(variable_terminals, depth) @operator = get_operator @operand_1 = get_operand(variable_terminals, depth) end def get_operand(variable_terminals, depth) if rand > (1/(2**depth) + 0.05) op = Terminal.new(variable_terminals) else op = Expression.create(variable_terminals, depth + 1) end return op end end class Terminal def initialize(variable_terminals) if is_variable? @terminal = variable_terminals.sample else @terminal = (10 * rand).round(1) if make_number_negative? @terminal = -1 * @terminal end end end def is_variable? coin_toss_is_heads? end def make_number_negative? coin_toss_is_heads? end def coin_toss_is_heads? rand > 0.5 end def to_s @terminal.to_s end end class TernaryExpression < Expression def initialize(variable_terminals, depth) super @operand_2 = get_operand(variable_terminals, depth) @conditional = ConditionalExpression.new(variable_terminals, depth) end def get_operator end def to_s "( " + @conditional.to_s + " ? " + @operand_1.to_s + " : " + @operand_2.to_s + " )" end end class BinaryExpression < Expression def initialize(variable_terminals, depth) super @operand_2 = get_operand(variable_terminals, depth) end def get_operator ['+', '-', '*', '/', '**'].sample end def to_s "( " + @operand_1.to_s + " " + @operator.to_s + " " + @operand_2.to_s + " )" end end class ConditionalExpression < BinaryExpression def get_operator ['<', '<=', '>', '>='].sample end end class UnaryExpression < Expression def get_operator '-' end def to_s "( " + @operator.to_s + " " + @operand_1.to_s + " )" end end 10.times do e = Expression.create puts e.to_s end
530ec842-2d48-11e5-af10-7831c1c36510 5316cf9c-2d48-11e5-85be-7831c1c36510 5316cf9c-2d48-11e5-85be-7831c1c36510
require 'json' $main_info = {}; proj_list = Dir['/home/ethan/games/kerbal/CKAN-meta/*'] proj_list.each do |proj| versions = Dir["#{proj}/*.ckan"] versions.each do |v| puts "Reading #{v}" info = JSON.parse(File.read(v)) $main_info[info['identifier']] = info end end puts "Done reading\n\n" $main_info.keys.sort.each do |key| info = $main_info[key] puts "#{info['name']}: #{info['abstract']}" end Switch to parsing Git history to find CKAN files to read require 'json' $main_info = {}; ckan_dir = '/home/ethan/games/kerbal/CKAN-meta' proj_list = Dir['#{ckan_dir}/*'] # sweet! "split" on a string handles blank lines in exactly the way I want :) files = `cd #{ckan_dir}; git log --name-only --format='format:' HEAD~5..HEAD`.split files.each do |f| path = "#{ckan_dir}/#{f}" if File.exists?(path) then puts "Reading #{f}" info = JSON.parse(File.read(path)) $main_info[info['identifier']] = info else puts "No such file #{f}" end end puts "Done reading\n\n" $main_info.keys.sort.each do |key| info = $main_info[key] puts "#{info['name']}: #{info['abstract']}" end
Create main.rb puts "Hello there!!"
70fb21e8-2d48-11e5-a7a8-7831c1c36510 710146a3-2d48-11e5-95f9-7831c1c36510 710146a3-2d48-11e5-95f9-7831c1c36510
5d177a6e-2d48-11e5-8a70-7831c1c36510 5d1dbac7-2d48-11e5-808e-7831c1c36510 5d1dbac7-2d48-11e5-808e-7831c1c36510
4faf37f3-2d48-11e5-8453-7831c1c36510 4fb5621e-2d48-11e5-8170-7831c1c36510 4fb5621e-2d48-11e5-8170-7831c1c36510
#!/usr/bin/ruby -w require 'csv' require 'byebug' oldUserTH = 6*30.4 minMeetupReminder = 3 lastCommTH = 21 ### Calculate the date until next season seasonBegin = Date.parse("2010-04-13") seasonBegin = Date.new(Date.today.year, seasonBegin.month, seasonBegin.day) seasonBegin = Date.new(Date.today.next_year.year, seasonBegin.month, seasonBegin.day) if Date.today >= seasonBegin skipTH = (seasonBegin - Date.today).to_i $stderr.puts "skipTH is #{skipTH} days" ### Function to read line from members CSV file def readTSVline(l) seperator="\t" if ! ENV['sep'].nil? seperator= ENV['sep'] end row = CSV.parse_line(l, :col_sep => seperator).collect{|x| if ! x.nil? x.strip; end } ### Pick specify elements of that table [0, 3, 6, 7, 12, 18, 19, 21].map {|i| row[i]} end ### First let's make sure there is a membershil list if ARGV[0].nil? or ARGV[1].nil? then $stderr.puts "I need the full path of the file as the first argument and shortfall as second argument." exit 1 end filePath=ARGV[0] shortfall=ARGV[1].to_f if ! File.file?(filePath) $stderr.puts "There does not seem to be a file at #{filePath}" exit 1 end ### ... that is recent if Time.now() - File.mtime(filePath) > 24*60*60 $stderr.puts "File is older than 24 hours. May want to get a fresh membership list." exit 1 end ### Parse data for membership list users = [] lineCount=0 File.foreach(filePath) { |l| lineCount += 1 next if lineCount == 1 name, id, lastVisitDate, lastAttendedDate, meetupsAttended, profileURL, lastDonationAmount, lastDonationDate = readTSVline(l) lastDonationDate = Date.parse(lastDonationDate) if lastDonationDate lastVisitDate = Date.parse(lastVisitDate) if meetupsAttended.to_i >= minMeetupReminder and (lastDonationDate.nil? or Date.today - lastDonationDate > 365.25 - 14) users.push({ 'name' => name, 'id' => id, 'lastAttendedDate' => Date.parse(lastAttendedDate), 'lastDonationAmount' => lastDonationAmount, 'lastVisit' => lastVisitDate, 'meetupsAttended' => meetupsAttended.to_i, 'profileURL' => profileURL, 'lastDonationDate' => lastDonationDate, }) end } #users.sort_by! { |hsh| hsh['lastAttendedDate'] } users.sort! { |a,b| chunkA = ((Date.today - a['lastAttendedDate'])/oldUserTH).floor; chunkB = ((Date.today - b['lastAttendedDate'])/oldUserTH).floor; chunkAvisit = ((Date.today - a['lastVisit'])/45).floor; chunkBvisit = ((Date.today - b['lastVisit'])/45).floor; if chunkA == chunkB if chunkA == 0 b['lastAttendedDate'] - a['lastAttendedDate'] else b['lastVisit'] - a['lastVisit'] end elsif chunkA > 0 and chunkB > 0 if chunkAvisit == chunkBvisit b['meetupsAttended'] - a['meetupsAttended'] else chunkAvisit - chunkBvisit #b['lastVisit'] - a['lastVisit'] end else chunkA - chunkB end } #users.reverse! users.each { |u| puts u } #puts users #exit 0 ### Now let's read the communication history file appDir = File.expand_path("~") + '/.meetupAssist/' unless File.directory?(appDir) FileUtils.mkdir_p(appDir) end commHistoryPath = appDir + '/commHistory.txt' usersMsgedLast30days = [] notes = Hash.new skipUsers = [] if File.file?(commHistoryPath) File.foreach(commHistoryPath) { |l| id, lastComm,skip,userNotes = CSV.parse_line(l) lastComm = Date.parse(lastComm) notes[id.to_i] = userNotes if ! userNotes.nil? and ! userNotes.empty? ### Take not of users we have contacted within last 30 days if Date.today - lastComm < lastCommTH usersMsgedLast30days.push(id.to_i) end if skip == 'skip' && Date.today - lastComm < skipTH skipUsers.push(id.to_i) end } end ### Read message file message = File.read(appDir + "reminder.txt") messageOldParticipants = File.read(appDir + "reminderOldParticipants.txt") c = File.open(commHistoryPath, 'a'); ### Go through each users users.each { |u| puts '=' * 72 puts u['profileURL'] puts "Meetups attended: #{u['meetupsAttended']}\tLast meetup attended: #{u['lastAttendedDate']}\tLast site visit: #{u['lastVisit']}" puts "\nNOTES: " + notes[u['id'].to_i] if ! notes[u['id'].to_i].nil? puts ### Skip if contacted in last 30 days if usersMsgedLast30days.include?(u['id'].to_i) puts "Skipping #{u['name']} cause recent communcation" next end if skipUsers.include?(u['id'].to_i) puts "Skip #{u['name']} cause requested skip" next end ### Process users not attending last 30 days msgContent = message lastAttendedDaysAgo = Date.today - u['lastAttendedDate'] if lastAttendedDaysAgo > oldUserTH ### If old user did donate, don't bug them if ! u['lastDonationAmount'].nil? puts "Skipping #{u['name']} cause user visited #{lastAttendedDaysAgo.to_s} days ago (#{u['lastAttendedDate']}), donated #{u['lastDonationAmount']}" next else ### If not, prepare message for old participants msgContent = messageOldParticipants end end ### Shortfall notice shortfallStr = '' if shortfall < 0 shortfallStr = "At the time of this writting, there is a shortfall of #{format("%.2f", shortfall)} $ ." end ### Prepare thank you note thankYouStr = '' if ! u['lastDonationAmount'].nil? thankYouStr = "\nThank you for your doanation of #{u['lastDonationAmount'].sub('USD', '$')} last #{u['lastDonationDate']}.\n" end ### Print message puts puts msgContent.sub('%THANKYOU%', thankYouStr).sub('%NAME%', u['name'].split(' ')[0]).sub('%SHORTFALL%', shortfallStr) puts #byebug ask = TRUE notesIn = '' skip = '' while(ask == TRUE) do notesTH = 5 print "Did you write to #{u['name']}? y/n/q/s/* (string longer than #{notesTH} chars will be stored as a note and you will be prompted again) " yn = $stdin.gets.chomp if yn == 'y' ask = FALSE elsif yn == 'n' ask = FALSE elsif yn == 'q' $stderr.puts "Quitting" ask = FALSE exit 0 elsif yn == 's' skip = 'skip' ask = FALSE elsif yn.length > notesTH notesIn = "\"#{yn}\"" end if yn == 'y' or yn == 's' str = "#{u['id']},#{Date.today.to_s},#{skip},#{notesIn}" $stderr.puts "Adding #{str} to #{commHistoryPath}" c.puts str end end } c.close() #CSV.parse_line(l # CSV.parse_line(l, :col_sep => seperator).collect{|x| # if ! x.nil? # x.strip; # end # } reduced quiet period from 1 year - 2 weeks to 1year - 1 month #!/usr/bin/ruby -w require 'csv' require 'byebug' oldUserTH = 6*30.4 minMeetupReminder = 3 lastCommTH = 21 ### Calculate the date until next season seasonBegin = Date.parse("2010-04-13") seasonBegin = Date.new(Date.today.year, seasonBegin.month, seasonBegin.day) seasonBegin = Date.new(Date.today.next_year.year, seasonBegin.month, seasonBegin.day) if Date.today >= seasonBegin skipTH = (seasonBegin - Date.today).to_i $stderr.puts "skipTH is #{skipTH} days" ### Function to read line from members CSV file def readTSVline(l) seperator="\t" if ! ENV['sep'].nil? seperator= ENV['sep'] end row = CSV.parse_line(l, :col_sep => seperator).collect{|x| if ! x.nil? x.strip; end } ### Pick specify elements of that table [0, 3, 6, 7, 12, 18, 19, 21].map {|i| row[i]} end ### First let's make sure there is a membershil list if ARGV[0].nil? or ARGV[1].nil? then $stderr.puts "I need the full path of the file as the first argument and shortfall as second argument." exit 1 end filePath=ARGV[0] shortfall=ARGV[1].to_f if ! File.file?(filePath) $stderr.puts "There does not seem to be a file at #{filePath}" exit 1 end ### ... that is recent if Time.now() - File.mtime(filePath) > 24*60*60 $stderr.puts "File is older than 24 hours. May want to get a fresh membership list." exit 1 end ### Parse data for membership list users = [] lineCount=0 File.foreach(filePath) { |l| lineCount += 1 next if lineCount == 1 name, id, lastVisitDate, lastAttendedDate, meetupsAttended, profileURL, lastDonationAmount, lastDonationDate = readTSVline(l) lastDonationDate = Date.parse(lastDonationDate) if lastDonationDate lastVisitDate = Date.parse(lastVisitDate) if meetupsAttended.to_i >= minMeetupReminder and (lastDonationDate.nil? or Date.today - lastDonationDate > 365.25 - 30.4) users.push({ 'name' => name, 'id' => id, 'lastAttendedDate' => Date.parse(lastAttendedDate), 'lastDonationAmount' => lastDonationAmount, 'lastVisit' => lastVisitDate, 'meetupsAttended' => meetupsAttended.to_i, 'profileURL' => profileURL, 'lastDonationDate' => lastDonationDate, }) end } #users.sort_by! { |hsh| hsh['lastAttendedDate'] } users.sort! { |a,b| chunkA = ((Date.today - a['lastAttendedDate'])/oldUserTH).floor; chunkB = ((Date.today - b['lastAttendedDate'])/oldUserTH).floor; chunkAvisit = ((Date.today - a['lastVisit'])/45).floor; chunkBvisit = ((Date.today - b['lastVisit'])/45).floor; if chunkA == chunkB if chunkA == 0 b['lastAttendedDate'] - a['lastAttendedDate'] else b['lastVisit'] - a['lastVisit'] end elsif chunkA > 0 and chunkB > 0 if chunkAvisit == chunkBvisit b['meetupsAttended'] - a['meetupsAttended'] else chunkAvisit - chunkBvisit #b['lastVisit'] - a['lastVisit'] end else chunkA - chunkB end } #users.reverse! users.each { |u| puts u } #puts users #exit 0 ### Now let's read the communication history file appDir = File.expand_path("~") + '/.meetupAssist/' unless File.directory?(appDir) FileUtils.mkdir_p(appDir) end commHistoryPath = appDir + '/commHistory.txt' usersMsgedLast30days = [] notes = Hash.new skipUsers = [] if File.file?(commHistoryPath) File.foreach(commHistoryPath) { |l| id, lastComm,skip,userNotes = CSV.parse_line(l) lastComm = Date.parse(lastComm) notes[id.to_i] = userNotes if ! userNotes.nil? and ! userNotes.empty? ### Take not of users we have contacted within last 30 days if Date.today - lastComm < lastCommTH usersMsgedLast30days.push(id.to_i) end if skip == 'skip' && Date.today - lastComm < skipTH skipUsers.push(id.to_i) end } end ### Read message file message = File.read(appDir + "reminder.txt") messageOldParticipants = File.read(appDir + "reminderOldParticipants.txt") c = File.open(commHistoryPath, 'a'); ### Go through each users users.each { |u| puts '=' * 72 puts u['profileURL'] puts "Meetups attended: #{u['meetupsAttended']}\tLast meetup attended: #{u['lastAttendedDate']}\tLast site visit: #{u['lastVisit']}" puts "\nNOTES: " + notes[u['id'].to_i] if ! notes[u['id'].to_i].nil? puts ### Skip if contacted in last 30 days if usersMsgedLast30days.include?(u['id'].to_i) puts "Skipping #{u['name']} cause recent communcation" next end if skipUsers.include?(u['id'].to_i) puts "Skip #{u['name']} cause requested skip" next end ### Process users not attending last 30 days msgContent = message lastAttendedDaysAgo = Date.today - u['lastAttendedDate'] if lastAttendedDaysAgo > oldUserTH ### If old user did donate, don't bug them if ! u['lastDonationAmount'].nil? puts "Skipping #{u['name']} cause user visited #{lastAttendedDaysAgo.to_s} days ago (#{u['lastAttendedDate']}), donated #{u['lastDonationAmount']}" next else ### If not, prepare message for old participants msgContent = messageOldParticipants end end ### Shortfall notice shortfallStr = '' if shortfall < 0 shortfallStr = "At the time of this writting, there is a shortfall of #{format("%.2f", shortfall)} $ ." end ### Prepare thank you note thankYouStr = '' if ! u['lastDonationAmount'].nil? thankYouStr = "\nThank you for your doanation of #{u['lastDonationAmount'].sub('USD', '$')} last #{u['lastDonationDate']}.\n" end ### Print message puts puts msgContent.sub('%THANKYOU%', thankYouStr).sub('%NAME%', u['name'].split(' ')[0]).sub('%SHORTFALL%', shortfallStr) puts #byebug ask = TRUE notesIn = '' skip = '' while(ask == TRUE) do notesTH = 5 print "Did you write to #{u['name']}? y/n/q/s/* (string longer than #{notesTH} chars will be stored as a note and you will be prompted again) " yn = $stdin.gets.chomp if yn == 'y' ask = FALSE elsif yn == 'n' ask = FALSE elsif yn == 'q' $stderr.puts "Quitting" ask = FALSE exit 0 elsif yn == 's' skip = 'skip' ask = FALSE elsif yn.length > notesTH notesIn = "\"#{yn}\"" end if yn == 'y' or yn == 's' str = "#{u['id']},#{Date.today.to_s},#{skip},#{notesIn}" $stderr.puts "Adding #{str} to #{commHistoryPath}" c.puts str end end } c.close() #CSV.parse_line(l # CSV.parse_line(l, :col_sep => seperator).collect{|x| # if ! x.nil? # x.strip; # end # }
#!/bin/ruby require 'gtk3' module ADesktop class MainWindow < Gtk::Window COL_PATH, COL_DISPLAY_NAME, COL_IS_DIR, COL_PIXBUF = (0..3).to_a def find_file(basename) %w(./ /usr/share/gtk-3.0/demo /usr/share/icons/Numix-Circle-Light/scalable/apps/).each do |dirname| path = dirname + basename if File.exist?(path) return path end end return "./gnome-fs-regular.png" end def fill_store @store.clear Dir.glob(File.join(@parent, "*")).each do |path| is_dir = FileTest.directory?(path) icon_px = @file_pixbuf if !is_dir icon_px = @folder_pixbuf if is_dir iter = @store.append path = GLib.filename_to_utf8(path) iter[COL_DISPLAY_NAME] = File.basename(path) iter[COL_PATH] = path iter[COL_IS_DIR] = is_dir iter[COL_PIXBUF] = icon_px end end def initialize() super(:toplevel) set_title("ADesktop") self.signal_connect("destroy") { Gtk.main_quit } self.fullscreen @file_pixbuf = Gdk::Pixbuf.new("gnome-fs-regular.png") @folder_pixbuf = Gdk::Pixbuf.new("gnome-fs-directory.png") @store = Gtk::ListStore.new(String, String, TrueClass, Gdk::Pixbuf) @parent = "/home/aosc/Desktop" @store.set_default_sort_func do |a, b| if !a[COL_IS_DIR] and b[COL_IS_DIR] 1 elsif a[COL_IS_DIR] and !b[COL_IS_DIR] -1 else a[COL_DISPLAY_NAME] <=> b[COL_DISPLAY_NAME] end end @store.set_sort_column_id(Gtk::TreeSortable::DEFAULT_SORT_COLUMN_ID, Gtk::SortType::ASCENDING) fill_store set_border_width(0) box = Gtk::Box.new(:vertical,0) self.add(box) sw = Gtk::ScrolledWindow.new sw.set_policy(:automatic, :automatic) box.pack_end(sw, :expand => true, :fill => true, :padding => 0) iconview = Gtk::IconView.new(@store) iconview.selection_mode = :multiple iconview.text_column = COL_DISPLAY_NAME iconview.pixbuf_column = COL_PIXBUF iconview.signal_connect("item_activated") do |iview, path| iter = @store.get_iter(path) system("xdg-open "+iter[COL_PATH]) end sw.add(iconview) iconview.grab_focus provider = Gtk::CssProvider.new cssfile = File.open("./style.css") css="" while line = cssfile.gets css+=line end provider.load(:data => css) apply_css(self, provider) end def apply_css(widget, provider) widget.style_context.add_provider(provider, GLib::MAXUINT) if widget.is_a?(Gtk::Container) widget.each_forall do |child| apply_css(child, provider) end end end end end Gtk.init @window = ADesktop::MainWindow.new() @window.show_all Gtk.main Stay above and skip the hint #!/bin/ruby require 'gtk3' module ADesktop class MainWindow < Gtk::Window COL_PATH, COL_DISPLAY_NAME, COL_IS_DIR, COL_PIXBUF = (0..3).to_a def fill_store @store.clear Dir.glob(File.join(@parent, "*")).each do |path| is_dir = FileTest.directory?(path) iconfile = Gtk::IconTheme.default.lookup_icon("gtk-file", 48, 0).filename if !is_dir iconfile = Gtk::IconTheme.default.lookup_icon("folder", 48, 0).filename if is_dir iter = @store.append path = GLib.filename_to_utf8(path) iter[COL_DISPLAY_NAME] = File.basename(path) iter[COL_PATH] = path iter[COL_IS_DIR] = is_dir iter[COL_PIXBUF] = Gdk::Pixbuf.new(iconfile) end end def initialize() super(:popup) set_title("ADesktop") self.signal_connect("destroy") { Gtk.main_quit } screen = Gdk::Screen.default self.set_default_size(screen.width,screen.height) self.set_keep_above(true) self.skip_pager_hint = true self.skip_taskbar_hint = true @store = Gtk::ListStore.new(String, String, TrueClass, Gdk::Pixbuf) @parent = "/home/aosc/Desktop" @store.set_default_sort_func do |a, b| if !a[COL_IS_DIR] and b[COL_IS_DIR] 1 elsif a[COL_IS_DIR] and !b[COL_IS_DIR] -1 else a[COL_DISPLAY_NAME] <=> b[COL_DISPLAY_NAME] end end @store.set_sort_column_id(Gtk::TreeSortable::DEFAULT_SORT_COLUMN_ID, Gtk::SortType::ASCENDING) fill_store set_border_width(0) box = Gtk::Box.new(:vertical,0) self.add(box) sw = Gtk::ScrolledWindow.new sw.set_policy(:automatic, :automatic) box.pack_end(sw, :expand => true, :fill => true, :padding => 0) iconview = Gtk::IconView.new(@store) iconview.selection_mode = :multiple iconview.text_column = COL_DISPLAY_NAME iconview.pixbuf_column = COL_PIXBUF iconview.signal_connect("item_activated") do |iview, path| iter = @store.get_iter(path) system("xdg-open "+iter[COL_PATH]) end sw.add(iconview) iconview.grab_focus provider = Gtk::CssProvider.new cssfile = File.open("./style.css") css="" while line = cssfile.gets css+=line end provider.load(:data => css) apply_css(self, provider) end def apply_css(widget, provider) widget.style_context.add_provider(provider, GLib::MAXUINT) if widget.is_a?(Gtk::Container) widget.each_forall do |child| apply_css(child, provider) end end end end end Gtk.init @window = ADesktop::MainWindow.new() @window.show_all Gtk.main
79274ac2-2d48-11e5-81a2-7831c1c36510 792d1b63-2d48-11e5-ab6e-7831c1c36510 792d1b63-2d48-11e5-ab6e-7831c1c36510
799f60de-2d48-11e5-989b-7831c1c36510 79a55e26-2d48-11e5-acf0-7831c1c36510 79a55e26-2d48-11e5-acf0-7831c1c36510
4c3404cc-2d48-11e5-985f-7831c1c36510 4c3a0107-2d48-11e5-a414-7831c1c36510 4c3a0107-2d48-11e5-a414-7831c1c36510
#!/usr/bin/env ruby require 'colorize' require_relative 'world' class Character attr_accessor :name, :hp, :xp, :attack, :defence, :level, :state, :location # Create the character, which by default begins at level one def initialize(name, initial_level=1) @name = name @hp = rand(80..100) + rand(10..20) * initial_level @xp = 0 @attack = rand(80..100) + rand(10..20) * initial_level @defence = rand(80..100) + rand(10..20) * initial_level @level = initial_level @location = 3001 end # Add experience. If we've gained 400xp since our last level, level up! def add_xp(gain) @xp += gain if @xp >= 400 # level up! puts "Congratulations, you have gained a level!" @xp =- 400 @attack += rand(10..20) @defence += rand(10..20) @hp = @defence @level += 1 end end def get_stats puts "\nName:%12s" % name puts "Level: %6d" % level puts "Experience:%6d" % xp puts "Hitpoints: %6d" % hp puts "Attack: %6d" % attack puts "Defence: %6d\n" % defence end end def get_player_choice print "(A)ttack, (D)efend, or (F)lee? " case gets.chomp.first when "A" then return "attack" when "D" then return "defend" when "F" then return "flee" else puts "I'm sorry, that's not an option." return get_player_choice end end def get_enemy_choice(defence, attack) (rand(defense + attack) < defence) ? "defend" : "attack" end def fill_name_array(names) f = File.open("names") or die "Unable to open 'names' file." f.each_line {|name|names.push name} f.close end def player_action(protagonist, antagonist, choice) case choice when "attack" damage = protagonist.attack * rand(1..3) / 10 antagonist.hp -= damage return "Your attack did #{damage} damage to #{antagonist.name}!" when "defend" restore = protagonist.defence * rand(1..2) / 15 protagonist.hp = [protagonist.defence, protagonist.hp + restore].min return "You restored #{restore} hitpoints!" when "flee" puts "#{antagonist.name} laughs as you run away like a coward." exit end end def enemy_action(protagonist, antagonist, choice) case choice when "attack" damage = protagonist.attack * rand(1..3) / 10 antagonist.hp -= damage return "#{protagonist.name}'s attack did #{damage} damage!" when "defend" restore = protagonist.defence * rand(1..2) / 15 protagonist.hp = [protagonist.defence, protagonist.hp + restore].min return "#{protagonist.name} restored #{restore} hitpoints!" end end def handle_input expected = {n: 0, e: 1, s: 2, w: 3, u: 4, d: 5} new_location = $world.get_destination($player.location, expected.fetch(gets.chomp.first.downcase.to_sym) {puts "\nYou can't go that way!".colorize(:green)}) $player.location = new_location end if __FILE__ == $0 fill_name_array %w(Mike Joe Alice Susan) $world = World.new "30.wld" print "Welcome! What is your name? ".colorize(:green) $player = Character.new gets.chomp puts loop do # starts an infinite loop puts $world.get_room_name($player.location).colorize(:light_blue) puts $world.get_room_description($player.location).colorize(:green) print "\n\n> ".colorize(:green) handle_input end end When asking for player input, looks for any instances of 'a', 'f', and 'd' instead of just checking the first character. #!/usr/bin/env ruby require 'colorize' require_relative 'world' class Character attr_accessor :name, :hp, :xp, :attack, :defence, :level, :state, :location # Create the character, which by default begins at level one def initialize(name, initial_level=1) @name = name @hp = rand(80..100) + rand(10..20) * initial_level @xp = 0 @attack = rand(80..100) + rand(10..20) * initial_level @defence = rand(80..100) + rand(10..20) * initial_level @level = initial_level @location = 3001 end # Add experience. If we've gained 400xp since our last level, level up! def add_xp(gain) @xp += gain if @xp >= 400 # level up! puts "Congratulations, you have gained a level!" @xp =- 400 @attack += rand(10..20) @defence += rand(10..20) @hp = @defence @level += 1 end end def get_stats puts "\nName:%12s" % name puts "Level: %6d" % level puts "Experience:%6d" % xp puts "Hitpoints: %6d" % hp puts "Attack: %6d" % attack puts "Defence: %6d\n" % defence end end def get_player_choice print "(A)ttack, (D)efend, or (F)lee? " case gets.chomp when /a/ then return "attack" when /d/ then return "defend" when /f/ then return "flee" else puts "I'm sorry, that's not an option." return get_player_choice end end def get_enemy_choice(defence, attack) (rand(defense + attack) < defence) ? "defend" : "attack" end def fill_name_array(names) f = File.open("names") or die "Unable to open 'names' file." f.each_line {|name|names.push name} f.close end def player_action(protagonist, antagonist, choice) case choice when "attack" damage = protagonist.attack * rand(1..3) / 10 antagonist.hp -= damage return "Your attack did #{damage} damage to #{antagonist.name}!" when "defend" restore = protagonist.defence * rand(1..2) / 15 protagonist.hp = [protagonist.defence, protagonist.hp + restore].min return "You restored #{restore} hitpoints!" when "flee" puts "#{antagonist.name} laughs as you run away like a coward." exit end end def enemy_action(protagonist, antagonist, choice) case choice when "attack" damage = protagonist.attack * rand(1..3) / 10 antagonist.hp -= damage return "#{protagonist.name}'s attack did #{damage} damage!" when "defend" restore = protagonist.defence * rand(1..2) / 15 protagonist.hp = [protagonist.defence, protagonist.hp + restore].min return "#{protagonist.name} restored #{restore} hitpoints!" end end def handle_input expected = {n: 0, e: 1, s: 2, w: 3, u: 4, d: 5} new_location = $world.get_destination($player.location, expected.fetch(gets.chomp.first.downcase.to_sym) {puts "\nYou can't go that way!".colorize(:green)}) $player.location = new_location end if __FILE__ == $0 fill_name_array %w(Mike Joe Alice Susan) $world = World.new "30.wld" print "Welcome! What is your name? ".colorize(:green) $player = Character.new gets.chomp puts loop do # starts an infinite loop puts $world.get_room_name($player.location).colorize(:light_blue) puts $world.get_room_description($player.location).colorize(:green) print "\n\n> ".colorize(:green) handle_input end end
# It was the night before Christmas and all through the house, not a creature was coding: UTF-8, not even with a mouse. require 'bundler' require 'tempfile' require 'digest/md5' Bundler.require(:default) require 'sinatra/sprockets-helpers' require 'sinatra/asset_pipeline' # Monkey patched Redis for easy caching. class Redis def cache(key, expire=nil) if (value = get(key)).nil? value = yield(self) set(key, value) expire(key, expire) if expire value else value end end end # Ease of use connection to the redis server. $redis = Redis.new :driver=>:hiredis DataMapper.setup(:default, "sqlite3://#{File.expand_path(File.dirname(__FILE__))}/main.db") # Redis has issues with datamapper associations especially Many-to-many. #$adapter = DataMapper.setup(:default, {:adapter => "redis"}); #$redis = $adapter.redis data = "window = {};"+File.read("./assets/javascripts/diff_match_patch.js") + File.read("./assets/javascripts/jsondiffpatch.min.js") $jsondiffpatch = ExecJS.compile data Sinatra::Sprockets = Sprockets module BJSONDiffPatch def diff object1, object2 return $jsondiffpatch.eval "jsondiffpatch.diff(#{JSON.dump(object1)},#{JSON.dump(object2)})" end end class JSONDiffPatch extend BJSONDiffPatch end class Document include DataMapper::Resource property :id, Serial property :name, String #property :body, Text property :body, Json, :default=>{}, :lazy=>true property :created, DateTime property :last_edit_time, DateTime property :public, Boolean, :default=>false property :config, Object, :default=>{} has n, :assets, :through => Resource belongs_to :user def config_set key, value n_config = config.dup n_config[key]=value self.config= n_config end end # Assets could be javascript or css class Asset include DataMapper::Resource property :id, Serial property :name, String property :description, String property :url, String property :type, Discriminator has n, :documents, :through => Resource end class Javascript < Asset; end class Stylesheet < Asset; end class User include DataMapper::Resource property :email, String, :key=>true property :password, BCryptHash has n, :documents property :config, Object, :default=>{} def config_set key, value n_config = config.dup n_config[key]=value self.config= n_config end end DataMapper.finalize DataMapper.auto_upgrade! class WebSync < Sinatra::Base use Rack::Logger helpers do def logger request.logger end def current_user if logged_in? return User.get(session['user']) end nil end def logged_in? (!session['userhash'].nil?)&&$redis.get('userhash:'+session['userhash'])==session['user'] end def login_required if !logged_in? redirect "/login?#{env["REQUEST_PATH"]}" end end def register email, pass email.downcase! if User.get(email).nil? user = User.create({:email=>email,:password=>pass}) authenticate email, pass return user elsif authenticate email, pass return current_user end nil end def authenticate email, pass, expire=nil email.downcase! user = User.get(email) if user.nil? return false end if user.password==pass session_key = SecureRandom.uuid $redis.set("userhash:#{session_key}",email) session['userhash']=session_key session['user']=email if !expire.nil? $redis.expire("userhash:#{session_key}",expire) end return true end false end def logout $redis.del "userhash:#{session['userhash']}" session['userhash']=nil session['user']=nil end def render_login_button if logged_in? return '<a href="/logout" title="Sign Out"><i class="icon-signout icon-large"></i> Sign Out</a>' else return '<a href="/login" title="Sign In"><i class="icon-signin icon-large"></i> Sign In</a>' end end end configure :development do Bundler.require(:development) set :assets_debug, true use PryRescue::Rack end configure :production do Bundler.require(:production) set :assets_css_compressor, :sass set :assets_js_compressor, :closure set :assets_precompile, %w(bundle.css bundle-norm.js bundle-edit.js *.png *.favico *.jpg *.svg *.eot *.ttf *.woff) set :assets_precompile_no_digest, %w(*.js) end configure do enable :sessions set :session_secret, "Web-Sync sdkjfskadfh1h3248c99sj2j4j2343" set :server, 'thin' set :sockets, [] set :template_engine, :erb register Sinatra::AssetPipeline sprockets.append_path File.join(root, 'assets', 'stylesheets') sprockets.append_path File.join(root, 'assets', 'javascripts') sprockets.append_path File.join(root, 'assets', 'images') end $dmp = DiffMatchPatch.new $table = Javascript.first_or_create(:name=>'Tables',:description=>'Table editing support',:url=>'/assets/tables.js') $chat = Javascript.first_or_create(:name=>'Chat',:description=>'Talk with other users!',:url=>'/assets/chat.js') get '/login' do if !logged_in? erb :login else redirect '/' end end post '/login' do redirect_loc = '/' if params[:redirect]!='' redirect_loc = params[:redirect] end if authenticate params[:email],params[:password] redirect redirect_loc else redirect "/login?#{redirect_loc}" end end get '/register' do redirect '/login' end post '/register' do if register params[:email],params[:password] redirect '/' else redirect '/login' end end get '/logout' do if logged_in? logout end redirect '/login' end not_found do erb :not_found end #get '/assets/*.css' do # content_type 'text/css' # assets_environment[params[:splat][0]+'.css'].to_s #end #get '/assets/*.js' do # content_type 'text/javascript' # assets_environment[params[:splat][0]+'.js'].to_s #end get '/' do #$redis.cache("index",300) do @javascripts = [] erb :index #end end get '/documentation' do erb :documentation end get '/new' do login_required doc = Document.create( :name => 'Unnamed Document', :body => {}, :created => Time.now, :last_edit_time => Time.now, :user => current_user ) doc.assets << Asset.get(1) doc.assets << Asset.get(2) doc.save redirect "/#{doc.id.base62_encode}/edit" end get '/upload' do login_required erb :upload end post '/upload' do tempfile = params[:file][:tempfile] filename = params[:file][:filename] filetype = params[:file][:type] content = nil # TODO: Split upload/download into its own external server. Right now Unoconv is blocking. Also issues may arise if multiple copies of LibreOffice are running on the same server. Should probably use a single server instance of LibreOffice `unoconv -f html #{tempfile.path}` exit_status = $?.to_i if exit_status == 0 content = File.read(tempfile.path+".html") else if filetype=="application/pdf" content = PDFToHTMLR::PdfFilePath.new(tempfile.path).convert.force_encoding("UTF-8") elsif filetype=='text/html' content = File.read(tempfile.path) elsif filename.split('.').pop=='docx' # This pretty much just reads plain text... content = Docx::Document.open(tempfile.path).to_html.force_encoding("UTF-8") else logger.info "Unoconv failed and Unrecognized filetype: #{params[:file][:type]}" end end if content!=nil # TODO: Upload into JSON format doc = Document.create( :name => filename, :body => content, :created => Time.now, :last_edit_time => Time.now, :user => current_user ) doc.assets << Asset.get(1) doc.save redirect "/#{doc.id.base62_encode}/edit" else redirect "/" end end get '/:doc/download/:format' do if !%w(bib doc doc6 doc95 docbook html odt ott ooxml pdb pdf psw rtf latex sdw sdw4 sdw3 stw sxw text txt vor vor4 vor3 xhtml bmp emf eps gif jpg met odd otg pbm pct pgm png ppm ras std svg svm swf sxd sxd3 sxd5 tiff wmf xpm odg odp pot ppt pwp sda sdd sdd3 sdd4 sti stp sxi vor5 csv dbf dif ods pts pxl sdc sdc4 sdc3 slk stc sxc xls xls5 xls95 xlt xlt5).include?(params[:format]) redirect '/' end login_required doc_id = params[:doc].base62_decode doc = Document.get doc_id if (!doc.public)&&doc.user!=current_user redirect '/' end file = Tempfile.new('websync-export') file.write doc.body file.close `unoconv -f #{params[:format]} #{file.path}` if $?.to_i==0 export_file = file.path+"."+params[:format] response.headers['content_type'] = `file --mime -b export_file`.split(';')[0] attachment(doc.name+'.'+params[:format]) response.write(File.read(export_file)) else redirect '/' end file.unlink end get '/:doc/delete' do login_required doc_id = params[:doc].base62_decode doc = Document.get doc_id if doc.user==current_user doc.destroy! end redirect '/' end get '/:doc/edit' do doc_id = params[:doc].base62_decode doc = Document.get doc_id if doc.nil? redirect 'notfound' end if !request.websocket? login_required if (!doc.public)&&doc.user!=current_user redirect '/' end @javascripts = [ #'/assets/bundle-edit.js' ] @doc = doc if !@doc.nil? @client_id = $redis.incr("clientid").base62_encode @client_key = SecureRandom.uuid $redis.set "websocket:id:#{@client_id}",current_user.email $redis.set "websocket:key:#{@client_id}", @client_key $redis.expire "websocket:id:#{@client_id}", 60*60*24*7 $redis.expire "websocket:key:#{@client_id}", 60*60*24*7 @no_menu = true erb :edit else redirect '/' end # Websocket edit else #TODO: Authentication for websockets redis_sock = EM::Hiredis.connect.pubsub redis_sock.subscribe("doc:#{doc_id.base62_encode}") authenticated = false user = nil client_id = nil request.websocket do |ws| websock = ws ws.onopen do warn "websocket open" end ws.onmessage do |msg| data = MultiJson.parse(msg.force_encoding("UTF-8")); puts "JSON: #{data.to_s}" if data['type']=='auth' if $redis.get("websocket:key:#{data['id']}") == data['key'] # Extend key expiry time email = $redis.get "websocket:id:#{data['id']}" user = User.get(email) if (!doc.public)&&doc.user!=user redis_sock.close_connection ws.close_connection return end authenticated = true client_id = data['id'] $redis.expire "websocket:id:#{client_id}", 60*60*24*7 $redis.expire "websocket:key:#{client_id}", 60*60*24*7 user_prop = "doc:#{doc_id.base62_encode}:users" user_raw = $redis.get(user_prop) if !user_raw.nil? users = MultiJson.parse(user_raw) else users = {} end user_id = Digest::MD5.hexdigest(email.strip.downcase) users[client_id]={id:user_id,email:email.strip} $redis.set user_prop,MultiJson.dump(users) $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:MultiJson.dump({type:"new_user",id:client_id,user:{id:user_id,email:email.strip}})}) ws.send MultiJson.dump({type:'info',user_id:user_id,users:users}) puts "[Websocket Client Authed] ID: #{client_id}, Email: #{email}" else ws.close_connection end end if authenticated # This replaces all the text w/ the provided content. if data["type"]=="text_update" doc.body = data["text"] doc.last_edit_time = Time.now if !doc.save puts("Save errors: #{doc.errors.inspect}") end $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:msg}) # Google Diff-Match-Patch algorithm elsif data['type']=='text_patch' doc = Document.get doc_id #I'm pretty sure this works just fine. The main issue seems to be diffing w/ structure content. We'll see with time. #html_optimized_patches = diff_htmlToChars_ doc.body, URI::decode(data['patch']) #puts html_optimized_patches.inspect patches = $dmp.patch_from_text data['patch'] doc.body = $dmp.patch_apply(patches,doc.body)[0] doc.last_edit_time = Time.now if !doc.save puts("Save errors: #{doc.errors.inspect}") end $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:msg}) # Sets the name elsif data['type']=="name_update" doc.name = data["name"] doc.last_edit_time = Time.now if !doc.save puts("Save errors: #{doc.errors.inspect}") end $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:msg}) # Loads scripts elsif data['type']=="load_scripts" msg = {type:'scripts', js:[],css:[]} doc.assets.each do |asset| arr = :js; if asset.type=="javascript" arr = :js elsif asset.type=="stylesheet" arr = :css end msg[arr].push asset.url end ws.send MultiJson.dump msg elsif data['type']=='connection' elsif data['type']=='config' if data['action']=='set' if data['property']=='public' doc.public = data['value'] doc.save else if data['space']=='user' user.config_set data['property'],data['value'] user.save elsif data['space']=='document' doc.config_set data['property'],data['value'] doc.save end end elsif data['action']=='get' if data['property']=='public' ws.send MultiJson.dump({type: 'config',action: 'get', property:'public', value: doc.public}) else if data['space']=='user' ws.send MultiJson.dump({type: 'config', action: data['action'], space: data['space'], property: data['property'], value: user.config[data['property']],id:data['id']}) elsif data['space']=='document' ws.send MultiJson.dump({type: 'config', action: data['action'], space: data['space'], property: data['property'], value: doc.config[data['property']],id:data['id']}) end end end elsif data['type']=='client_event' $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:MultiJson.dump({type:"client_event",event:data['event'],from:client_id,data:data['data']})}) end end end ws.onclose do warn("websocket closed") redis_sock.close_connection if authenticated user_prop = "doc:#{doc_id.base62_encode}:users" users = MultiJson.parse($redis.get(user_prop)) users.delete client_id $redis.set user_prop,MultiJson.dump(users) $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:MultiJson.dump({type:"exit_user",id:client_id})}) end ws.close_connection end redis_sock.on(:message) do |channel, message| puts "[#{client_id}]#{channel}: #{message}" data = MultiJson.parse(message) if data['client']!=client_id if data['type']=="client_bounce" ws.send data['data'] end end end end end end =begin # This might be completely useless since it seems like you only have to structure for diff. # Create a diff after replacing all HTML tags with unicode characters. def diff_htmlToChars_ text1, text2 lineArray = [] # e.g. lineArray[4] == 'Hello\n' lineHash = {} # e.g. lineHash['Hello\n'] == 4 # '\x00' is a valid character, but various debuggers don't like it. # So we'll insert a junk entry to avoid generating a null character. lineArray[0] = '' #/** #* Split a text into an array of strings. Reduce the texts to a string of #* hashes where each Unicode character represents one line. #* Modifies linearray and linehash through being a closure. #* @param {string} text String to encode. #* @return {string} Encoded string. #* @private #*/ def diff_linesToCharsMunge_ text, lineArray, lineHash chars = ""+text #// Walk the text, pulling out a substring for each line. #// text.split('\n') would would temporarily double our memory footprint. #// Modifying text would create many large strings to garbage collect. lineStart = 0 lineEnd = 0 #// Keeping our own length variable is faster than looking it up. lineArrayLength = lineArray.length; while lineEnd <(text.length - 1) prevLineEnd = lineEnd if prevLineEnd==nil prevLineEnd=0 end lineStart = text.index('<',lineEnd) if lineStart.nil? lineEnd=nil break else lineEnd = text.index('>', lineStart) end if lineEnd.nil? lineEnd = text.length - 1 end line = text[lineStart..lineEnd] lineStart = lineEnd + 1 if lineHash.has_key? line chars.gsub!(line,[lineHash[line]].pack("U")) else chars.gsub!(line,[lineArrayLength].pack("U")) lineHash[line] = lineArrayLength lineArray[lineArrayLength] = line lineArrayLength +=1 end end return chars; end chars1 = diff_linesToCharsMunge_(text1, lineArray,lineHash) chars2 = diff_linesToCharsMunge_(text2,lineArray,lineHash) return {chars1: chars1, chars2: chars2, lineArray: lineArray} end def diff_charsToHTML_ diffs, lineArray (0..(diffs.length-1)).each do |x| chars = diffs[x][1]; text = ""+chars (0..(lineArray-1)).each do |y| text.gsub!([y].pack("U"),lineArray[y]) end diffs[x][1] = text; end end =end end Fixed MultiJson.load # It was the night before Christmas and all through the house, not a creature was coding: UTF-8, not even with a mouse. require 'bundler' require 'tempfile' require 'digest/md5' Bundler.require(:default) require 'sinatra/sprockets-helpers' require 'sinatra/asset_pipeline' # Monkey patched Redis for easy caching. class Redis def cache(key, expire=nil) if (value = get(key)).nil? value = yield(self) set(key, value) expire(key, expire) if expire value else value end end end # Ease of use connection to the redis server. $redis = Redis.new :driver=>:hiredis DataMapper.setup(:default, "sqlite3://#{File.expand_path(File.dirname(__FILE__))}/main.db") # Redis has issues with datamapper associations especially Many-to-many. #$adapter = DataMapper.setup(:default, {:adapter => "redis"}); #$redis = $adapter.redis data = "window = {};"+File.read("./assets/javascripts/diff_match_patch.js") + File.read("./assets/javascripts/jsondiffpatch.min.js") $jsondiffpatch = ExecJS.compile data Sinatra::Sprockets = Sprockets module BJSONDiffPatch def diff object1, object2 return $jsondiffpatch.eval "jsondiffpatch.diff(#{MultiJson.dump(object1)},#{MultiJson.dump(object2)})" end end class JSONDiffPatch extend BJSONDiffPatch end class Document include DataMapper::Resource property :id, Serial property :name, String #property :body, Text property :body, Json, :default=>{}, :lazy=>true property :created, DateTime property :last_edit_time, DateTime property :public, Boolean, :default=>false property :config, Object, :default=>{} has n, :assets, :through => Resource belongs_to :user def config_set key, value n_config = config.dup n_config[key]=value self.config= n_config end end # Assets could be javascript or css class Asset include DataMapper::Resource property :id, Serial property :name, String property :description, String property :url, String property :type, Discriminator has n, :documents, :through => Resource end class Javascript < Asset; end class Stylesheet < Asset; end class User include DataMapper::Resource property :email, String, :key=>true property :password, BCryptHash has n, :documents property :config, Object, :default=>{} def config_set key, value n_config = config.dup n_config[key]=value self.config= n_config end end DataMapper.finalize DataMapper.auto_upgrade! class WebSync < Sinatra::Base use Rack::Logger helpers do def logger request.logger end def current_user if logged_in? return User.get(session['user']) end nil end def logged_in? (!session['userhash'].nil?)&&$redis.get('userhash:'+session['userhash'])==session['user'] end def login_required if !logged_in? redirect "/login?#{env["REQUEST_PATH"]}" end end def register email, pass email.downcase! if User.get(email).nil? user = User.create({:email=>email,:password=>pass}) authenticate email, pass return user elsif authenticate email, pass return current_user end nil end def authenticate email, pass, expire=nil email.downcase! user = User.get(email) if user.nil? return false end if user.password==pass session_key = SecureRandom.uuid $redis.set("userhash:#{session_key}",email) session['userhash']=session_key session['user']=email if !expire.nil? $redis.expire("userhash:#{session_key}",expire) end return true end false end def logout $redis.del "userhash:#{session['userhash']}" session['userhash']=nil session['user']=nil end def render_login_button if logged_in? return '<a href="/logout" title="Sign Out"><i class="icon-signout icon-large"></i> Sign Out</a>' else return '<a href="/login" title="Sign In"><i class="icon-signin icon-large"></i> Sign In</a>' end end end configure :development do Bundler.require(:development) set :assets_debug, true use PryRescue::Rack end configure :production do Bundler.require(:production) set :assets_css_compressor, :sass set :assets_js_compressor, :closure set :assets_precompile, %w(bundle.css bundle-norm.js bundle-edit.js *.png *.favico *.jpg *.svg *.eot *.ttf *.woff) set :assets_precompile_no_digest, %w(*.js) end configure do enable :sessions set :session_secret, "Web-Sync sdkjfskadfh1h3248c99sj2j4j2343" set :server, 'thin' set :sockets, [] set :template_engine, :erb register Sinatra::AssetPipeline sprockets.append_path File.join(root, 'assets', 'stylesheets') sprockets.append_path File.join(root, 'assets', 'javascripts') sprockets.append_path File.join(root, 'assets', 'images') end $dmp = DiffMatchPatch.new $table = Javascript.first_or_create(:name=>'Tables',:description=>'Table editing support',:url=>'/assets/tables.js') $chat = Javascript.first_or_create(:name=>'Chat',:description=>'Talk with other users!',:url=>'/assets/chat.js') get '/login' do if !logged_in? erb :login else redirect '/' end end post '/login' do redirect_loc = '/' if params[:redirect]!='' redirect_loc = params[:redirect] end if authenticate params[:email],params[:password] redirect redirect_loc else redirect "/login?#{redirect_loc}" end end get '/register' do redirect '/login' end post '/register' do if register params[:email],params[:password] redirect '/' else redirect '/login' end end get '/logout' do if logged_in? logout end redirect '/login' end not_found do erb :not_found end #get '/assets/*.css' do # content_type 'text/css' # assets_environment[params[:splat][0]+'.css'].to_s #end #get '/assets/*.js' do # content_type 'text/javascript' # assets_environment[params[:splat][0]+'.js'].to_s #end get '/' do #$redis.cache("index",300) do @javascripts = [] erb :index #end end get '/documentation' do erb :documentation end get '/new' do login_required doc = Document.create( :name => 'Unnamed Document', :body => {}, :created => Time.now, :last_edit_time => Time.now, :user => current_user ) doc.assets << Asset.get(1) doc.assets << Asset.get(2) doc.save redirect "/#{doc.id.base62_encode}/edit" end get '/upload' do login_required erb :upload end post '/upload' do tempfile = params[:file][:tempfile] filename = params[:file][:filename] filetype = params[:file][:type] content = nil # TODO: Split upload/download into its own external server. Right now Unoconv is blocking. Also issues may arise if multiple copies of LibreOffice are running on the same server. Should probably use a single server instance of LibreOffice `unoconv -f html #{tempfile.path}` exit_status = $?.to_i if exit_status == 0 content = File.read(tempfile.path+".html") else if filetype=="application/pdf" content = PDFToHTMLR::PdfFilePath.new(tempfile.path).convert.force_encoding("UTF-8") elsif filetype=='text/html' content = File.read(tempfile.path) elsif filename.split('.').pop=='docx' # This pretty much just reads plain text... content = Docx::Document.open(tempfile.path).to_html.force_encoding("UTF-8") else logger.info "Unoconv failed and Unrecognized filetype: #{params[:file][:type]}" end end if content!=nil # TODO: Upload into JSON format doc = Document.create( :name => filename, :body => content, :created => Time.now, :last_edit_time => Time.now, :user => current_user ) doc.assets << Asset.get(1) doc.save redirect "/#{doc.id.base62_encode}/edit" else redirect "/" end end get '/:doc/download/:format' do if !%w(bib doc doc6 doc95 docbook html odt ott ooxml pdb pdf psw rtf latex sdw sdw4 sdw3 stw sxw text txt vor vor4 vor3 xhtml bmp emf eps gif jpg met odd otg pbm pct pgm png ppm ras std svg svm swf sxd sxd3 sxd5 tiff wmf xpm odg odp pot ppt pwp sda sdd sdd3 sdd4 sti stp sxi vor5 csv dbf dif ods pts pxl sdc sdc4 sdc3 slk stc sxc xls xls5 xls95 xlt xlt5).include?(params[:format]) redirect '/' end login_required doc_id = params[:doc].base62_decode doc = Document.get doc_id if (!doc.public)&&doc.user!=current_user redirect '/' end file = Tempfile.new('websync-export') file.write doc.body file.close `unoconv -f #{params[:format]} #{file.path}` if $?.to_i==0 export_file = file.path+"."+params[:format] response.headers['content_type'] = `file --mime -b export_file`.split(';')[0] attachment(doc.name+'.'+params[:format]) response.write(File.read(export_file)) else redirect '/' end file.unlink end get '/:doc/delete' do login_required doc_id = params[:doc].base62_decode doc = Document.get doc_id if doc.user==current_user doc.destroy! end redirect '/' end get '/:doc/edit' do doc_id = params[:doc].base62_decode doc = Document.get doc_id if doc.nil? redirect 'notfound' end if !request.websocket? login_required if (!doc.public)&&doc.user!=current_user redirect '/' end @javascripts = [ #'/assets/bundle-edit.js' ] @doc = doc if !@doc.nil? @client_id = $redis.incr("clientid").base62_encode @client_key = SecureRandom.uuid $redis.set "websocket:id:#{@client_id}",current_user.email $redis.set "websocket:key:#{@client_id}", @client_key $redis.expire "websocket:id:#{@client_id}", 60*60*24*7 $redis.expire "websocket:key:#{@client_id}", 60*60*24*7 @no_menu = true erb :edit else redirect '/' end # Websocket edit else #TODO: Authentication for websockets redis_sock = EM::Hiredis.connect.pubsub redis_sock.subscribe("doc:#{doc_id.base62_encode}") authenticated = false user = nil client_id = nil request.websocket do |ws| websock = ws ws.onopen do warn "websocket open" end ws.onmessage do |msg| data = MultiJson.load(msg.force_encoding("UTF-8")); puts "JSON: #{data.to_s}" if data['type']=='auth' if $redis.get("websocket:key:#{data['id']}") == data['key'] # Extend key expiry time email = $redis.get "websocket:id:#{data['id']}" user = User.get(email) if (!doc.public)&&doc.user!=user redis_sock.close_connection ws.close_connection return end authenticated = true client_id = data['id'] $redis.expire "websocket:id:#{client_id}", 60*60*24*7 $redis.expire "websocket:key:#{client_id}", 60*60*24*7 user_prop = "doc:#{doc_id.base62_encode}:users" user_raw = $redis.get(user_prop) if !user_raw.nil? users = MultiJson.load(user_raw) else users = {} end user_id = Digest::MD5.hexdigest(email.strip.downcase) users[client_id]={id:user_id,email:email.strip} $redis.set user_prop,MultiJson.dump(users) $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:MultiJson.dump({type:"new_user",id:client_id,user:{id:user_id,email:email.strip}})}) ws.send MultiJson.dump({type:'info',user_id:user_id,users:users}) puts "[Websocket Client Authed] ID: #{client_id}, Email: #{email}" else ws.close_connection end end if authenticated # This replaces all the text w/ the provided content. if data["type"]=="text_update" doc.body = data["text"] doc.last_edit_time = Time.now if !doc.save puts("Save errors: #{doc.errors.inspect}") end $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:msg}) # Google Diff-Match-Patch algorithm elsif data['type']=='text_patch' doc = Document.get doc_id #I'm pretty sure this works just fine. The main issue seems to be diffing w/ structure content. We'll see with time. #html_optimized_patches = diff_htmlToChars_ doc.body, URI::decode(data['patch']) #puts html_optimized_patches.inspect patches = $dmp.patch_from_text data['patch'] doc.body = $dmp.patch_apply(patches,doc.body)[0] doc.last_edit_time = Time.now if !doc.save puts("Save errors: #{doc.errors.inspect}") end $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:msg}) # Sets the name elsif data['type']=="name_update" doc.name = data["name"] doc.last_edit_time = Time.now if !doc.save puts("Save errors: #{doc.errors.inspect}") end $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:msg}) # Loads scripts elsif data['type']=="load_scripts" msg = {type:'scripts', js:[],css:[]} doc.assets.each do |asset| arr = :js; if asset.type=="javascript" arr = :js elsif asset.type=="stylesheet" arr = :css end msg[arr].push asset.url end ws.send MultiJson.dump msg elsif data['type']=='connection' elsif data['type']=='config' if data['action']=='set' if data['property']=='public' doc.public = data['value'] doc.save else if data['space']=='user' user.config_set data['property'],data['value'] user.save elsif data['space']=='document' doc.config_set data['property'],data['value'] doc.save end end elsif data['action']=='get' if data['property']=='public' ws.send MultiJson.dump({type: 'config',action: 'get', property:'public', value: doc.public}) else if data['space']=='user' ws.send MultiJson.dump({type: 'config', action: data['action'], space: data['space'], property: data['property'], value: user.config[data['property']],id:data['id']}) elsif data['space']=='document' ws.send MultiJson.dump({type: 'config', action: data['action'], space: data['space'], property: data['property'], value: doc.config[data['property']],id:data['id']}) end end end elsif data['type']=='client_event' $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:MultiJson.dump({type:"client_event",event:data['event'],from:client_id,data:data['data']})}) end end end ws.onclose do warn("websocket closed") redis_sock.close_connection if authenticated user_prop = "doc:#{doc_id.base62_encode}:users" users = MultiJson.load($redis.get(user_prop)) users.delete client_id $redis.set user_prop,MultiJson.dump(users) $redis.publish "doc:#{doc_id.base62_encode}", MultiJson.dump({type:"client_bounce",client:client_id,data:MultiJson.dump({type:"exit_user",id:client_id})}) end ws.close_connection end redis_sock.on(:message) do |channel, message| puts "[#{client_id}]#{channel}: #{message}" data = MultiJson.load(message) if data['client']!=client_id if data['type']=="client_bounce" ws.send data['data'] end end end end end end =begin # This might be completely useless since it seems like you only have to structure for diff. # Create a diff after replacing all HTML tags with unicode characters. def diff_htmlToChars_ text1, text2 lineArray = [] # e.g. lineArray[4] == 'Hello\n' lineHash = {} # e.g. lineHash['Hello\n'] == 4 # '\x00' is a valid character, but various debuggers don't like it. # So we'll insert a junk entry to avoid generating a null character. lineArray[0] = '' #/** #* Split a text into an array of strings. Reduce the texts to a string of #* hashes where each Unicode character represents one line. #* Modifies linearray and linehash through being a closure. #* @param {string} text String to encode. #* @return {string} Encoded string. #* @private #*/ def diff_linesToCharsMunge_ text, lineArray, lineHash chars = ""+text #// Walk the text, pulling out a substring for each line. #// text.split('\n') would would temporarily double our memory footprint. #// Modifying text would create many large strings to garbage collect. lineStart = 0 lineEnd = 0 #// Keeping our own length variable is faster than looking it up. lineArrayLength = lineArray.length; while lineEnd <(text.length - 1) prevLineEnd = lineEnd if prevLineEnd==nil prevLineEnd=0 end lineStart = text.index('<',lineEnd) if lineStart.nil? lineEnd=nil break else lineEnd = text.index('>', lineStart) end if lineEnd.nil? lineEnd = text.length - 1 end line = text[lineStart..lineEnd] lineStart = lineEnd + 1 if lineHash.has_key? line chars.gsub!(line,[lineHash[line]].pack("U")) else chars.gsub!(line,[lineArrayLength].pack("U")) lineHash[line] = lineArrayLength lineArray[lineArrayLength] = line lineArrayLength +=1 end end return chars; end chars1 = diff_linesToCharsMunge_(text1, lineArray,lineHash) chars2 = diff_linesToCharsMunge_(text2,lineArray,lineHash) return {chars1: chars1, chars2: chars2, lineArray: lineArray} end def diff_charsToHTML_ diffs, lineArray (0..(diffs.length-1)).each do |x| chars = diffs[x][1]; text = ""+chars (0..(lineArray-1)).each do |y| text.gsub!([y].pack("U"),lineArray[y]) end diffs[x][1] = text; end end =end end
5c007702-2d48-11e5-8c9b-7831c1c36510 5c05abb5-2d48-11e5-ba62-7831c1c36510 5c05abb5-2d48-11e5-ba62-7831c1c36510
require_relative 'library' require 'ncurses' include Ncurses ################################################################################# # Initialize # ################################################################################# Ncurses.initscr # Start Ncurses Ncurses.noecho # Do not show keyboard input at cursor location Ncurses.curs_set(0) # Disable blinking cursor Ncurses.cbreak # Only accept a single character of input Ncurses.stdscr # Initialize Standard Screen, which uses dimensions of current Terminal window Ncurses.keypad(stdscr,true) # Use expanded keyboard characters sd_cols = [] # Standard Screen column aka y sd_lines = [] # Standard Screen lines aka x Ncurses.getmaxyx(stdscr,sd_cols,sd_lines) # Get Max Y,X for standard screen, place them in arrays. getmaxyx outputs to arrays. # Welcome Screen Ncurses.mvwaddstr(stdscr, sd_cols[0] / 2, sd_lines[0] / 2, "Welcome to Move!") Ncurses.mvwaddstr(stdscr, sd_cols[0] / 2 + 1, sd_lines[0] / 2, "rows = #{sd_cols[0]}, rows = #{sd_lines[0]}") Ncurses.refresh # Refresh window to display new text Ncurses.getch # Wait for user input Ncurses.clear # Clear the screen once player is ready to proceed Ncurses.refresh # Refresh window to display cleared screen # Instantiate Windows # For each window, define lines,cols variables and work with those instead of direct numbers # Demo game uses 4 windows: Field (aka game map), Viewport (aka what the player sees), Console and side HUD. field_lines = 200 field_cols = 200 view_lines = 25 view_cols = 25 hud_lines = view_lines hud_cols = 15 console_lines = 3 console_cols = view_cols + hud_cols field = Ncurses.newwin(field_lines, field_cols, 0, 0) viewp = Ncurses.derwin(field,view_lines, view_cols, 0, 0) # Must not exceed size of terminal or else crash console = Ncurses.newwin(console_lines, console_cols, view_lines, 0) hud = Ncurses.newwin(hud_lines, hud_cols, 0, view_lines) # Draw map draw_map(field) # Draws a simple map with one terrain type # Draw bunkers and beacons all_beacons = [] demo_bunker(field,10,10) # Adds a building to map. It overlays anything underneath it b1 = Beacon.new(xlines: 11, ycols: 16) all_beacons << b1 Ncurses.mvwaddstr(field, b1.xlines, b1.ycols, b1.symb) demo_bunker(field,field_lines - 21,field_cols - 21) # Adds a building to map. It overlays anything underneath it b2 = Beacon.new(xlines: field_lines - 20, ycols: field_cols - 15, message: "..HELP..HELP") all_beacons << b2 Ncurses.mvwaddstr(field, b2.xlines, b2.ycols, b2.symb) # Define Actors, Items and Terrain actors = [] # Array will contain ascii decimal value of actor symbols items = [36] # Array contains ascii decimal value of all items on ground walkable = [32,88,126] # ' ', '~', 'X' # Setup Actors field_max_lines = [] field_max_cols = [] Ncurses.getmaxyx(field,field_max_cols,field_max_lines) # Get Max Y,X of Field player_start_lines = (field_max_lines[0] / 4) player_start_cols = (field_max_cols[0] / 4) # Create Player Character p = Character.new(symb: '@', xlines: player_start_lines, ycols: player_start_cols, hp: 9) # Begin player in top, right corner actors << p.symb.ord # Add player symbol to array of actor symbols Ncurses.mvwaddstr(field, p.xlines, p.ycols, "#{p.symb}") # Draw layer to map center(viewp,field,p.xlines,p.ycols) # Center map on player # Create Monster m = Character.new(symb: 'M', xlines: player_start_cols + view_cols, ycols: player_start_lines + view_lines, hp: 3) # Begin Monster near player, but out of sight actors << m.symb.ord # Add player symbol to array of actor symbols Ncurses.mvwaddstr(field, m.xlines, m.ycols, "#{m.symb}") # Draw Monster to map Ncurses.wrefresh(viewp) # Update viewport with all previous changes # Set up Console borders(console) # Add borders to the console #Ncurses.mvwaddstr(console, 1, 2, "Hello!") # Add a test message to confirm console works Ncurses.wrefresh(console) # Refresh console window with message # Set up HUD (Heads-Up-Display) hud_on(hud,p) ################################################################################# # Game Loop # ################################################################################# # Game Variables - Initial set and forget direction_steps = 0 counter = 0 dice_roll = false # Begin Loop while p.hp > 0 # While Player hit points are above 0, keep playing input = Ncurses.getch case input when KEY_UP, 119 # Move Up check = check_movement(field,p.xlines - 1,p.ycols,walkable,items,actors) if check == 1 move_character_x(field,p,-1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_x(field,p,-1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when KEY_DOWN, 115 # Move Down check = check_movement(field,p.xlines + 1,p.ycols,walkable,items,actors) if check == 1 move_character_x(field,p,1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_x(field,p,1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when KEY_RIGHT, 100 # Move Right check = check_movement(field,p.xlines,p.ycols + 1,walkable,items,actors) if check == 1 move_character_y(field,p,1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_y(field,p,1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when KEY_LEFT, 97 # Move Left check = check_movement(field,p.xlines,p.ycols - 1,walkable,items,actors) if check == 1 move_character_y(field,p,-1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_y(field,p,-1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when 114 # r the_beacon = get_distance_all_beacons(p,all_beacons) if get_distance(p,the_beacon) < 101 message(console,static(the_beacon, transmission(field,the_beacon,p))) else message(console,"..zz..zZ..Zzz..") end when KEY_F2, 113, 81 # Quit Game with F2, q or Q break else Ncurses.flash # Flash screen if undefined input selected message(console,"Move not valid") # Display ascii decimal number of selected input Ncurses.wrefresh(console) end # Monster Move if m.hp <= 0 Ncurses.mvwaddstr(field, m.xlines, m.ycols, "X") # Turn into dead body Ncurses.wrefresh(viewp) else distance_from_player = [(p.xlines - m.xlines).abs,(p.ycols - m.ycols).abs] # Get positive value of distance between monster and player if distance_from_player[0] < view_lines / 2 or distance_from_player[1] < view_cols / 2 # if the monster is visible, chase player #message(console,"MONSTER HUNTS YOU!") # Troubleshooting message for testing mode_hunt(field,hud, m, p, walkable, items, actors) else # If player is not visible, wander around if counter <= direction_steps if dice_roll == false d6 = rand(6) direction_steps = rand(10..25) # Meander long distances dice_roll = true end #message(console,"steps:#{direction_steps},count:#{counter},d6:#{d6}") # Troubleshooting message for testing mode_wander(field,hud, m, p, walkable, items, actors,d6) counter += 1 else #message(console,"Monster move reset") # Troubleshooting message for testing dice_roll = false counter = 0 direction_steps = 0 end end end end Ncurses.clear Ncurses.mvwaddstr(stdscr, sd_cols[0] / 2, sd_lines[0] / 2, "Good Bye!") Ncurses.wrefresh(stdscr) Ncurses.getch Ncurses.endwin edited radio console message for clarity require_relative 'library' require 'ncurses' include Ncurses ################################################################################# # Initialize # ################################################################################# Ncurses.initscr # Start Ncurses Ncurses.noecho # Do not show keyboard input at cursor location Ncurses.curs_set(0) # Disable blinking cursor Ncurses.cbreak # Only accept a single character of input Ncurses.stdscr # Initialize Standard Screen, which uses dimensions of current Terminal window Ncurses.keypad(stdscr,true) # Use expanded keyboard characters sd_cols = [] # Standard Screen column aka y sd_lines = [] # Standard Screen lines aka x Ncurses.getmaxyx(stdscr,sd_cols,sd_lines) # Get Max Y,X for standard screen, place them in arrays. getmaxyx outputs to arrays. # Welcome Screen Ncurses.mvwaddstr(stdscr, sd_cols[0] / 2, sd_lines[0] / 2, "Welcome to Move!") Ncurses.mvwaddstr(stdscr, sd_cols[0] / 2 + 1, sd_lines[0] / 2, "rows = #{sd_cols[0]}, rows = #{sd_lines[0]}") Ncurses.refresh # Refresh window to display new text Ncurses.getch # Wait for user input Ncurses.clear # Clear the screen once player is ready to proceed Ncurses.refresh # Refresh window to display cleared screen # Instantiate Windows # For each window, define lines,cols variables and work with those instead of direct numbers # Demo game uses 4 windows: Field (aka game map), Viewport (aka what the player sees), Console and side HUD. field_lines = 200 field_cols = 200 view_lines = 25 view_cols = 25 hud_lines = view_lines hud_cols = 15 console_lines = 3 console_cols = view_cols + hud_cols field = Ncurses.newwin(field_lines, field_cols, 0, 0) viewp = Ncurses.derwin(field,view_lines, view_cols, 0, 0) # Must not exceed size of terminal or else crash console = Ncurses.newwin(console_lines, console_cols, view_lines, 0) hud = Ncurses.newwin(hud_lines, hud_cols, 0, view_lines) # Draw map draw_map(field) # Draws a simple map with one terrain type # Draw bunkers and beacons all_beacons = [] demo_bunker(field,10,10) # Adds a building to map. It overlays anything underneath it b1 = Beacon.new(xlines: 11, ycols: 16) all_beacons << b1 Ncurses.mvwaddstr(field, b1.xlines, b1.ycols, b1.symb) demo_bunker(field,field_lines - 21,field_cols - 21) # Adds a building to map. It overlays anything underneath it b2 = Beacon.new(xlines: field_lines - 20, ycols: field_cols - 15, message: "..HELP..HELP") all_beacons << b2 Ncurses.mvwaddstr(field, b2.xlines, b2.ycols, b2.symb) # Define Actors, Items and Terrain actors = [] # Array will contain ascii decimal value of actor symbols items = [36] # Array contains ascii decimal value of all items on ground walkable = [32,88,126] # ' ', '~', 'X' # Setup Actors field_max_lines = [] field_max_cols = [] Ncurses.getmaxyx(field,field_max_cols,field_max_lines) # Get Max Y,X of Field player_start_lines = (field_max_lines[0] / 4) player_start_cols = (field_max_cols[0] / 4) # Create Player Character p = Character.new(symb: '@', xlines: player_start_lines, ycols: player_start_cols, hp: 9) # Begin player in top, right corner actors << p.symb.ord # Add player symbol to array of actor symbols Ncurses.mvwaddstr(field, p.xlines, p.ycols, "#{p.symb}") # Draw layer to map center(viewp,field,p.xlines,p.ycols) # Center map on player # Create Monster m = Character.new(symb: 'M', xlines: player_start_cols + view_cols, ycols: player_start_lines + view_lines, hp: 3) # Begin Monster near player, but out of sight actors << m.symb.ord # Add player symbol to array of actor symbols Ncurses.mvwaddstr(field, m.xlines, m.ycols, "#{m.symb}") # Draw Monster to map Ncurses.wrefresh(viewp) # Update viewport with all previous changes # Set up Console borders(console) # Add borders to the console #Ncurses.mvwaddstr(console, 1, 2, "Hello!") # Add a test message to confirm console works Ncurses.wrefresh(console) # Refresh console window with message # Set up HUD (Heads-Up-Display) hud_on(hud,p) ################################################################################# # Game Loop # ################################################################################# # Game Variables - Initial set and forget direction_steps = 0 counter = 0 dice_roll = false # Begin Loop while p.hp > 0 # While Player hit points are above 0, keep playing input = Ncurses.getch case input when KEY_UP, 119 # Move Up check = check_movement(field,p.xlines - 1,p.ycols,walkable,items,actors) if check == 1 move_character_x(field,p,-1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_x(field,p,-1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when KEY_DOWN, 115 # Move Down check = check_movement(field,p.xlines + 1,p.ycols,walkable,items,actors) if check == 1 move_character_x(field,p,1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_x(field,p,1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when KEY_RIGHT, 100 # Move Right check = check_movement(field,p.xlines,p.ycols + 1,walkable,items,actors) if check == 1 move_character_y(field,p,1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_y(field,p,1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when KEY_LEFT, 97 # Move Left check = check_movement(field,p.xlines,p.ycols - 1,walkable,items,actors) if check == 1 move_character_y(field,p,-1) elsif check == 2 attack(m) elsif check == 3 Ncurses.mvwaddstr(hud, 8, 1, " -Money") Ncurses.wrefresh(hud) move_character_y(field,p,-1) else # No valid move nil end center(viewp,field,p.xlines,p.ycols) when 114 # r the_beacon = get_distance_all_beacons(p,all_beacons) if get_distance(p,the_beacon) < 101 message(console,"Radio: #{static(the_beacon, transmission(field,the_beacon,p))}") else message(console,"..zz..zZ..Zzz..") end when KEY_F2, 113, 81 # Quit Game with F2, q or Q break else Ncurses.flash # Flash screen if undefined input selected message(console,"Move not valid") # Display ascii decimal number of selected input Ncurses.wrefresh(console) end # Monster Move if m.hp <= 0 Ncurses.mvwaddstr(field, m.xlines, m.ycols, "X") # Turn into dead body Ncurses.wrefresh(viewp) else distance_from_player = [(p.xlines - m.xlines).abs,(p.ycols - m.ycols).abs] # Get positive value of distance between monster and player if distance_from_player[0] < view_lines / 2 or distance_from_player[1] < view_cols / 2 # if the monster is visible, chase player #message(console,"MONSTER HUNTS YOU!") # Troubleshooting message for testing mode_hunt(field,hud, m, p, walkable, items, actors) else # If player is not visible, wander around if counter <= direction_steps if dice_roll == false d6 = rand(6) direction_steps = rand(10..25) # Meander long distances dice_roll = true end #message(console,"steps:#{direction_steps},count:#{counter},d6:#{d6}") # Troubleshooting message for testing mode_wander(field,hud, m, p, walkable, items, actors,d6) counter += 1 else #message(console,"Monster move reset") # Troubleshooting message for testing dice_roll = false counter = 0 direction_steps = 0 end end end end Ncurses.clear Ncurses.mvwaddstr(stdscr, sd_cols[0] / 2, sd_lines[0] / 2, "Good Bye!") Ncurses.wrefresh(stdscr) Ncurses.getch Ncurses.endwin
#!/usr/bin/env ruby require 'rest_client' require "stringio" # # Handle arguments # $options = { :make_class => ARGV.delete("class") != nil, :make_mobile => ARGV.delete("mobile") != nil, :fresh => ARGV.delete("--fresh") != nil, :verbose => ARGV.delete("--verbose") != nil, :help => ARGV.delete("--help") != nil } if ARGV.length > 0 or $options[:help] or (!$options[:make_class] and !$options[:make_mobile]) commands = { "class" => "Makes a Tangerine Class APK", "mobile" => "Makes a regular Tangerine APK", "--fresh" => "Starts with a new database", "--verbose" => "Outputs additional information", "--help" => "..." } plural = if ARGV.length > 1 then "s" else "" end puts "\nTangerine make script\n\nUsage: make [class|mobile] --fresh --verbose --help\n" if $options[:help] then puts "\n" commands.each_pair do |opt, desc| printf " %-20s %s\n", opt, desc end end puts "Unrecognized argument#{plural}: #{ARGV.join(',')}" if ARGV.length > 0 puts "\n" exit(2) end # # Helper functions # # handles verbosity def check_step(response="", intent="") if response.downcase.include? "error" puts "Aborting. Error while attempting to #{intent}." puts split("\n").select { |line| line if line.downcase.include? "error" } exit(2) end if response.downcase.include? "warning" puts response.split("\n").select { |line| line if line.downcase.include? "warning" } elsif $options[:verbose] puts response end end # Shows user nice updates def section(title="") puts "\n\n*** #{title}\n" yield puts "Done." end # capture standard error def bite_tongue previous_stderr, $stderr = $stderr, StringIO.new yield $stderr.string ensure $stderr = previous_stderr end # # Config # time = Time.new home_dir = ENV['HOME'] backup_dir = "#{home_dir}/tangerine-apks/" relative_to_app = "../app/" version = `git log --pretty=format:'%h' -n 1` date_hour = "#{time.year}-#{time.month}-#{time.day}-#{time.day}" if $options[:make_class] package_name = "org.rti.tangerineclass" app_name = "Tangerine Class" context = "class" elsif $options[:make_mobile] package_name = "org.rti.tangerine" app_name = "Tangerine" context = "mobile" end # # Prepare CouchDB # section "Preparing couch" do # reverted to "server" after push File.open("#{relative_to_app}_docs/configuration.json", "r+") { |file| newText = file.read.sub(/\"context(.*)\"/, "\"context\" : \"#{context}\"") file.seek(0) file.truncate(0) file.write newText } if $options[:fresh] begin check_step RestClient.delete("http://tangerine:tangytangerine@localhost:5984/tangerine"), "delete database" rescue nil end check_step RestClient.put("http://tangerine:tangytangerine@localhost:5984/tangerine", "", :content_type => 'application/json'), "create new database" end bite_tongue do check_step `cd #{relative_to_app}; couchapp push; cd -`, "push with Couchapp" end File.open("#{relative_to_app}_docs/configuration.json", "r+") { |file| newText = file.read.sub(/\"context(.*)\"/, "\"context\" : \"server\"") file.seek(0) file.truncate(0) file.write newText } check_step RestClient.post("http://tangerine:tangytangerine@localhost:5984/tangerine/_compact", "", :content_type => 'application/json'), "compact database" end # # Prepare the source # section "Preparing source" do File.open("AndroidManifest.xml", "r+") { |file| newText = file.read.sub(/package=\"(.*?)\"/, "package=\"#{package_name}\"") file.seek(0) file.truncate(0) file.write newText } File.open("res/values/strings.xml", "r+") { |file| newText = file.read.sub(/\<string name=\"app_name\"\>(.*?)\<\/string\>/, "<string name=\"app_name\">#{app_name}</string>") file.seek(0) file.truncate(0) file.write newText } File.open("src/Tangerine.java", "r+") { |file| newText = file.read.sub(/package(.*?);/, "package #{package_name};") file.seek(0) file.truncate(0) file.write newText } end # # Get on with the building # bite_tongue do section "Building" do check_step `ant clean`, "clean with ant" check_step `ant debug`, "build APK" end section "Installing" do if $options[:make_class] check_step `adb uninstall org.rti.tangerineclass`, "uninstall old APK" elsif $options[:make_mobile] check_step `adb uninstall org.rti.tangerine`, "uninstall old APK" end check_step `adb install bin/Tangerine-debug.apk`, "install new APK" end # Save backup check_step `cp bin/Tangerine-debug.apk #{backup_dir}Tangerine-#{date_hour}-#{version}.apk`, "make backup" end puts "\nAll done. Enjoy your #{if $options[:fresh] then "fresh " else "" end}Tangerine.\n\n" launch app after install #!/usr/bin/env ruby require 'rest_client' require "stringio" # # Handle arguments # $options = { :make_class => ARGV.delete("class") != nil, :make_mobile => ARGV.delete("mobile") != nil, :fresh => ARGV.delete("--fresh") != nil, :verbose => ARGV.delete("--verbose") != nil, :help => ARGV.delete("--help") != nil } if ARGV.length > 0 or $options[:help] or (!$options[:make_class] and !$options[:make_mobile]) commands = { "class" => "Makes a Tangerine Class APK", "mobile" => "Makes a regular Tangerine APK", "--fresh" => "Starts with a new database", "--verbose" => "Outputs additional information", "--help" => "..." } plural = if ARGV.length > 1 then "s" else "" end puts "\nTangerine make script\n\nUsage: make [class|mobile] --fresh --verbose --help\n" if $options[:help] then puts "\n" commands.each_pair do |opt, desc| printf " %-20s %s\n", opt, desc end end puts "Unrecognized argument#{plural}: #{ARGV.join(',')}" if ARGV.length > 0 puts "\n" exit(2) end # # Helper functions # # handles verbosity def check_step(response="", intent="") if response.downcase.include? "error" puts "Aborting. Error while attempting to #{intent}." puts split("\n").select { |line| line if line.downcase.include? "error" } exit(2) end if response.downcase.include? "warning" puts response.split("\n").select { |line| line if line.downcase.include? "warning" } elsif $options[:verbose] puts response end end # Shows user nice updates def section(title="") puts "\n\n*** #{title}\n" yield puts "Done." end # capture standard error def bite_tongue previous_stderr, $stderr = $stderr, StringIO.new yield $stderr.string ensure $stderr = previous_stderr end # # Config # time = Time.new home_dir = ENV['HOME'] backup_dir = "#{home_dir}/tangerine-apks/" relative_to_app = "../app/" version = `git log --pretty=format:'%h' -n 1` date_hour = "#{time.year}-#{time.month}-#{time.day}-#{time.day}" if $options[:make_class] package_name = "org.rti.tangerineclass" app_name = "Tangerine Class" context = "class" elsif $options[:make_mobile] package_name = "org.rti.tangerine" app_name = "Tangerine" context = "mobile" end # # Prepare CouchDB # section "Preparing couch" do # reverted to "server" after push File.open("#{relative_to_app}_docs/configuration.json", "r+") { |file| newText = file.read.sub(/\"context(.*)\"/, "\"context\" : \"#{context}\"") file.seek(0) file.truncate(0) file.write newText } if $options[:fresh] begin check_step RestClient.delete("http://tangerine:tangytangerine@localhost:5984/tangerine"), "delete database" rescue nil end check_step RestClient.put("http://tangerine:tangytangerine@localhost:5984/tangerine", "", :content_type => 'application/json'), "create new database" end bite_tongue do check_step `cd #{relative_to_app}; couchapp push; cd -`, "push with Couchapp" end File.open("#{relative_to_app}_docs/configuration.json", "r+") { |file| newText = file.read.sub(/\"context(.*)\"/, "\"context\" : \"server\"") file.seek(0) file.truncate(0) file.write newText } check_step RestClient.post("http://tangerine:tangytangerine@localhost:5984/tangerine/_compact", "", :content_type => 'application/json'), "compact database" end # # Prepare the source # section "Preparing source" do File.open("AndroidManifest.xml", "r+") { |file| newText = file.read.sub(/package=\"(.*?)\"/, "package=\"#{package_name}\"") file.seek(0) file.truncate(0) file.write newText } File.open("res/values/strings.xml", "r+") { |file| newText = file.read.sub(/\<string name=\"app_name\"\>(.*?)\<\/string\>/, "<string name=\"app_name\">#{app_name}</string>") file.seek(0) file.truncate(0) file.write newText } File.open("src/Tangerine.java", "r+") { |file| newText = file.read.sub(/package(.*?);/, "package #{package_name};") file.seek(0) file.truncate(0) file.write newText } end # # Get on with the building # bite_tongue do section "Building" do check_step `ant clean`, "clean with ant" check_step `ant debug`, "build APK" end section "Installing" do if $options[:make_class] check_step `adb uninstall org.rti.tangerineclass`, "uninstall old APK" elsif $options[:make_mobile] check_step `adb uninstall org.rti.tangerine`, "uninstall old APK" end check_step `adb install bin/Tangerine-debug.apk`, "install new APK" end # Save backup check_step `cp bin/Tangerine-debug.apk #{backup_dir}Tangerine-#{date_hour}-#{version}.apk`, "make backup" end puts "\nAll done. Enjoy your #{if $options[:fresh] then "fresh " else "" end}Tangerine.\n\n" if $options[:make_mobile] `adb shell am start -n org.rti.tangerine/org.rti.tangerine.Tangerine` elsif $options[:make_class] `adb shell am start -n org.rti.tangerineclass/org.rti.tangerineclass.Tangerine` end
require 'paint' require './node' require './wall' require './path' class Maze attr_reader :height, :width def initialize(height, width, display_time = 0.0005) @display_time = display_time @height = height.even? ? height + 1 : height @width = width.even? ? width + 1 : width @nodes = @height.times.map do |row| if row.even? Array.new(@width) { |column| Wall.new(row, column) } else @width.times.map do |column| column.even? ? Wall.new(row, column) : Node.new(row, column) end end end puts self.paint end def paint @nodes.each_with_object('') do |row, result| row.each { |node| result << node.paint } result << "\n" end end def erase print "\r" + ("\e[A" * height) + "\e[J" end def make draw(@nodes[0][1].path) draw(@nodes[-1][-2].path) make_path(@nodes[1][1], @nodes[-2][-2]) self end def solve draw(@nodes[0][1].visit) solve_path(@nodes[1][1], @nodes[-2][-2]) # breadth_solve_path([Path.new([@nodes[1][1]])]) draw(@nodes[-1][-2].visit) self end private def make_path(node, previous) draw(node.path) unless node.path? return true if last_node?(node) next_node = neighbors(node).reject { |n| n.path? }.sample if next_node draw(get_wall(node, next_node).path) make_path(next_node, node) make_path(node, previous) end end def breadth_solve_path(paths) paths.each { |p| draw(p.last.visit) unless p.last.visited? } if finale = paths.find { |p| last_node?(p.last) } dead_nodes = (paths.flat_map(&:nodes) - finale.nodes) dead_nodes.concat(dead_nodes.flat_map { |n| open_walls(n) }) dead_nodes.shuffle.each do |n| draw(n.dead_end) unless n.dead_end? end return true end sub_paths = [] paths.each_with_index do |path, i| branches = neighbors(path.last).reject do |n| n.visited? || !get_wall(path.last, n).path? end .map { |n| Path.new(path.nodes, n) } if branches.empty? paths.values_at(0...i, (i + 1)..-1).each do |p| path.nodes -= p.nodes end path.nodes.shuffle.each do |n| draw(n.dead_end) open_walls(n).each { |w| draw(w.dead_end) unless w.dead_end? } end else sub_paths.concat(branches) end end unless sub_paths.empty? sub_paths.each { |p| draw(get_wall(p.last, p.previous).visit) } breadth_solve_path(sub_paths) end end def solve_path(node, previous) draw(node.visit) unless node.visited? return true if last_node?(node) next_node = neighbors(node).reject do |n| n.visited? || !get_wall(node, n).path? end .sample if next_node draw(get_wall(node, next_node).visit) if solve_path(next_node, node) true else draw(get_wall(node, next_node).dead_end) draw(next_node.dead_end) solve_path(node, previous) end end end def neighbors(node) [ get_node(node.row - 2, node.column), get_node(node.row + 2, node.column), get_node(node.row, node.column - 2), get_node(node.row, node.column + 2) ].compact end def last_node?(node) node.row == @height - 2 && node.column == @width - 2 end def get_node(row, column) return nil if row < 0 || column < 0 @nodes[row][column] if row < @height && column < @width end def open_walls(node) [ get_node(node.row - 1, node.column), get_node(node.row + 1, node.column), get_node(node.row, node.column - 1), get_node(node.row, node.column + 1) ].compact.select { |w| w.path? } end def get_wall(node, other_node) row = (node.row + other_node.row) / 2 column = (node.column + other_node.column) / 2 @nodes[row][column] end def draw(node) print "\r" print "\e[A" * (height - node.row) print "\e[C" * 2 * node.column print node.paint print "\e[B" * (height - node.row) print "\r" sleep(@display_time) end def show_step puts self.paint sleep(0.09) print "\r" + ("\e[A" * height) + "\e[J" end end Improve fading effect when finding dead ends When a path is determined to be a dead end, shuffle together the nodes and walls of the path and repaint them. This improves the effect over painting a node and its walls together. require 'paint' require './node' require './wall' require './path' class Maze attr_reader :height, :width def initialize(height, width, display_time = 0.0005) @display_time = display_time @height = height.even? ? height + 1 : height @width = width.even? ? width + 1 : width @nodes = @height.times.map do |row| if row.even? Array.new(@width) { |column| Wall.new(row, column) } else @width.times.map do |column| column.even? ? Wall.new(row, column) : Node.new(row, column) end end end puts self.paint end def paint @nodes.each_with_object('') do |row, result| row.each { |node| result << node.paint } result << "\n" end end def erase print "\r" + ("\e[A" * height) + "\e[J" end def make draw(@nodes[0][1].path) draw(@nodes[-1][-2].path) make_path(@nodes[1][1], @nodes[-2][-2]) self end def solve draw(@nodes[0][1].visit) solve_path(@nodes[1][1], @nodes[-2][-2]) # breadth_solve_path([Path.new([@nodes[1][1]])]) draw(@nodes[-1][-2].visit) self end private def make_path(node, previous) draw(node.path) unless node.path? return true if last_node?(node) next_node = neighbors(node).reject { |n| n.path? }.sample if next_node draw(get_wall(node, next_node).path) make_path(next_node, node) make_path(node, previous) end end def breadth_solve_path(paths) paths.each { |p| draw(p.last.visit) unless p.last.visited? } if finale = paths.find { |p| last_node?(p.last) } dead_nodes = (paths.flat_map(&:nodes) - finale.nodes) dead_nodes.concat(dead_nodes.flat_map { |n| open_walls(n) }) dead_nodes.shuffle.each do |n| draw(n.dead_end) unless n.dead_end? end return true end sub_paths = [] paths.each_with_index do |path, i| branches = neighbors(path.last).reject do |n| n.visited? || !get_wall(path.last, n).path? end .map { |n| Path.new(path.nodes, n) } if branches.empty? paths.values_at(0...i, (i + 1)..-1).each do |p| path.nodes -= p.nodes end (path.nodes + path.nodes.flat_map { |n| open_walls(n) }) .shuffle.each do |n| draw(n.dead_end) unless n.dead_end? end else sub_paths.concat(branches) end end unless sub_paths.empty? sub_paths.each { |p| draw(get_wall(p.last, p.previous).visit) } breadth_solve_path(sub_paths) end end def solve_path(node, previous) draw(node.visit) unless node.visited? return true if last_node?(node) next_node = neighbors(node).reject do |n| n.visited? || !get_wall(node, n).path? end .sample if next_node draw(get_wall(node, next_node).visit) if solve_path(next_node, node) true else draw(get_wall(node, next_node).dead_end) draw(next_node.dead_end) solve_path(node, previous) end end end def neighbors(node) [ get_node(node.row - 2, node.column), get_node(node.row + 2, node.column), get_node(node.row, node.column - 2), get_node(node.row, node.column + 2) ].compact end def last_node?(node) node.row == @height - 2 && node.column == @width - 2 end def get_node(row, column) return nil if row < 0 || column < 0 @nodes[row][column] if row < @height && column < @width end def open_walls(node) [ get_node(node.row - 1, node.column), get_node(node.row + 1, node.column), get_node(node.row, node.column - 1), get_node(node.row, node.column + 1) ].compact.select { |w| w.path? } end def get_wall(node, other_node) row = (node.row + other_node.row) / 2 column = (node.column + other_node.column) / 2 @nodes[row][column] end def draw(node) print "\r" print "\e[A" * (height - node.row) print "\e[C" * 2 * node.column print node.paint print "\e[B" * (height - node.row) print "\r" sleep(@display_time) end def show_step puts self.paint sleep(0.09) print "\r" + ("\e[A" * height) + "\e[J" end end
start of a unified application #!/usr/bin/env ruby # encoding: UTF-8 require 'time' class MinimumAverageMaximum attr_reader :key, :count, :min, :max def initialize(key) @key = key @count = 0.0 @total = 0.0 @min = 0.0 @max = 0.0 end def add(value) if @count == 0.0 @min = value @max = value else @min = value if value < @min @max = value if value > @max end @count += 1.0 @total += value end def average @total / @count end end class Statuses attr_reader :key, :count, :code2, :code3, :code4, :code5 def initialize(key) @key = key @count = 0 @code2 = 0 @code3 = 0 @code4 = 0 @code5 = 0 end def add(code) @count += 1 case code[0..0] when '2' @code2 += 1 when '3' @code3 += 1 when '4' @code4 += 1 when '5' @code5 += 1 end end end REPORT = '--report'.freeze BY = '--by'.freeze REPORT_VALUES = %w(status size response).freeze BY_VALUES = %w(hour ip).freeze def opts ## # Assumes that the options, in long format such as "--file xxx", # will come before the arguments. The first argument that appears # will signal the end of the options. So with: # # --file fred.txt --delim tab arnold smith --output fred.out # # "--file" and "--delim" are options and "arnold", "smith", # "--output", "fred.out" are all arguments # # To force option like arguments from being read as options # the plain "--" option will stop looking for options. Everything # after the "--" will be arguments # # All options must have parameters # # Probably a tad over-engineered :) ## commands = ARGV.dup options = {} arguments = [] end_of_options = false while commands.any? x = commands.shift.downcase if end_of_options arguments << x elsif x == '--' end_of_options = true elsif x.index('--') == 0 y = commands.shift.downcase options[x] = y else arguments << x end_of_options = true end end [options, arguments] end def valid_options(options) raise "Missing option #{REPORT}" unless options.key?(REPORT) raise "Argument to #{REPORT} must be either 'status', 'size' or 'response'" unless REPORT_VALUES.include?(options[REPORT]) raise "Missing option #{BY}" unless options.key?(BY) raise "Argument to #{BY} must be either 'hour' or 'ip'" unless BY_VALUES.include?(options[BY]) if options.size > 2 x = options.keys x.delete(REPORT) x.delete(BY) raise "Unknown option(s) #{x.inspect}" end end def process_line(line) puts line.upcase end options, arguments = opts valid_options(options) report = options[REPORT] by = options[BY] if arguments.any? arguments.each do |filename| File.open(filename, 'r').each do |line| process_line(line) end end else STDIN.read.split("\n").each do |line| process_line(line) end end
class Node < Formula desc "Platform built on V8 to build network applications" homepage "https://nodejs.org/" url "https://nodejs.org/dist/v7.7.4/node-v7.7.4.tar.xz" sha256 "807c61b1e90a6fd8af3f3b5c1929effa4e1cb4569e7a88357b73197feeba5719" head "https://github.com/nodejs/node.git" bottle do root_url "https://homebrew.bintray.com/bottles" sha256 "a1932b4970877f30b9ce4cae776109b2edb24e6b12523f897b1aca0bc5793bb6" => :sierra sha256 "6857d84df361d171102f4c9ac4dcd0a62122b79e42344cafd9091a2cb27f4c8d" => :el_capitan sha256 "d2d526207857bde2e55af0b6c35f64f9ef547bf647c87fe94faf0ef2001c1659" => :yosemite end option "with-debug", "Build with debugger hooks" option "with-openssl", "Build against Homebrew's OpenSSL instead of the bundled OpenSSL" deprecated_option "enable-debug" => "with-debug" depends_on :python => :build if MacOS.version <= :snow_leopard depends_on "pkg-config" => :build depends_on "icu4c" => :recommended depends_on "openssl" => :optional conflicts_with "node@4", :because => "Differing versions of the same formulae." # Per upstream - "Need g++ 4.8 or clang++ 3.4". fails_with :clang if MacOS.version <= :snow_leopard fails_with :gcc_4_0 fails_with :gcc ("4.3".."4.7").each do |n| fails_with :gcc => n end resource "icu4c" do url "https://ssl.icu-project.org/files/icu4c/58.1/icu4c-58_1-src.tgz" mirror "https://nuxi.nl/distfiles/third_party/icu4c-58_1-src.tgz" version "58.1" sha256 "0eb46ba3746a9c2092c8ad347a29b1a1b4941144772d13a88667a7b11ea30309" end def install # Never install the bundled "npm", always prefer our # installation from tarball for better packaging control. args = %W[--prefix=#{prefix} --without-npm] args << "--debug" if build.with? "debug" args << "--shared-openssl" if build.with? "openssl" args << "--tag=head" if build.head? if build.with? "full-icu" resource("icu4c").stage buildpath/"deps/icu" args << "--with-intl=full-icu" end system "./configure", *args system "make", "install" end def post_install rm_rf "#{prefix}/etc" rm_rf "#{etc}/bash_completion.d/npm" rm_rf "#{prefix}/libexec" end def caveats s = "" s += <<-EOS.undent Homebrew did NOT install npm. Please install and configure npm manually. EOS if build.without? "full-icu" s += <<-EOS.undent Please note by default only English locale support is provided. If you need full locale support you should either rebuild with full icu: `brew reinstall node --with-full-icu` or add full icu data at runtime following: https://github.com/nodejs/node/wiki/Intl#using-and-customizing-the-small-icu-build EOS end s end test do path = testpath/"test.js" path.write "console.log('hello');" output = shell_output("#{bin}/node #{path}").strip assert_equal "hello", output output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"en-EN\").format(1234.56))'").strip assert_equal "1,234.56", output if build.with? "full-icu" output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"de-DE\").format(1234.56))'").strip assert_equal "1.234,56", output end end end update node.rb formula to v7.8.0 class Node < Formula desc "Platform built on V8 to build network applications" homepage "https://nodejs.org/" url "https://nodejs.org/dist/v7.8.0/node-v7.8.0.tar.xz" sha256 "6821aaee58bbc8bc8d08fec6989a42278b725a21382500dc20fd9d9f71398f02" head "https://github.com/nodejs/node.git" bottle do root_url "https://homebrew.bintray.com/bottles" sha256 "95613cb9796550d8aadc24ca82f55f8c5d7c4eb89815b1fb7e1cfd65e998241f" => :sierra sha256 "0a6ab520d75cb99855b8b82dd229ba19cfa89561d53bd73f623dd6ad1ac60d7b" => :el_capitan sha256 "bd6c53b86bd62f50976f5c4ebc73c633273210c05f01aede33fcf896d74153d5" => :yosemite end option "with-debug", "Build with debugger hooks" option "with-openssl", "Build against Homebrew's OpenSSL instead of the bundled OpenSSL" deprecated_option "enable-debug" => "with-debug" depends_on :python => :build if MacOS.version <= :snow_leopard depends_on "pkg-config" => :build depends_on "icu4c" => :recommended depends_on "openssl" => :optional conflicts_with "node@4", :because => "Differing versions of the same formulae." # Per upstream - "Need g++ 4.8 or clang++ 3.4". fails_with :clang if MacOS.version <= :snow_leopard fails_with :gcc_4_0 fails_with :gcc ("4.3".."4.7").each do |n| fails_with :gcc => n end resource "icu4c" do url "https://ssl.icu-project.org/files/icu4c/58.1/icu4c-58_1-src.tgz" mirror "https://nuxi.nl/distfiles/third_party/icu4c-58_1-src.tgz" version "58.1" sha256 "0eb46ba3746a9c2092c8ad347a29b1a1b4941144772d13a88667a7b11ea30309" end def install # Never install the bundled "npm", always prefer our # installation from tarball for better packaging control. args = %W[--prefix=#{prefix} --without-npm] args << "--debug" if build.with? "debug" args << "--shared-openssl" if build.with? "openssl" args << "--tag=head" if build.head? if build.with? "full-icu" resource("icu4c").stage buildpath/"deps/icu" args << "--with-intl=full-icu" end system "./configure", *args system "make", "install" end def post_install rm_rf "#{prefix}/etc" rm_rf "#{etc}/bash_completion.d/npm" rm_rf "#{prefix}/libexec" end def caveats s = "" s += <<-EOS.undent Homebrew did NOT install npm. Please install and configure npm manually. EOS if build.without? "full-icu" s += <<-EOS.undent Please note by default only English locale support is provided. If you need full locale support you should either rebuild with full icu: `brew reinstall node --with-full-icu` or add full icu data at runtime following: https://github.com/nodejs/node/wiki/Intl#using-and-customizing-the-small-icu-build EOS end s end test do path = testpath/"test.js" path.write "console.log('hello');" output = shell_output("#{bin}/node #{path}").strip assert_equal "hello", output output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"en-EN\").format(1234.56))'").strip assert_equal "1,234.56", output if build.with? "full-icu" output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"de-DE\").format(1234.56))'").strip assert_equal "1.234,56", output end end end
############################################################################ # Copyright 2009,2010 Benjamin Kellermann # # # # This file is part of dudle. # # # # Dudle is free software: you can redistribute it and/or modify it under # # the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # Dudle is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # # License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with dudle. If not, see <http://www.gnu.org/licenses/>. # ############################################################################ require "hash" require "yaml" require "time" require "pollhead" require "timepollhead" $KCODE = "u" class String def to_htmlID CGI.escapeHTML(self.gsub(/[^A-Z^a-z^0-9^\-^_^:^\.]/,".")) end end class Poll attr_reader :head, :name YESVAL = "ayes" MAYBEVAL = "bmaybe" NOVAL = "cno" def initialize name,type @name = name case type when "normal" @head = PollHead.new when "time" @head = TimePollHead.new else raise("unknown poll type: #{type}") end @data = {} @comment = [] store "Poll #{name} created" end def sort_data fields if fields.include?("name") until fields.pop == "name" end @data.sort{|x,y| cmp = x[1].compare_by_values(y[1],fields) cmp == 0 ? x[0].downcase <=> y[0].downcase : cmp } else @data.sort{|x,y| x[1].compare_by_values(y[1],fields)} end end def userstring(participant,link) ret = "" ret += "<a title='" + _("Edit user %{user}") % {:user => CGI.escapeHTML(participant)} + "' href=\"?edituser=#{CGI.escapeHTML(CGI.escape(participant))}\">" if link ret += participant ret += "<span class='edituser'> <sup>#{EDIT}</sup></span></a>" if link ret end def to_html(edituser = "", showparticipation = true) ret = "<table border='1'>\n" sortcolumns = $cgi.include?("sort") ? $cgi.params["sort"] : ["timestamp"] ret += @head.to_html(sortcolumns) sort_data(sortcolumns).each{|participant,poll| if edituser == participant ret += participate_to_html(edituser) else ret += "<tr class='participantrow'>\n" ret += "<td class='name'>" ret += userstring(participant,showparticipation) ret += "</td>\n" @head.columns.each{|column| klasse = poll[column] case klasse when nil value = UNKNOWN klasse = "undecided" when YESVAL value = YES when NOVAL value = NO when MAYBEVAL value = MAYBE end ret += "<td class='#{klasse}' title=\"#{CGI.escapeHTML(participant)}: #{CGI.escapeHTML(column.to_s)}\">#{value}</td>\n" } ret += "<td class='date'>#{poll['timestamp'].strftime('%d.%m,&nbsp;%H:%M')}</td>" ret += "</tr>\n" end } # PARTICIPATE ret += participate_to_html(edituser) unless @data.keys.include?(edituser) || !showparticipation # SUMMARY ret += "<tr id='summary'><td class='name'>" + _("total") + "</td>\n" @head.columns.each{|column| yes = 0 undecided = 0 @data.each_value{|participant| if participant[column] == YESVAL yes += 1 elsif !participant.has_key?(column) or participant[column] == MAYBEVAL undecided += 1 end } if @data.empty? percent_f = 0 else percent_f = 100*yes/@data.size end percent = "#{percent_f}%" unless @data.empty? if undecided > 0 percent += "-#{(100.0*(undecided+yes)/@data.size).round}%" end ret += "<td id='sum_#{column.to_htmlID}' class='sum' title='#{percent}' style='" ["","background-"].each {|c| ret += "#{c}color: rgb(" 3.times{ ret += (c == "" ? "#{155+percent_f}" : "#{100-percent_f}") ret += "," } ret.chop! ret += ");" } ret += "'>#{yes}</td>\n" } ret += "<td class='invisible'></td></tr>" ret += "</table>\n" ret end def invite_to_html(edituser) invitestr = _("Invite") namestr = _("Name") ret = <<HEAD <table id='participanttable' class='settingstable'> <tr> <th>#{namestr}</th> </tr> HEAD @data.keys.sort.each{|participant| has_voted = false @head.columns.each{|column| has_voted = true unless @data[participant][column].nil? } if edituser == participant ret += "<tr id='add_participant_row'>" ret += add_participant_input(edituser) ret += save_input(edituser,invitestr) else ret += "<tr class='participantrow'>" ret += "<td class='name'>" ret += userstring(participant,!has_voted) ret += "</td>" end ret += "</tr>" } unless @data.keys.include?(edituser) ret += "<tr id='add_participant_row'>" ret += add_participant_input(edituser) ret += save_input(edituser,invitestr) ret += "</tr>" end ret += "</table>" ret end def add_participant_input(edituser) return <<END <td id='add_participant_input_td'> <input type='hidden' name='olduser' value=\"#{edituser}\" /> <input size='16' type='text' name='add_participant' id='add_participant_input' value="#{edituser}"/> </td> END end def save_input(edituser, savestring) ret = "<td>" if @data.include?(edituser) ret += "<input id='savebutton' type='submit' value='" + _("Save Changes") + "' />" ret += "<br /><input style='margin-top:1ex' type='submit' name='delete_participant' value='" + _("Delete User") + "' />" else ret += "<input id='savebutton' type='submit' value='#{savestring}' />" end ret += "</td>\n" end def participate_to_html(edituser) checked = {} if @data.include?(edituser) @head.columns.each{|k| checked[k] = @data[edituser][k]} else edituser = $cgi.cookies["username"][0] unless @data.include?($cgi.cookies["username"][0]) @head.columns.each{|k| checked[k] = NOVAL} end ret = "<tr id='separator_top'><td colspan='#{@head.col_size + 2}' class='invisible'></td></tr>\n" ret += "<tr id='add_participant'>\n" ret += add_participant_input(edituser) @head.columns.each{|column| ret += "<td class='checkboxes'><table class='checkboxes'>" [[YES, YESVAL],[NO, NOVAL],[MAYBE, MAYBEVAL]].each{|valhuman, valbinary| ret += <<TR <tr class='input-#{valbinary}'> <td class='input-#{valbinary}'> <input type='radio' value='#{valbinary}' id=\"add_participant_checked_#{column.to_htmlID}_#{valbinary}\" name=\"add_participant_checked_#{CGI.escapeHTML(column.to_s)}\" title=\"#{CGI.escapeHTML(column.to_s)}\" #{checked[column] == valbinary ? "checked='checked'":""}/> </td> <td class='input-#{valbinary}'> <label for=\"add_participant_checked_#{column.to_htmlID}_#{valbinary}\">#{valhuman}</label> </td> </tr> TR } ret += "</table></td>" } ret += save_input(edituser, _("Save")) ret += "</tr>\n" ret += "<tr id='separator_bottom'><td colspan='#{@head.col_size + 2}' class='invisible'></td></tr>\n" ret end def comment_to_html(editable = true) ret = "<div id='comments'>" ret += "<h2>" + _("Comments") + "</h2>" if !@comment.empty? || editable unless @comment.empty? @comment.each_with_index{|c,i| time,name,comment = c ret += "<form method='post' action='.'>" ret += "<div class='textcolumn'><h3 class='comment'>" ret += _("%{user} said on %{time}") % {:user => name, :time => time.strftime("%d.%m., %H:%M")} if editable ret += "<input type='hidden' name='delete_comment' value='#{i}' />" ret += "&nbsp;" ret += "<input class='delete_comment_button' type='submit' value='" ret += _("Delete") ret += "' />" end ret += "</h3>#{comment}</div>" ret += "</form>" } end if editable # ADD COMMENT saysstr = _("says") submitstr = _("Submit Comment") ret += <<ADDCOMMENT <form method='post' action='.' accept-charset='utf-8'> <div class='comment' id='add_comment'> <input value='#{$cgi.cookies["username"][0] || "Anonymous"}' type='text' name='commentname' size='9' /> #{saysstr}&nbsp; <br /> <textarea cols='50' rows='7' name='comment' ></textarea> <br /><input type='submit' value='#{submitstr}' /> </div> </form> ADDCOMMENT end ret += "</div>\n" ret end def history_selectform(revision, selected) showhiststr = _("Show history items:") ret = <<FORM <form method='get' action=''> <div> #{showhiststr} <select name='history'> FORM [["",_("All")], ["participants",_("Participant related")], ["columns",_("Column related")], ["comments",_("Comment related")], ["ac",_("Access Control related")] ].each{|value,opt| ret += "<option value='#{value}' #{selected == value ? "selected='selected'" : ""} >#{opt}</option>" } ret += "</select>" ret += "<input type='hidden' name='revision' value='#{revision}' />" if revision updatestr = _("Update") ret += <<FORM <input type='submit' value='#{updatestr}' /> </div> </form> FORM ret end def history_to_html(middlerevision,only) log = VCS.history if only != "" case only when "comments" match = /^Comment .*$/ when "participants" match = /^Participant .*$/ when "columns" match = /^Column .*$/ when "ac" match = /^Access Control .*$/ else raise "invalid value #{only}" end log = log.comment_matches(match) end log.around_rev(middlerevision,11).to_html(middlerevision,only) end def add_participant(olduser, name, agreed) name.strip! if name == "" maximum = @data.keys.collect{|e| e.scan(/^Anonymous #(\d*)/).flatten[0]}.compact.collect{|i| i.to_i}.max maximum ||= 0 name = "Anonymous ##{maximum + 1}" end htmlname = CGI.escapeHTML(name) action = '' if @data.delete(CGI.escapeHTML(olduser)) action = "edited" else action = "added" end @data[htmlname] = {"timestamp" => Time.now } @head.columns.each{|column| @data[htmlname][column] = agreed[column.to_s] } store "Participant #{name.strip} #{action}" end def delete(name) htmlname = CGI.escapeHTML(name.strip) if @data.has_key?(htmlname) @data.delete(htmlname) store "Participant #{name.strip} deleted" end end def store comment File.open("data.yaml", 'w') do |out| out << "# This is a dudle poll file\n" out << self.to_yaml out.chmod(0660) end VCS.commit(CGI.escapeHTML(comment)) end ############################### # comment related functions ############################### def add_comment name, comment @comment << [Time.now, CGI.escapeHTML(name.strip), CGI.escapeHTML(comment.strip).gsub("\r\n","<br />")] store "Comment added by #{name}" end def delete_comment index store "Comment from #{@comment.delete_at(index)[1]} deleted" end ############################### # column related functions ############################### def delete_column column if @head.delete_column(column) store "Column #{column} deleted" return true else return false end end def edit_column(oldcolumn, newtitle, cgi) parsedtitle = @head.edit_column(oldcolumn, newtitle, cgi) store "Column #{parsedtitle} #{oldcolumn == "" ? "added" : "edited"}" if parsedtitle end def edit_column_htmlform(activecolumn, revision) @head.edit_column_htmlform(activecolumn, revision) end end if __FILE__ == $0 require 'test/unit' require 'cgi' require 'pp' SITE = "glvhc_8nuv_8fchi09bb12a-23_uvc" class Poll attr_accessor :head, :data, :comment def store comment end end #┌───────────────────┬─────────────────────────────────┬────────────┐ #│ │ May 2009 │ │ #├───────────────────┼────────┬────────────────────────┼────────────┤ #│ │Tue, 05 │ Sat, 23 │ │ #├───────────────────┼────────┼────────┬────────┬──────┼────────────┤ #│ Name ▾▴ │ ▾▴ │10:00 ▾▴│11:00 ▾▴│foo ▾▴│Last Edit ▾▴│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Alice ^✍ │✔ │✘ │✔ │✘ │24.11, 18:15│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Bob ^✍ │✔ │✔ │✘ │? │24.11, 18:15│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Dave ^✍ │✘ │? │✔ │✔ │24.11, 18:16│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Carol ^✍ │✔ │✔ │? │✘ │24.11, 18:16│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│total │3 │2 │2 │1 │ │ #└───────────────────┴────────┴────────┴────────┴──────┴────────────┘ class PollTest < Test::Unit::TestCase Y,N,M = Poll::YESVAL, Poll::NOVAL, Poll::MAYBEVAL A,B,C,D = "Alice", "Bob", "Carol", "Dave" Q,W,E,R = "2009-05-05", "2009-05-23 10:00", "2009-05-23 11:00", "2009-05-23 foo" def setup def add_participant(type,user,votearray) h = { Q => votearray[0], W => votearray[1], E => votearray[2], R => votearray[3]} @polls[type].add_participant("",user,h) end @polls = {} ["time","normal"].each{|type| @polls[type] = Poll.new(SITE, type) @polls[type].edit_column("","2009-05-05", {"columndescription" => ""}) 2.times{|t| @polls[type].edit_column("","2009-05-23 #{t+10}:00", {"columntime" => "#{t+10}:00","columndescription" => ""}) } @polls[type].edit_column("","2009-05-23 foo", {"columntime" => "foo","columndescription" => ""}) add_participant(type,A,[Y,N,Y,N]) add_participant(type,B,[Y,Y,N,M]) add_participant(type,D,[N,M,Y,Y]) add_participant(type,C,[Y,Y,M,N]) } end def test_sort ["time","normal"].each{|type| comment = "Test Type: #{type}" assert_equal([A,B,C,D],@polls[type].sort_data(["name"]).collect{|a| a[0]},comment) assert_equal([A,B,D,C],@polls[type].sort_data(["timestamp"]).collect{|a| a[0]},comment) assert_equal([B,C,D,A],@polls[type].sort_data([W,"name"]).collect{|a| a[0]},comment) assert_equal([B,A,C,D],@polls[type].sort_data([Q,R,E]).collect{|a| a[0]},comment+ " " + [Q,R,E].join("; ")) } end end end regex conformity ############################################################################ # Copyright 2009,2010 Benjamin Kellermann # # # # This file is part of dudle. # # # # Dudle is free software: you can redistribute it and/or modify it under # # the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # Dudle is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # # License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with dudle. If not, see <http://www.gnu.org/licenses/>. # ############################################################################ require "hash" require "yaml" require "time" require "pollhead" require "timepollhead" $KCODE = "u" class String def to_htmlID CGI.escapeHTML(self.gsub(/[^A-Za-z0-9_:.\-]/,".")) end end class Poll attr_reader :head, :name YESVAL = "ayes" MAYBEVAL = "bmaybe" NOVAL = "cno" def initialize name,type @name = name case type when "normal" @head = PollHead.new when "time" @head = TimePollHead.new else raise("unknown poll type: #{type}") end @data = {} @comment = [] store "Poll #{name} created" end def sort_data fields if fields.include?("name") until fields.pop == "name" end @data.sort{|x,y| cmp = x[1].compare_by_values(y[1],fields) cmp == 0 ? x[0].downcase <=> y[0].downcase : cmp } else @data.sort{|x,y| x[1].compare_by_values(y[1],fields)} end end def userstring(participant,link) ret = "" ret += "<a title='" + _("Edit user %{user}") % {:user => CGI.escapeHTML(participant)} + "' href=\"?edituser=#{CGI.escapeHTML(CGI.escape(participant))}\">" if link ret += participant ret += "<span class='edituser'> <sup>#{EDIT}</sup></span></a>" if link ret end def to_html(edituser = "", showparticipation = true) ret = "<table border='1'>\n" sortcolumns = $cgi.include?("sort") ? $cgi.params["sort"] : ["timestamp"] ret += @head.to_html(sortcolumns) sort_data(sortcolumns).each{|participant,poll| if edituser == participant ret += participate_to_html(edituser) else ret += "<tr class='participantrow'>\n" ret += "<td class='name'>" ret += userstring(participant,showparticipation) ret += "</td>\n" @head.columns.each{|column| klasse = poll[column] case klasse when nil value = UNKNOWN klasse = "undecided" when YESVAL value = YES when NOVAL value = NO when MAYBEVAL value = MAYBE end ret += "<td class='#{klasse}' title=\"#{CGI.escapeHTML(participant)}: #{CGI.escapeHTML(column.to_s)}\">#{value}</td>\n" } ret += "<td class='date'>#{poll['timestamp'].strftime('%d.%m,&nbsp;%H:%M')}</td>" ret += "</tr>\n" end } # PARTICIPATE ret += participate_to_html(edituser) unless @data.keys.include?(edituser) || !showparticipation # SUMMARY ret += "<tr id='summary'><td class='name'>" + _("total") + "</td>\n" @head.columns.each{|column| yes = 0 undecided = 0 @data.each_value{|participant| if participant[column] == YESVAL yes += 1 elsif !participant.has_key?(column) or participant[column] == MAYBEVAL undecided += 1 end } if @data.empty? percent_f = 0 else percent_f = 100*yes/@data.size end percent = "#{percent_f}%" unless @data.empty? if undecided > 0 percent += "-#{(100.0*(undecided+yes)/@data.size).round}%" end ret += "<td id='sum_#{column.to_htmlID}' class='sum' title='#{percent}' style='" ["","background-"].each {|c| ret += "#{c}color: rgb(" 3.times{ ret += (c == "" ? "#{155+percent_f}" : "#{100-percent_f}") ret += "," } ret.chop! ret += ");" } ret += "'>#{yes}</td>\n" } ret += "<td class='invisible'></td></tr>" ret += "</table>\n" ret end def invite_to_html(edituser) invitestr = _("Invite") namestr = _("Name") ret = <<HEAD <table id='participanttable' class='settingstable'> <tr> <th>#{namestr}</th> </tr> HEAD @data.keys.sort.each{|participant| has_voted = false @head.columns.each{|column| has_voted = true unless @data[participant][column].nil? } if edituser == participant ret += "<tr id='add_participant_row'>" ret += add_participant_input(edituser) ret += save_input(edituser,invitestr) else ret += "<tr class='participantrow'>" ret += "<td class='name'>" ret += userstring(participant,!has_voted) ret += "</td>" end ret += "</tr>" } unless @data.keys.include?(edituser) ret += "<tr id='add_participant_row'>" ret += add_participant_input(edituser) ret += save_input(edituser,invitestr) ret += "</tr>" end ret += "</table>" ret end def add_participant_input(edituser) return <<END <td id='add_participant_input_td'> <input type='hidden' name='olduser' value=\"#{edituser}\" /> <input size='16' type='text' name='add_participant' id='add_participant_input' value="#{edituser}"/> </td> END end def save_input(edituser, savestring) ret = "<td>" if @data.include?(edituser) ret += "<input id='savebutton' type='submit' value='" + _("Save Changes") + "' />" ret += "<br /><input style='margin-top:1ex' type='submit' name='delete_participant' value='" + _("Delete User") + "' />" else ret += "<input id='savebutton' type='submit' value='#{savestring}' />" end ret += "</td>\n" end def participate_to_html(edituser) checked = {} if @data.include?(edituser) @head.columns.each{|k| checked[k] = @data[edituser][k]} else edituser = $cgi.cookies["username"][0] unless @data.include?($cgi.cookies["username"][0]) @head.columns.each{|k| checked[k] = NOVAL} end ret = "<tr id='separator_top'><td colspan='#{@head.col_size + 2}' class='invisible'></td></tr>\n" ret += "<tr id='add_participant'>\n" ret += add_participant_input(edituser) @head.columns.each{|column| ret += "<td class='checkboxes'><table class='checkboxes'>" [[YES, YESVAL],[NO, NOVAL],[MAYBE, MAYBEVAL]].each{|valhuman, valbinary| ret += <<TR <tr class='input-#{valbinary}'> <td class='input-#{valbinary}'> <input type='radio' value='#{valbinary}' id=\"add_participant_checked_#{column.to_htmlID}_#{valbinary}\" name=\"add_participant_checked_#{CGI.escapeHTML(column.to_s)}\" title=\"#{CGI.escapeHTML(column.to_s)}\" #{checked[column] == valbinary ? "checked='checked'":""}/> </td> <td class='input-#{valbinary}'> <label for=\"add_participant_checked_#{column.to_htmlID}_#{valbinary}\">#{valhuman}</label> </td> </tr> TR } ret += "</table></td>" } ret += save_input(edituser, _("Save")) ret += "</tr>\n" ret += "<tr id='separator_bottom'><td colspan='#{@head.col_size + 2}' class='invisible'></td></tr>\n" ret end def comment_to_html(editable = true) ret = "<div id='comments'>" ret += "<h2>" + _("Comments") + "</h2>" if !@comment.empty? || editable unless @comment.empty? @comment.each_with_index{|c,i| time,name,comment = c ret += "<form method='post' action='.'>" ret += "<div class='textcolumn'><h3 class='comment'>" ret += _("%{user} said on %{time}") % {:user => name, :time => time.strftime("%d.%m., %H:%M")} if editable ret += "<input type='hidden' name='delete_comment' value='#{i}' />" ret += "&nbsp;" ret += "<input class='delete_comment_button' type='submit' value='" ret += _("Delete") ret += "' />" end ret += "</h3>#{comment}</div>" ret += "</form>" } end if editable # ADD COMMENT saysstr = _("says") submitstr = _("Submit Comment") ret += <<ADDCOMMENT <form method='post' action='.' accept-charset='utf-8'> <div class='comment' id='add_comment'> <input value='#{$cgi.cookies["username"][0] || "Anonymous"}' type='text' name='commentname' size='9' /> #{saysstr}&nbsp; <br /> <textarea cols='50' rows='7' name='comment' ></textarea> <br /><input type='submit' value='#{submitstr}' /> </div> </form> ADDCOMMENT end ret += "</div>\n" ret end def history_selectform(revision, selected) showhiststr = _("Show history items:") ret = <<FORM <form method='get' action=''> <div> #{showhiststr} <select name='history'> FORM [["",_("All")], ["participants",_("Participant related")], ["columns",_("Column related")], ["comments",_("Comment related")], ["ac",_("Access Control related")] ].each{|value,opt| ret += "<option value='#{value}' #{selected == value ? "selected='selected'" : ""} >#{opt}</option>" } ret += "</select>" ret += "<input type='hidden' name='revision' value='#{revision}' />" if revision updatestr = _("Update") ret += <<FORM <input type='submit' value='#{updatestr}' /> </div> </form> FORM ret end def history_to_html(middlerevision,only) log = VCS.history if only != "" case only when "comments" match = /^Comment .*$/ when "participants" match = /^Participant .*$/ when "columns" match = /^Column .*$/ when "ac" match = /^Access Control .*$/ else raise "invalid value #{only}" end log = log.comment_matches(match) end log.around_rev(middlerevision,11).to_html(middlerevision,only) end def add_participant(olduser, name, agreed) name.strip! if name == "" maximum = @data.keys.collect{|e| e.scan(/^Anonymous #(\d*)/).flatten[0]}.compact.collect{|i| i.to_i}.max maximum ||= 0 name = "Anonymous ##{maximum + 1}" end htmlname = CGI.escapeHTML(name) action = '' if @data.delete(CGI.escapeHTML(olduser)) action = "edited" else action = "added" end @data[htmlname] = {"timestamp" => Time.now } @head.columns.each{|column| @data[htmlname][column] = agreed[column.to_s] } store "Participant #{name.strip} #{action}" end def delete(name) htmlname = CGI.escapeHTML(name.strip) if @data.has_key?(htmlname) @data.delete(htmlname) store "Participant #{name.strip} deleted" end end def store comment File.open("data.yaml", 'w') do |out| out << "# This is a dudle poll file\n" out << self.to_yaml out.chmod(0660) end VCS.commit(CGI.escapeHTML(comment)) end ############################### # comment related functions ############################### def add_comment name, comment @comment << [Time.now, CGI.escapeHTML(name.strip), CGI.escapeHTML(comment.strip).gsub("\r\n","<br />")] store "Comment added by #{name}" end def delete_comment index store "Comment from #{@comment.delete_at(index)[1]} deleted" end ############################### # column related functions ############################### def delete_column column if @head.delete_column(column) store "Column #{column} deleted" return true else return false end end def edit_column(oldcolumn, newtitle, cgi) parsedtitle = @head.edit_column(oldcolumn, newtitle, cgi) store "Column #{parsedtitle} #{oldcolumn == "" ? "added" : "edited"}" if parsedtitle end def edit_column_htmlform(activecolumn, revision) @head.edit_column_htmlform(activecolumn, revision) end end if __FILE__ == $0 require 'test/unit' require 'cgi' require 'pp' SITE = "glvhc_8nuv_8fchi09bb12a-23_uvc" class Poll attr_accessor :head, :data, :comment def store comment end end #┌───────────────────┬─────────────────────────────────┬────────────┐ #│ │ May 2009 │ │ #├───────────────────┼────────┬────────────────────────┼────────────┤ #│ │Tue, 05 │ Sat, 23 │ │ #├───────────────────┼────────┼────────┬────────┬──────┼────────────┤ #│ Name ▾▴ │ ▾▴ │10:00 ▾▴│11:00 ▾▴│foo ▾▴│Last Edit ▾▴│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Alice ^✍ │✔ │✘ │✔ │✘ │24.11, 18:15│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Bob ^✍ │✔ │✔ │✘ │? │24.11, 18:15│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Dave ^✍ │✘ │? │✔ │✔ │24.11, 18:16│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│Carol ^✍ │✔ │✔ │? │✘ │24.11, 18:16│ #├───────────────────┼────────┼────────┼────────┼──────┼────────────┤ #│total │3 │2 │2 │1 │ │ #└───────────────────┴────────┴────────┴────────┴──────┴────────────┘ class PollTest < Test::Unit::TestCase Y,N,M = Poll::YESVAL, Poll::NOVAL, Poll::MAYBEVAL A,B,C,D = "Alice", "Bob", "Carol", "Dave" Q,W,E,R = "2009-05-05", "2009-05-23 10:00", "2009-05-23 11:00", "2009-05-23 foo" def setup def add_participant(type,user,votearray) h = { Q => votearray[0], W => votearray[1], E => votearray[2], R => votearray[3]} @polls[type].add_participant("",user,h) end @polls = {} ["time","normal"].each{|type| @polls[type] = Poll.new(SITE, type) @polls[type].edit_column("","2009-05-05", {"columndescription" => ""}) 2.times{|t| @polls[type].edit_column("","2009-05-23 #{t+10}:00", {"columntime" => "#{t+10}:00","columndescription" => ""}) } @polls[type].edit_column("","2009-05-23 foo", {"columntime" => "foo","columndescription" => ""}) add_participant(type,A,[Y,N,Y,N]) add_participant(type,B,[Y,Y,N,M]) add_participant(type,D,[N,M,Y,Y]) add_participant(type,C,[Y,Y,M,N]) } end def test_sort ["time","normal"].each{|type| comment = "Test Type: #{type}" assert_equal([A,B,C,D],@polls[type].sort_data(["name"]).collect{|a| a[0]},comment) assert_equal([A,B,D,C],@polls[type].sort_data(["timestamp"]).collect{|a| a[0]},comment) assert_equal([B,C,D,A],@polls[type].sort_data([W,"name"]).collect{|a| a[0]},comment) assert_equal([B,A,C,D],@polls[type].sort_data([Q,R,E]).collect{|a| a[0]},comment+ " " + [Q,R,E].join("; ")) } end end end
rxvt 2.6.4 (new formula) class Rxvt < Formula desc "Classic VT102 terminal emulator for X11" homepage "http://rxvt.sourceforge.net/" url "https://downloads.sourceforge.net/project/rxvt/rxvt/2.6.4/rxvt-2.6.4.tar.gz" sha256 "af0b90bb4d563aafeabcb4c237bd66668740743531e025a70d61a32d214f2242" devel do url "https://downloads.sourceforge.net/project/rxvt/rxvt-dev/2.7.10/rxvt-2.7.10.tar.gz" sha256 "616ad56502820264e6933d07bc4eb752aa6940ec14add6e780ffccf15f38d449" end depends_on :x11 def install args = %W[ --prefix=#{prefix} --mandir=#{man} --enable-xpm-background --enable-transparency --enable-menubar --enable-kanji --enable-graphics --enable-xim --enable-xgetdefault --with-terminfo=#{pkgshare}/terminfo --with-term=rxvt ] if build.devel? more_args = %W[ --enable-languages --enable-rxvt-scroll --enable-xterm-scroll --enable-next-scroll --enable-frills --enable-linespace --enable-24bit --enable-smart-resize --enable-256-color --with-xpm ] args.push(*more_args) end system "./configure", *args system "make", "install" end test do assert_match "Usage", shell_output("#{bin}/rxvt -help 2>&1 | cat") end end
class Scio < Formula desc "Scala API for Google Cloud Dataflow and Apache Beam" homepage "https://github.com/spotify/scio/" url "https://github.com/spotify/scio/releases/download/v0.4.1/scio-repl-0.4.1.jar" sha256 "08ab8d9bf8fffae6229f4435d82fb1b6965641c7144577abd2f739ec4cd2967b" bottle :unneeded def install libexec.install "scio-repl-#{version}.jar" (bin+"scio-repl").write <<-EOS.undent #!/bin/bash java_opts=() scio_opts=() for o in "$@"; do if [[ "$o" =~ ^-D.* || "$o" =~ ^-X.* ]]; then java_opts+=("$o") else scio_opts+=("$o") fi done CLASSPATH="#{libexec}/scio-repl-#{version}.jar"${CLASSPATH:+:${CLASSPATH}} exec java ${java_opts[*]} com.spotify.scio.repl.ScioShell ${scio_opts[*]} EOS end test do shell_output("#{bin}/scio-repl -Y", 1) end end Use env bash class Scio < Formula desc "Scala API for Google Cloud Dataflow and Apache Beam" homepage "https://github.com/spotify/scio/" url "https://github.com/spotify/scio/releases/download/v0.4.1/scio-repl-0.4.1.jar" sha256 "08ab8d9bf8fffae6229f4435d82fb1b6965641c7144577abd2f739ec4cd2967b" bottle :unneeded def install libexec.install "scio-repl-#{version}.jar" (bin+"scio-repl").write <<-EOS.undent #!/usr/bin/env bash java_opts=() scio_opts=() for o in "$@"; do if [[ "$o" =~ ^-D.* || "$o" =~ ^-X.* ]]; then java_opts+=("$o") else scio_opts+=("$o") fi done CLASSPATH="#{libexec}/scio-repl-#{version}.jar"${CLASSPATH:+:${CLASSPATH}} exec java ${java_opts[*]} com.spotify.scio.repl.ScioShell ${scio_opts[*]} EOS end test do shell_output("#{bin}/scio-repl -Y", 1) end end
Add initial seed… let the fertilisation begin… in_thread do loop do sample :drum_cymbal_closed, rate: 0.9, amp: 0.4 sleep 0.25 end end in_thread do loop do sample :drum_bass_hard sleep 1.25 sample :drum_bass_hard sleep 0.75 end end in_thread do use_synth :tb303 with_fx :echo do loop do play_pattern_timed [50, 52, 55, 59], [1, 0.5], amp: 0.3 sleep 3 end end end
require 'rubygems' require 'bundler/setup' require 'sinatra' require 'haml' require 'rack-canonical-host' require 'sinatra/r18n' require './rk2gpx' LANGS = %w( en nl ) HOST = nil if settings.environment == :production HOST = 'rk2gpx.hyzkia.com' end use Rack::CanonicalHost, HOST unless HOST.nil? set :erb, :layout => :'layout.html' set :default_locale, 'en-gb' helpers do include Rack::Utils alias_method :h, :escape_html def host settings.environment == :production ? 'rk2gpx.hyzkia.com' : 'localhost:9292' end def bookmarklet "(function(){var d=document,s=d.createElement('script');s.setAttribute('src','http://#{host}/bm.js');d.body.appendChild(s);})()" end def with_route json = params[:json] json.nil? ? nil : Route.from_json(json) end end get '/' do erb :'index.html' end get '/bm.js' do erb :'bm.js', :layout => false end post '/route' do with_route erb :'route.html' end post '/route.gpx' do with_route content_type 'application/gpx+xml', :charset => 'utf-8' attachment "#{@route.title}.gpx" haml :'route.gpx' end Fixed default locale require 'rubygems' require 'bundler/setup' require 'sinatra' require 'haml' require 'rack-canonical-host' require 'sinatra/r18n' require './rk2gpx' HOST = nil if settings.environment == :production HOST = 'rk2gpx.hyzkia.com' end use Rack::CanonicalHost, HOST unless HOST.nil? set :erb, :layout => :'layout.html' set :default_locale, 'en' helpers do include Rack::Utils alias_method :h, :escape_html def host settings.environment == :production ? 'rk2gpx.hyzkia.com' : 'localhost:9292' end def bookmarklet "(function(){var d=document,s=d.createElement('script');s.setAttribute('src','http://#{host}/bm.js');d.body.appendChild(s);})()" end def with_route json = params[:json] json.nil? ? nil : Route.from_json(json) end end get '/' do erb :'index.html' end get '/bm.js' do erb :'bm.js', :layout => false end post '/route' do with_route erb :'route.html' end post '/route.gpx' do with_route content_type 'application/gpx+xml', :charset => 'utf-8' attachment "#{@route.title}.gpx" haml :'route.gpx' end
#!/usr/bin/env ruby require 'cgi' require 'digest/md5' class Markup attr_accessor :layout def initialize clear end def ok? @errors.empty? end def errors @errors.dup end def out tpl_out = template_replace(@layout, { :content => @content.join("\n"), :toc => @toc.join("\n"), :toc_no_heading => @toc_nh.join("\n"), :title => @title, :now => escape(@now.to_s), :now_numeric => escape(@now.strftime("%Y-%m-%d %H:%M:%S")), :filename => @filename, }) unless @code_lang_used tpl_out. gsub!(/<!-- s:HILITE \{\{\{ -->.*<!-- e:HILITE \}\}\} -->\s*/m, '') end tpl_out end def process(file) clear @filename = File.basename(file.path) #.sub(/\.[^.]{3,4}$/,'') @line = 0 file.each do |ln| ln.chomp! @line += 1 type = typeof(ln) case type when :title @title = title(ln) when :heading flush @content << "" @content << heading(ln) when :list cond_switch_state(:list) @current << list_item(ln) when :def_list cond_switch_state(:def_list) @current << def_list_item(ln) when :end flush when :text cond_switch_state(:text) @current << text_line(ln) when :code cond_switch_state(:code) or @current << code_line(ln) when :img cond_switch_state(:text) @current << img(ln) when :comment else @errors << "Something weird at line: #{@line}" end end flush generate_toc end private def clear @content = [] @toc = [] @toc_nh = [] @toc_data = [] @state = :end @errors = [] @current = [] @layout ||= DATA.read @now = Time.now @title = "Unnamed spec ({{{{FILENAME}}}})" @filename = "?" @heading_base = 1 @code_lang = nil @code_lang_used = false end def template_replace(where, what) what.each do |k, v| where.gsub!(Regexp.new(Regexp.escape("{{" + "{{#{k.to_s}}}" + "}}"), Regexp::IGNORECASE), v.gsub(/\\/, '\\\\\\\\')) end where end def title(ln) @title = escape(ln.sub(/^!\s+/,'')) end def cond_switch_state(st) unless @state == st flush @state = st true else false end end def generate_toc level = 0 @toc << "<h#{@heading_base + 1}>Table of contents</h#{@heading_base + 1}>" (@toc_data + [[0, nil, nil]]).each do |lev, entry, key| case level <=> lev when -1 (lev-level).times do |i| l = (lev + i - 1) if l.zero? @toc_nh << (" " * l) + "<ul>" else @toc_nh << (" " * l) + "<li style='list-style-type: none;'><ul>" end end when 0 # nothing when 1 (level-lev).times do |i| l = (level - i - 1) if l.zero? @toc_nh << (" " * l) + "</ul>" else @toc_nh << (" " * l) + "</ul></li>" end end end level = lev @toc_nh << (" " * lev) + '<li><a href="#' + key + '">' + entry + '</a></li>' unless key.nil? || entry.nil? end @toc_nh << "" @toc += @toc_nh end def heading(ln) ar = ln.split(/^(=+\s+)/) if ar.size == 3 && ar[0].empty? sz = ar[1].strip.size cont = ar[2] id = ::Digest::MD5.hexdigest(@toc_data.size.to_s + sz.to_s + cont) @toc_data << [ar[1].strip.size, ar[2], id] "<h#{@heading_base + sz}>" + "<a name='#{id}'></a>" + cont + "</h#{@heading_base + sz}>" else @errors << "BUG: Heading assertion failed (#{@line})" "" end end def flush case @state when :text @content << "<p>\n" + @current.join("\n") + "\n</p>" when :list @content << "<ul>\n" + @current.join("\n") + "\n</ul>" when :def_list @content << "<dl>\n" + @current.join("\n") + "\n</dl>" when :code if @code_lang.empty? @content << "<pre>\n" + @current.join("\n") + "\n</pre>" else @content << "<pre class=\"highlight language-#{@code_lang}\">\n" + @current.join("\n") + "\n</pre>" @code_lang_used = true end when :end # nothing to do ... :) else @errors << "Some weird state encountered around line: #{@line}" end @current = [] @state = :end end def def_list_item(ln) ar = ln.split(/^(:\s*)(.*?)(\s*=\s*)(.*)/) if ar.size == 5 && ar[0] == "" && ar[1] =~ /:\s*/ && ar[3] =~ /\s*=\s*/ "<dt>" + escape(ar[2]) + "</dt>\n<dd>" + escape(ar[4]) + "</dd>" else @errors << "BUG: Def_list_item assertion failed (#{@line})" "" end end def text_line(ln) out = [] while (ln =~ /("[^"]*?"|[^\s]+)\<((ftp|https?|mailto|news|irc|REL):.*?)\>/) pre, label, url, post = $`, $1, $2, $' label = label[1..-2] if label =~ /^".*"$/ url = url[4..-1] if url =~ /^REL:/ out << escape(pre) out << "<a href=\"#{url}\">#{label}</a>" ln = post end out << escape(ln) out.join end def img(ln) ar = ln.split(/\s+/) ar.shift out = [] out << "<img src=\"#{ar.first}\"" ar.shift out << "style=\"#{ar.join(' ')}\"" unless ar.join(' ').empty? out << "/>" out.join(' ') end def code_line(ln) CGI.escapeHTML(ln) end def list_item(ln) ar = ln.split(/^(\*\s+)/) if ar.size == 3 && ar[0].empty? "<li>" + escape(ar[2]) + "</li>" else @errors << "BUG: List_item assertion failed (#{@line})" "" end end def escape(what) CGI.escapeHTML(what). gsub(/`(.*?)`/) { "<code>" + $1.gsub(/~/, '&#96;') + "</code>" }. gsub(/~/, '&nbsp;') end def typeof(ln) if @state == :code case ln when /^\}\}\}$/ :end else :code end else case ln when /^!\s+/ if @content.empty? :title else :text end when /^=/ :heading when /^\*/ :list when /^:/ :def_list when /^$/, /^\s+$/ :end when /^\{\{\{(.*)/ @code_lang = $1.strip :code when /^@/ :img when /^#/ :comment else :text end end end end if ARGV.size != 1 && ARGV.size != 2 puts "Usage: #$0 <input_file> [output_file]" exit 1 end begin out = ARGV[1].nil? ? $stdout : File.open(ARGV[1], 'w') rescue $stderr.puts "Unable to open output file: #$!" exit 1 end content = [] m = Markup.new ['layout.spec', ARGV[0].gsub(/\.[^.]+$/, '') + '.lsp'].each do |file| if FileTest.exists?(file) m.layout = File.open(file, 'r').read break end end File.open(ARGV[0]) do |f| m.process(f) end if m.ok? out.puts m.out exit 0 else $stderr.puts "Error:" $stderr.puts m.errors.join("\n") exit 1 end __END__ <!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" /> <title>{{{{TITLE}}}}</title> <!-- s:HILITE {{{ --> <!-- github hilite stylesheet --> <link rel="stylesheet" href="data:text/css;base64, LyoKCmdpdGh1Yi5jb20gc3R5bGUgKGMpIFZhc2lseSBQb2xvdm55b3YgPHZh c3RAd2hpdGVhbnRzLm5ldD4KCiovCgpwcmUgY29kZSB7CiAgZGlzcGxheTog YmxvY2s7IHBhZGRpbmc6IDAuNWVtOwogIGNvbG9yOiAjMDAwOwogIGJhY2tn cm91bmQ6ICNmOGY4ZmYKfQoKcHJlIC5jb21tZW50LApwcmUgLnRlbXBsYXRl X2NvbW1lbnQsCnByZSAuZGlmZiAuaGVhZGVyLApwcmUgLmphdmFkb2Mgewog IGNvbG9yOiAjOTk4OwogIGZvbnQtc3R5bGU6IGl0YWxpYwp9CgpwcmUgLmtl eXdvcmQsCnByZSAuY3NzIC5ydWxlIC5rZXl3b3JkLApwcmUgLndpbnV0aWxz LApwcmUgLmphdmFzY3JpcHQgLnRpdGxlLApwcmUgLmxpc3AgLnRpdGxlLApw cmUgLm5naW54IC50aXRsZSwKcHJlIC5zdWJzdCwKcHJlIC5yZXF1ZXN0LApw cmUgLnN0YXR1cyB7CiAgY29sb3I6ICMwMDA7CiAgZm9udC13ZWlnaHQ6IGJv bGQKfQoKcHJlIC5udW1iZXIsCnByZSAuaGV4Y29sb3IgewogIGNvbG9yOiAj NDBhMDcwCn0KCnByZSAuc3RyaW5nLApwcmUgLnRhZyAudmFsdWUsCnByZSAu cGhwZG9jLApwcmUgLnRleCAuZm9ybXVsYSB7CiAgY29sb3I6ICNkMTQKfQoK cHJlIC50aXRsZSwKcHJlIC5pZCB7CiAgY29sb3I6ICM5MDA7CiAgZm9udC13 ZWlnaHQ6IGJvbGQKfQoKcHJlIC5qYXZhc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bGlzdHxxdWV1ZXxzdGFja3x2ZWN0b3J8bWFw fHNldHxiaXRzZXR8bXVsdGlzZXR8bXVsdGltYXB8dW5vcmRlcmVkX21hcHx1 bm9yZGVyZWRfc2V0fHVub3JkZXJlZF9tdWx0aXNldHx1bm9yZGVyZWRfbXVs dGltYXB8YXJyYXkpXFxzKjwiLGU6Ij4iLGs6YixyOjEwLGM6WyJzZWxmIl19 XX19fShobGpzKTs="></script> <script type="text/javascript"> window.onload = function() { // jQuery: $(function(){ $('pre.highlight').each(function(i, e) {hljs.highlightBlock(e)}); }); var objects = document.evaluate('//pre[contains(@class, "highlight")]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < objects.snapshotLength; i++) { hljs.highlightBlock(objects.snapshotItem(i)); } }; </script> <!-- e:HILITE }}} --> <style type="text/css"> /* <![CDATA[ */ /* Based on Pixy's (wellstyled.com) style */ /* layout */ body { font-family: "Trebuchet MS", sans-serif; line-height: 1.5; text-align: center; margin-top: 0; padding: 0; } a:link { color: #FF8000; font-weight:bold; } a:visited { color: #BF8F5F; } a:hover { background-color:#6291CA; color:white; } .main { width: 800px; background-color: #eee; padding: 0; margin: 0; margin-left: auto; margin-right: auto; text-align: left; padding-left: 0.5em; padding-right: 0.5em; } /* content */ .content code { background-color: #ddd; white-space: nowrap; } .content em { color: #f00; } .content h2 { border-bottom: 3px dashed #0df; } .content h3 { border-bottom: 2px dashed #0df; } .content h4 { border-bottom: 1px dashed #0df; } .content pre { background-color: #ddd; } /* header and footer */ .header, .footer { font-size: 70%; text-align: center; font-weight: bold; } .header { border-bottom: 1px dashed black; margin-top: 0; } .footer { border-top: 1px dashed black; margin-bottom: 0; } /* toc */ .toc { border-bottom: 1px dashed black; text-align: left; margin-top: 0; } /* title */ .title h1 { text-align: center; } .title { border-bottom: 1px dashed black; margin-bottom: 1em; margin-top: 1em; } /* ]]> */ </style> </head> <body> <div class="main"> <div class="header">Generated by spec.rb at: {{{{NOW}}}}</div> <div class="title"><h1>{{{{TITLE}}}}</h1></div> <div class="toc"> {{{{TOC}}}} </div> <div class="content"> {{{{CONTENT}}}} </div> <div class="footer">Generated by spec.rb at: {{{{NOW}}}}</div> </div> </body> </html> Fix greediness in HILITE yank-out #!/usr/bin/env ruby require 'cgi' require 'digest/md5' class Markup attr_accessor :layout def initialize clear end def ok? @errors.empty? end def errors @errors.dup end def out tpl_out = template_replace(@layout, { :content => @content.join("\n"), :toc => @toc.join("\n"), :toc_no_heading => @toc_nh.join("\n"), :title => @title, :now => escape(@now.to_s), :now_numeric => escape(@now.strftime("%Y-%m-%d %H:%M:%S")), :filename => @filename, }) unless @code_lang_used tpl_out. gsub!(/<!-- s:HILITE \{\{\{ -->.*?<!-- e:HILITE \}\}\} -->\s*/m, '') end tpl_out end def process(file) clear @filename = File.basename(file.path) #.sub(/\.[^.]{3,4}$/,'') @line = 0 file.each do |ln| ln.chomp! @line += 1 type = typeof(ln) case type when :title @title = title(ln) when :heading flush @content << "" @content << heading(ln) when :list cond_switch_state(:list) @current << list_item(ln) when :def_list cond_switch_state(:def_list) @current << def_list_item(ln) when :end flush when :text cond_switch_state(:text) @current << text_line(ln) when :code cond_switch_state(:code) or @current << code_line(ln) when :img cond_switch_state(:text) @current << img(ln) when :comment else @errors << "Something weird at line: #{@line}" end end flush generate_toc end private def clear @content = [] @toc = [] @toc_nh = [] @toc_data = [] @state = :end @errors = [] @current = [] @layout ||= DATA.read @now = Time.now @title = "Unnamed spec ({{{{FILENAME}}}})" @filename = "?" @heading_base = 1 @code_lang = nil @code_lang_used = false end def template_replace(where, what) what.each do |k, v| where.gsub!(Regexp.new(Regexp.escape("{{" + "{{#{k.to_s}}}" + "}}"), Regexp::IGNORECASE), v.gsub(/\\/, '\\\\\\\\')) end where end def title(ln) @title = escape(ln.sub(/^!\s+/,'')) end def cond_switch_state(st) unless @state == st flush @state = st true else false end end def generate_toc level = 0 @toc << "<h#{@heading_base + 1}>Table of contents</h#{@heading_base + 1}>" (@toc_data + [[0, nil, nil]]).each do |lev, entry, key| case level <=> lev when -1 (lev-level).times do |i| l = (lev + i - 1) if l.zero? @toc_nh << (" " * l) + "<ul>" else @toc_nh << (" " * l) + "<li style='list-style-type: none;'><ul>" end end when 0 # nothing when 1 (level-lev).times do |i| l = (level - i - 1) if l.zero? @toc_nh << (" " * l) + "</ul>" else @toc_nh << (" " * l) + "</ul></li>" end end end level = lev @toc_nh << (" " * lev) + '<li><a href="#' + key + '">' + entry + '</a></li>' unless key.nil? || entry.nil? end @toc_nh << "" @toc += @toc_nh end def heading(ln) ar = ln.split(/^(=+\s+)/) if ar.size == 3 && ar[0].empty? sz = ar[1].strip.size cont = ar[2] id = ::Digest::MD5.hexdigest(@toc_data.size.to_s + sz.to_s + cont) @toc_data << [ar[1].strip.size, ar[2], id] "<h#{@heading_base + sz}>" + "<a name='#{id}'></a>" + cont + "</h#{@heading_base + sz}>" else @errors << "BUG: Heading assertion failed (#{@line})" "" end end def flush case @state when :text @content << "<p>\n" + @current.join("\n") + "\n</p>" when :list @content << "<ul>\n" + @current.join("\n") + "\n</ul>" when :def_list @content << "<dl>\n" + @current.join("\n") + "\n</dl>" when :code if @code_lang.empty? @content << "<pre>\n" + @current.join("\n") + "\n</pre>" else @content << "<pre class=\"highlight language-#{@code_lang}\">\n" + @current.join("\n") + "\n</pre>" @code_lang_used = true end when :end # nothing to do ... :) else @errors << "Some weird state encountered around line: #{@line}" end @current = [] @state = :end end def def_list_item(ln) ar = ln.split(/^(:\s*)(.*?)(\s*=\s*)(.*)/) if ar.size == 5 && ar[0] == "" && ar[1] =~ /:\s*/ && ar[3] =~ /\s*=\s*/ "<dt>" + escape(ar[2]) + "</dt>\n<dd>" + escape(ar[4]) + "</dd>" else @errors << "BUG: Def_list_item assertion failed (#{@line})" "" end end def text_line(ln) out = [] while (ln =~ /("[^"]*?"|[^\s]+)\<((ftp|https?|mailto|news|irc|REL):.*?)\>/) pre, label, url, post = $`, $1, $2, $' label = label[1..-2] if label =~ /^".*"$/ url = url[4..-1] if url =~ /^REL:/ out << escape(pre) out << "<a href=\"#{url}\">#{label}</a>" ln = post end out << escape(ln) out.join end def img(ln) ar = ln.split(/\s+/) ar.shift out = [] out << "<img src=\"#{ar.first}\"" ar.shift out << "style=\"#{ar.join(' ')}\"" unless ar.join(' ').empty? out << "/>" out.join(' ') end def code_line(ln) CGI.escapeHTML(ln) end def list_item(ln) ar = ln.split(/^(\*\s+)/) if ar.size == 3 && ar[0].empty? "<li>" + escape(ar[2]) + "</li>" else @errors << "BUG: List_item assertion failed (#{@line})" "" end end def escape(what) CGI.escapeHTML(what). gsub(/`(.*?)`/) { "<code>" + $1.gsub(/~/, '&#96;') + "</code>" }. gsub(/~/, '&nbsp;') end def typeof(ln) if @state == :code case ln when /^\}\}\}$/ :end else :code end else case ln when /^!\s+/ if @content.empty? :title else :text end when /^=/ :heading when /^\*/ :list when /^:/ :def_list when /^$/, /^\s+$/ :end when /^\{\{\{(.*)/ @code_lang = $1.strip :code when /^@/ :img when /^#/ :comment else :text end end end end if ARGV.size != 1 && ARGV.size != 2 puts "Usage: #$0 <input_file> [output_file]" exit 1 end begin out = ARGV[1].nil? ? $stdout : File.open(ARGV[1], 'w') rescue $stderr.puts "Unable to open output file: #$!" exit 1 end content = [] m = Markup.new ['layout.spec', ARGV[0].gsub(/\.[^.]+$/, '') + '.lsp'].each do |file| if FileTest.exists?(file) m.layout = File.open(file, 'r').read break end end File.open(ARGV[0]) do |f| m.process(f) end if m.ok? out.puts m.out exit 0 else $stderr.puts "Error:" $stderr.puts m.errors.join("\n") exit 1 end __END__ <!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" /> <title>{{{{TITLE}}}}</title> <!-- s:HILITE {{{ --> <!-- github hilite stylesheet --> <link rel="stylesheet" href="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Ij4iLGs6YixyOjEwLGM6WyJzZWxmIl19 XX19fShobGpzKTs="></script> <script type="text/javascript"> window.onload = function() { // jQuery: $(function(){ $('pre.highlight').each(function(i, e) {hljs.highlightBlock(e)}); }); var objects = document.evaluate('//pre[contains(@class, "highlight")]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < objects.snapshotLength; i++) { hljs.highlightBlock(objects.snapshotItem(i)); } }; </script> <!-- e:HILITE }}} --> <style type="text/css"> /* <![CDATA[ */ /* Based on Pixy's (wellstyled.com) style */ /* layout */ body { font-family: "Trebuchet MS", sans-serif; line-height: 1.5; text-align: center; margin-top: 0; padding: 0; } a:link { color: #FF8000; font-weight:bold; } a:visited { color: #BF8F5F; } a:hover { background-color:#6291CA; color:white; } .main { width: 800px; background-color: #eee; padding: 0; margin: 0; margin-left: auto; margin-right: auto; text-align: left; padding-left: 0.5em; padding-right: 0.5em; } /* content */ .content code { background-color: #ddd; white-space: nowrap; } .content em { color: #f00; } .content h2 { border-bottom: 3px dashed #0df; } .content h3 { border-bottom: 2px dashed #0df; } .content h4 { border-bottom: 1px dashed #0df; } .content pre { background-color: #ddd; } /* header and footer */ .header, .footer { font-size: 70%; text-align: center; font-weight: bold; } .header { border-bottom: 1px dashed black; margin-top: 0; } .footer { border-top: 1px dashed black; margin-bottom: 0; } /* toc */ .toc { border-bottom: 1px dashed black; text-align: left; margin-top: 0; } /* title */ .title h1 { text-align: center; } .title { border-bottom: 1px dashed black; margin-bottom: 1em; margin-top: 1em; } /* ]]> */ </style> </head> <body> <div class="main"> <div class="header">Generated by spec.rb at: {{{{NOW}}}}</div> <div class="title"><h1>{{{{TITLE}}}}</h1></div> <div class="toc"> {{{{TOC}}}} </div> <div class="content"> {{{{CONTENT}}}} </div> <div class="footer">Generated by spec.rb at: {{{{NOW}}}}</div> </div> </body> </html>
$:.unshift 'ext' require 'rblineprof' class Obj define_method(:inner_block) do sleep 0.001 end def another(options={}) sleep 0.001 end class_eval <<-RUBY, 'otherfile.rb', 1 def other_file another end RUBY end def inner sleep 0.001 1*2*3 4*5*6 7*8*9*10*11*12*13*14*15 2**32 2**128 o = Obj.new o.inner_block o.another o.other_file end def outer sleep 0.001 100.times do inner end inner end profile = lineprof(/./) do outer end file = File.expand_path(__FILE__) File.readlines(file).each_with_index do |line, num| time, calls = profile[file][num+1] if calls && calls > 0 printf "% 8.1fms (% 5d) | %s", time/1000.0, calls, line else printf " | %s", line end end puts profile.each do |file, data| total, child, exclusive = data[0] puts file printf " % 10.1fms in this file\n", exclusive/1000.0 printf " % 10.1fms in this file + children\n", total/1000.0 printf " % 10.1fms in children\n", child/1000.0 puts end 1.8 compat $:.unshift 'ext' require 'rblineprof' class Obj define_method(:inner_block) do sleep 0.001 end def another(options={}) sleep 0.001 end class_eval <<-RUBY, 'otherfile.rb', 1 def other_file another end RUBY end def inner sleep 0.001 1*2*3 4*5*6 7*8*9*10*11*12*13*14*15 2**32 2**128 o = Obj.new o.inner_block o.another o.other_file end def outer sleep 0.001 100.times do inner end inner end profile = lineprof(/./) do outer end file = RUBY_VERSION > '1.9' ? File.expand_path(__FILE__) : __FILE__ File.readlines(file).each_with_index do |line, num| time, calls = profile[file][num+1] if calls && calls > 0 printf "% 8.1fms (% 5d) | %s", time/1000.0, calls, line else printf " | %s", line end end puts profile.each do |file, data| total, child, exclusive = data[0] puts file printf " % 10.1fms in this file\n", exclusive/1000.0 printf " % 10.1fms in this file + children\n", total/1000.0 printf " % 10.1fms in children\n", child/1000.0 puts end
require_relative 'init' require_relative './test/write_log_messages' require_relative './test/write_to_null_logger' require_relative './test/ad_hoc_debug_message' Add exclude log messages test to test.rb file. require_relative 'init' require_relative './test/write_log_messages' require_relative './test/write_to_null_logger' require_relative './test/ad_hoc_debug_message' require_relative './test/exclude_log_messages'
#!/usr/bin/env ruby require 'solareventcalculator' class NewTime def self.current_time(latitude, longitude, tz) yesterday = SolarEventCalculator.new(Date.today - 1, latitude, longitude) today = SolarEventCalculator.new(Date.today, latitude, longitude) tomorrow = SolarEventCalculator.new(Date.today + 1, latitude, longitude) sunset_yesterday = yesterday.compute_official_sunset(tz) sunrise_today = today.compute_official_sunrise(tz) sunset_today = today.compute_official_sunset(tz) sunrise_tomorrow = tomorrow.compute_official_sunrise(tz) time = DateTime.now if time < sunrise_today start, finish = sunset_yesterday, sunrise_today start_hour = 18 elsif time < sunset_today start, finish = sunrise_today, sunset_today start_hour = 6 else start, finish = sunset_today, sunrise_tomorrow start_hour = 18 end seconds = (start_hour + (time - start).to_f / (finish - start) * 12) * 60 * 60 fractional = seconds - seconds.floor seconds = seconds.floor minutes = seconds / 60 seconds -= minutes * 60 hours = minutes / 60 minutes -= hours * 60 hours -= 24 if hours >= 24 if hours > 12 "%i:%02i pm" % [hours - 12, minutes] else "%i:%02i am" % [hours, minutes] end end end latitude = -33.714955 longitude = 150.311407 tz = "Australia/Sydney" puts NewTime.current_time(latitude, longitude, tz) Separate display of time #!/usr/bin/env ruby require 'solareventcalculator' class NewTime attr_accessor :hours, :minutes, :seconds, :fractional def initialize(hours, minutes, seconds, fractional) @hours, @minutes, @seconds, @fractional = hours, minutes, seconds, fractional end def self.current_time(latitude, longitude, tz) yesterday = SolarEventCalculator.new(Date.today - 1, latitude, longitude) today = SolarEventCalculator.new(Date.today, latitude, longitude) tomorrow = SolarEventCalculator.new(Date.today + 1, latitude, longitude) sunset_yesterday = yesterday.compute_official_sunset(tz) sunrise_today = today.compute_official_sunrise(tz) sunset_today = today.compute_official_sunset(tz) sunrise_tomorrow = tomorrow.compute_official_sunrise(tz) time = DateTime.now if time < sunrise_today start, finish = sunset_yesterday, sunrise_today start_hour = 18 elsif time < sunset_today start, finish = sunrise_today, sunset_today start_hour = 6 else start, finish = sunset_today, sunrise_tomorrow start_hour = 18 end seconds = (start_hour + (time - start).to_f / (finish - start) * 12) * 60 * 60 fractional = seconds - seconds.floor seconds = seconds.floor minutes = seconds / 60 seconds -= minutes * 60 hours = minutes / 60 minutes -= hours * 60 hours -= 24 if hours >= 24 NewTime.new(hours, minutes, seconds, fractional) end def to_s if hours > 12 "%i:%02i pm" % [hours - 12, minutes] else "%i:%02i am" % [hours, minutes] end end end latitude = -33.714955 longitude = 150.311407 tz = "Australia/Sydney" puts NewTime.current_time(latitude, longitude, tz)
#!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'rdf-trix' gem.homepage = 'http://ruby-rdf.github.com/rdf-trix/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'TriX support for RDF.rb.' gem.description = 'RDF.rb plugin for parsing/serializing TriX data.' gem.rubyforge_project = 'rdf' gem.author = 'Arto Bendiken' gem.email = 'public-rdf-ruby@w3.org' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS CREDITS README UNLICENSE VERSION etc/doap.xml) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w() gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = ['REXML (>= 3.1.7), LibXML-Ruby (>= 1.1.4), or Nokogiri (>= 1.4.2)'] gem.add_runtime_dependency 'rdf', '>= 1.0' gem.add_development_dependency 'rdf-spec', '>= 1.0' gem.add_development_dependency 'rspec', '>= 2.13' gem.add_development_dependency 'yard' , '>= 0.8.5' gem.add_development_dependency 'libxml-ruby', '>= 1.1.4' gem.add_development_dependency 'nokogiri', '>= 1.5.9' gem.post_install_message = nil end Remove development dependencies on libxml-ruby and nokogiri for JRuby. #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'rdf-trix' gem.homepage = 'http://ruby-rdf.github.com/rdf-trix/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'TriX support for RDF.rb.' gem.description = 'RDF.rb plugin for parsing/serializing TriX data.' gem.rubyforge_project = 'rdf' gem.author = 'Arto Bendiken' gem.email = 'public-rdf-ruby@w3.org' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS CREDITS README UNLICENSE VERSION etc/doap.xml) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w() gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = ['REXML (>= 3.1.7), LibXML-Ruby (>= 1.1.4), or Nokogiri (>= 1.4.2)'] gem.add_runtime_dependency 'rdf', '>= 1.0' gem.add_development_dependency 'rdf-spec', '>= 1.0' gem.add_development_dependency 'rspec', '>= 2.13' gem.add_development_dependency 'yard' , '>= 0.8.5' gem.add_development_dependency 'libxml-ruby', '>= 1.1.4' unless RUBY_PLATFORM == 'java' gem.add_development_dependency 'nokogiri', '>= 1.5.9' unless RUBY_PLATFORM == 'java' gem.post_install_message = nil end
require 'net/http' require 'uri' module SVN class << self attr_accessor :username, :password end # Returns a string to be passed into commands containing authentication options # Requires setting of username and password via attr_accessor methods def self.authentication_details "--username #{@username} --password #{@password}" end # Returns an array representing the current status of any new or modified files def self.status SVN.execute("status").split(/\n/).map do |file| file =~ /(\?|\!|\~|\*|\+|A|C|D|I|M|S|X)\s*([\w\W]*)/ [$1, $2] end end # Adds the given path to the working copy def self.add(path) SVN.execute("add #{path}") end # Adds all new or modified files to the working copy def self.add_all SVN.status.each { |file| add = SVN.add(file[1]) if file[0] == '?' } end # Add all new or modified files to the working copy and commits changes # An optional commit message can be passed if required def self.add_and_commit_all(message=nil) SVN.add_all SVN.commit message end # Commits all changes, and returns the new revision number # An optional commit message can be passed if required def self.commit(message=nil) if message.nil? action = SVN.execute("commit") else action = SVN.execute("commit -m '#{message}'") end if action.split(/\n/).last =~ /Committed revision (\d+)\./ return $1 else return nil end end # Returns a diff of two commits based on their respective revision numbers # (first and second arguments) and a repository path (third argument) def self.diff(revision_1,revision_2,file=nil) if file.nil? SVN.execute("diff -r #{revision_1}:#{revision_2}") else SVN.execute("diff -r #{revision_1}:#{revision_2} #{file}") end end # Retrieve a file based on it's path and commit revision number def self.get(file,revision) SVN.execute("cat -r #{revision} #{file}") end # Rename a file based on the given current and new filenames def self.rename(old_filename, new_filename) SVN.execute("rename #{old_filename} #{new_filename}") end # Delete a file based on a given path def self.delete(file) SVN.execute("delete #{file}") end private def self.execute(command) %x{svn #{command} #{SVN.authentication_details}} end end added support for path require 'net/http' require 'uri' module SVN class << self attr_accessor :username, :password,:path end # Returns a string to be passed into commands containing authentication options # Requires setting of username and password via attr_accessor methods def self.authentication_details "--username #{@username} --password #{@password}" end # Returns an array representing the current status of any new or modified files def self.status SVN.execute("status").split(/\n/).map do |file| file =~ /(\?|\!|\~|\*|\+|A|C|D|I|M|S|X)\s*([\w\W]*)/ [$1, $2] end end # Adds the given path to the working copy def self.add(path) SVN.execute("add #{path}") end # Adds all new or modified files to the working copy def self.add_all SVN.status.each { |file| add = SVN.add(file[1]) if file[0] == '?' } end # Add all new or modified files to the working copy and commits changes # An optional commit message can be passed if required def self.add_and_commit_all(message=nil) SVN.add_all SVN.commit message end # Commits all changes, and returns the new revision number # An optional commit message can be passed if required def self.commit(message=nil) if message.nil? action = SVN.execute("commit") else action = SVN.execute("commit -m '#{message}'") end if action.split(/\n/).last =~ /Committed revision (\d+)\./ return $1 else return nil end end # Returns a diff of two commits based on their respective revision numbers # (first and second arguments) and a repository path (third argument) def self.diff(revision_1,revision_2,file=nil) if file.nil? SVN.execute("diff -r #{revision_1}:#{revision_2}") else SVN.execute("diff -r #{revision_1}:#{revision_2} #{file}") end end # Retrieve a file based on it's path and commit revision number def self.get(file,revision) SVN.execute("cat -r #{revision} #{file}") end # Rename a file based on the given current and new filenames def self.rename(old_filename, new_filename) SVN.execute("rename #{old_filename} #{new_filename}") end # Delete a file based on a given path def self.delete(file) SVN.execute("delete #{file}") end private def self.execute(command) if @path.nil? return %x{svn #{command} #{SVN.authentication_details}} else return %x{svn #{command} #{SVN.authentication_details} #{@path}} end end end
require 'digest/sha1' require 'digest/sha2' module Enumerable def tee(*procs) each { |i| procs.map { |p| p.call i } } end end class IO def chunks(chunk_size=1024) Enumerator.new { |y| y << read(chunk_size) until eof? } end def each_chunk(chunk_size=nil) chunks.each { |*args| yield *args } end def digest_with(digest, chunk_size=nil) chunks(chunk_size).each { |chunk| digest << chunk } digest end def sha256(chunk_size=nil) digest_with Digest::SHA2.new(256), chunk_size end def tee(*procs) ios = procs.map { |proc| FiberChunkedIO.new &proc } chunks.each do |chunk| ios.each do |io| io.write chunk end end ios.each { |io| io.close } ios.map { |io| io.result } end end class FiberChunkedIO def initialize(chunk_size=1024, &block) @chunk_size = chunk_size @chunks = [] @eof = false @fiber = Fiber.new do @result = block.call self end @fiber.resume end # Being a stream, it behaves like IO#eof? and blocks until the other end sends some data or closes it. def eof? Fiber.yield @eof end def close @eof = true @fiber.resume end def result @result end def write(chunk) if chunk.size > @chunk_size raise ArgumentError.new("chunk size mismatch: expected #{@chunk_size}, got #{chunk.size}") end @chunks << chunk @eof = false @fiber.resume chunk.size end def read(chunk_size) unless chunk_size == @chunk_size raise ArgumentError.new("chunk size mismatch: expected #{@chunk_size}, got #{chunk_size}") end @chunks.shift end def chunks(chunk_size=1024) Enumerator.new do |y| y << read(chunk_size) until eof? end end end File.open("test") do |f| sha1_proc = lambda do |f| digest = Digest::SHA1.new f.chunks.each { |chunk| digest << chunk } digest end sha2_proc = lambda do |f| digest = Digest::SHA2.new(256) f.chunks.each { |chunk| digest << chunk } digest end puts_proc = lambda do |f| f.chunks.each { |chunk| puts chunk.length } end results = f.tee(sha1_proc, sha2_proc, puts_proc) p results p File.read('sums').lines.map.with_index { |l, i| results[i] == l.split(' ')[0] } end modulization require 'digest/sha1' require 'digest/sha2' module Enumerable def tee(*procs) each { |i| procs.map { |p| p.call i } } end end class IO module Chunkable def chunks(chunk_size=1024) Enumerator.new { |y| y << read(chunk_size) until eof? } end def each_chunk(chunk_size=nil) chunks.each { |*args| yield *args } end end module Digestable def digest_with(digest, chunk_size=nil) chunks(chunk_size).each { |chunk| digest << chunk } digest end def sha256(chunk_size=nil) digest_with Digest::SHA2.new(256), chunk_size end end module Utils def tee(*procs) ios = procs.map { |proc| FiberChunkedIO.new &proc } chunks.each do |chunk| ios.each do |io| io.write chunk end end ios.each { |io| io.close } ios.map { |io| io.result } end end include Chunkable include Digestable include Utils end class FiberChunkedIO def initialize(chunk_size=1024, &block) @chunk_size = chunk_size @chunks = [] @eof = false @fiber = Fiber.new do @result = block.call self end @fiber.resume end # Being a stream, it behaves like IO#eof? and blocks until the other end sends some data or closes it. def eof? Fiber.yield @eof end def close @eof = true @fiber.resume end def result @result end def write(chunk) if chunk.size > @chunk_size raise ArgumentError.new("chunk size mismatch: expected #{@chunk_size}, got #{chunk.size}") end @chunks << chunk @eof = false @fiber.resume chunk.size end def read(chunk_size) unless chunk_size == @chunk_size raise ArgumentError.new("chunk size mismatch: expected #{@chunk_size}, got #{chunk_size}") end @chunks.shift end include IO::Chunkable end File.open("test") do |f| sha1_proc = lambda do |f| digest = Digest::SHA1.new f.chunks.each { |chunk| digest << chunk } digest end sha2_proc = lambda do |f| digest = Digest::SHA2.new(256) f.chunks.each { |chunk| digest << chunk } digest end puts_proc = lambda do |f| f.chunks.each { |chunk| puts chunk.length } end results = f.tee(sha1_proc, sha2_proc, puts_proc) p results p File.read('sums').lines.map.with_index { |l, i| results[i] == l.split(' ')[0] } end
Initial Commit - README will come soon :) class Vhm < Formula desc "A very simple VirtualHost Manager Script for Apache" homepage "http://github.com/alxndrhi/vhm" url "https://github.com/alxndrhi/vhm/archive/v0.1.0.tar.gz" sha256 "bfa77d5ad4de266153adbe29a6204667692913b864bddafd0a4dd3a18154480c" version "0.1.0" def install bin.install "vhm" (etc/"vhm").install "vhm.cfg" (etc/"vhm").install "httpd-vhosts.conf" (etc/"vhm/templates").install "VirtualHost.conf" Dir.mkdir("#{etc}/vhm/sites-enabled") unless File.exists?("#{etc}/vhm/sites-enabled") Dir.mkdir("#{etc}/vhm/sites-available") unless File.exists?("#{etc}/vhm/sites-available") end def caveats; <<-EOS.undent The next step is to set the correct values in your config file. You can find the config files in #{etc}/vhm. Apache need to know where your configuration files will be located. To include them add the following Line to your httpd-vhosts.conf: Include /usr/local/etc/vhm/httpd-vhosts.conf You can find more detailed information on how to setup vhm on http://github.com/alxndrhi/vhm If you are migrating from an earlier version please see the nodes on: http://github.com/alxndrhi/vhm EOS end end
require 'sinatra' require 'sinatra/logger' require 'line/bot' require 'net/http' require 'json' def client @client ||= Line::Bot::Client.new { |config| config.channel_secret = ENV["LINE_CHANNEL_SECRET"] config.channel_token = ENV["LINE_CHANNEL_TOKEN"] } end def request_nba_stat results = {} nba_stat_uri = URI('http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2016-17') response = Net::HTTP.get(nba_stat_uri) data = JSON.parse(response) data['resultSets'][0]['rowSet'].each do |player| player_id = player[0] full_name = player[2].gsub(/[^a-zA-Z0-9\-_]+/, '_').downcase results[full_name] = player_id end results end def get_player_news_by_id(player_id) player_uri = URI("http://stats-prod.nba.com/wp-json/statscms/v1/rotowire/player/?playerId=#{player_id}&limit=2") response = Net::HTTP.get(player_uri) data = JSON.parse(response) end player_map = request_nba_stat configure do enable :logging end post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] unless client.validate_signature(body, signature) error 400 do 'Bad Request' end end events = client.parse_events_from(body) events.each do |event| puts event.message case event when Line::Bot::Event::Message case event.type when Line::Bot::Event::MessageType::Text receive_message = event.message['text'] nba_msg_segment = receive_message.split('nba player ') cmd_nba_flag = nba_msg_segment.length > 1 if cmd_nba_flag puts 'Confirm' player_name = nba_msg_segment[1].gsub(/[^a-zA-Z0-9\-_]+/, '_').downcase player_id = player_map[player_name] if player_id != nil puts "Loading player...#{player_name} #{player_id}" player_news = get_player_news_by_id(player_id) puts player_news if player_news puts "use template for #{player_id}" message = { type: 'template', altText: "http://stats.nba.com/player/#!/#{player_id}", template: { type: 'buttons', title: "#{player_name}", text: "Test", actions: [ { type: 'uri', label: '球員資訊', uri: "http://stats.nba.com/player/#!/#{player_id}" } ] } } else message = { type: 'text', text: "#{player_name} 沒新聞" } end else message = { type: 'text', text: "沒找到 #{player_name}" } end puts event['replyToken'] response = client.reply_message(event['replyToken'], message) puts response.body end when Line::Bot::Event::MessageType::Image, Line::Bot::Event::MessageType::Video response = client.get_message_content(event.message['id']) tf = Tempfile.open("content") tf.write(response.body) end end end "OK" end Update require 'sinatra' require 'sinatra/logger' require 'line/bot' require 'net/http' require 'json' def client @client ||= Line::Bot::Client.new { |config| config.channel_secret = ENV["LINE_CHANNEL_SECRET"] config.channel_token = ENV["LINE_CHANNEL_TOKEN"] } end def request_nba_stat results = {} nba_stat_uri = URI('http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2016-17') response = Net::HTTP.get(nba_stat_uri) data = JSON.parse(response) data['resultSets'][0]['rowSet'].each do |player| player_id = player[0] full_name = player[2].gsub(/[^a-zA-Z0-9\-_]+/, '_').downcase results[full_name] = player_id end results end def get_player_news_by_id(player_id) player_uri = URI("http://stats-prod.nba.com/wp-json/statscms/v1/rotowire/player/?playerId=#{player_id}&limit=2") response = Net::HTTP.get(player_uri) data = JSON.parse(response) end player_map = request_nba_stat configure do enable :logging end post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] unless client.validate_signature(body, signature) error 400 do 'Bad Request' end end events = client.parse_events_from(body) events.each do |event| puts event.message case event when Line::Bot::Event::Message case event.type when Line::Bot::Event::MessageType::Text receive_message = event.message['text'] nba_msg_segment = receive_message.split('nba player ') cmd_nba_flag = nba_msg_segment.length > 1 if cmd_nba_flag puts 'Confirm' player_name = nba_msg_segment[1].gsub(/[^a-zA-Z0-9\-_]+/, '_').downcase player_id = player_map[player_name] if player_id != nil puts "Loading player...#{player_name} #{player_id}" player_news = get_player_news_by_id(player_id) puts player_news if player_news puts "use template for #{player_id}" first_news = player_new['PlayerRotowires'][0] message = { type: 'template', altText: "[#{first_news['Team']}] #{first_new['FirstName']} #{first_news['LastName']}: http://stats.nba.com/player/#!/#{player_id}", template: { type: 'buttons', title: "[#{first_news['Team']}] #{first_new['FirstName']} #{first_news['LastName']}", text: first_news['ListItemCaption'][0..40], actions: [ { type: 'uri', label: '球員資訊', uri: "http://stats.nba.com/player/#!/#{player_id}" } ] } } else message = { type: 'text', text: "#{player_name} 沒新聞" } end else message = { type: 'text', text: "沒找到 #{player_name}" } end puts event['replyToken'] response = client.reply_message(event['replyToken'], message) puts response.body end when Line::Bot::Event::MessageType::Image, Line::Bot::Event::MessageType::Video response = client.get_message_content(event.message['id']) tf = Tempfile.open("content") tf.write(response.body) end end end "OK" end
require './lib/models/session' class Web < Sinatra::Base register Sinatra::Contrib helpers Sinatra::Param set :raise_sinatra_param_exceptions, true set :show_exceptions, false set :raise_errors, true helpers do def title(*args) [*args].compact.join(" - ") end def url(session) "/#{session.year}/sessions/#{session.number}" end def image_url(session) case Integer(session.year) when 2010, 2011 "/images/wwdc-#{session.year}.jpg" when 2012..2018 "/images/wwdc-#{session.year}.png" else nil end end def video_url(session) "https://developer.apple.com/videos/wwdc/#{session.year}/?id=#{session.number}" end end before do @query = params[:q] cache_control :public, max_age: 36000 unless @query headers "Content-Security-Policy" => %( default-src 'self' *.asciiwwdc.com https://www.google-analytics.com 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'none'; ).gsub("\n", ' ').squeeze(' ').strip, "Link" => %( </css/screen.css>; rel=preload; as=style ).gsub("\n", ' ').squeeze(' ').strip, "Referrer-Policy" => "same-origin", "Server" => '', "Strict-Transport-Security" => "max-age=63072000; includeSubDomains; preload", "X-Content-Type-Options" => "nosniff", "X-Frame-Options" => "DENY", "X-XSS-Protection" => "1; mode=block" unless settings.development? end error Sinatra::Param::InvalidParameterError do haml :error, :locals => { :msg => env['sinatra.error'] } end error 404 do haml :error, :locals => { :msg => "404 Not found"} end not_found do haml :error, :locals => { :msg => "404 Not found"} end get '/' do cachepath = "/tmp/asciiwwdc-index.tmp" if File.exists?(cachepath) && !params.has_key?("refreshCache") File.read(cachepath) else @sessions = Session.order(:year, :number).all.group_by(&:year) output = haml :index File.open(cachepath, "w") do |file| file.write(output) end output end end get '/contribute' do haml :contribute end get '/:year/sessions/:number', provides: [:html, :json, :vtt, :txt] do param :year, Integer, required: true param :number, Integer, required: true halt 404 unless @session = Session.first(year: params[:year], number: params[:number]) link video_url(@session), :rel => :alternate respond_to do |f| f.html {haml :session} f.json {@session.to_json} f.vtt {send_file "data/#{params[:year]}/#{params[:number]}.vtt", type: :vtt} f.txt {@session.transcript} end end get '/search', provides: [:html, :json] do param :q, String, blank: false param :year, Integer, in: 2010..2016 @sessions = Session.search(@query, params[:year]) respond_to do |f| f.html {haml :search} f.json do { query: @query, results: @sessions.collect(&:to_h) }.to_json end end end get '/sitemap.xml' do @sessions = Session.order(:year, :number).all respond_to do |f| f.xml { builder :sitemap } end end get '/:year' do param :year, Integer case params[:year] when 2010..2016 redirect "/#wwdc-#{params[:year]}" else pass end end end Remove performance hack for index require './lib/models/session' class Web < Sinatra::Base register Sinatra::Contrib helpers Sinatra::Param set :raise_sinatra_param_exceptions, true set :show_exceptions, false set :raise_errors, true helpers do def title(*args) [*args].compact.join(" - ") end def url(session) "/#{session.year}/sessions/#{session.number}" end def image_url(session) case Integer(session.year) when 2010, 2011 "/images/wwdc-#{session.year}.jpg" when 2012..2018 "/images/wwdc-#{session.year}.png" else nil end end def video_url(session) "https://developer.apple.com/videos/wwdc/#{session.year}/?id=#{session.number}" end end before do @query = params[:q] cache_control :public, max_age: 3600 headers "Content-Security-Policy" => %( default-src 'self' *.asciiwwdc.com https://www.google-analytics.com 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'none'; ).gsub("\n", ' ').squeeze(' ').strip, "Link" => %( </css/screen.css>; rel=preload; as=style ).gsub("\n", ' ').squeeze(' ').strip, "Referrer-Policy" => "same-origin", "Server" => '', "Strict-Transport-Security" => "max-age=63072000; includeSubDomains; preload", "X-Content-Type-Options" => "nosniff", "X-Frame-Options" => "DENY", "X-XSS-Protection" => "1; mode=block" unless settings.development? end error Sinatra::Param::InvalidParameterError do haml :error, :locals => { :msg => env['sinatra.error'] } end error 404 do haml :error, :locals => { :msg => "404 Not found"} end not_found do haml :error, :locals => { :msg => "404 Not found"} end get '/' do @sessions = Session.select(:title, :year, :number, :track) .order(:year, :number) .all .group_by(&:year) haml :index end get '/contribute' do haml :contribute end get '/:year/sessions/:number', provides: [:html, :json, :vtt, :txt] do param :year, Integer, required: true param :number, Integer, required: true halt 404 unless @session = Session.first(year: params[:year], number: params[:number]) link video_url(@session), :rel => :alternate respond_to do |f| f.html {haml :session} f.json {@session.to_json} f.vtt {send_file "data/#{params[:year]}/#{params[:number]}.vtt", type: :vtt} f.txt {@session.transcript} end end get '/search', provides: [:html, :json] do param :q, String, blank: false param :year, Integer, in: 2010..2016 @sessions = Session.search(@query, params[:year]) respond_to do |f| f.html {haml :search} f.json do { query: @query, results: @sessions.collect(&:to_h) }.to_json end end end get '/sitemap.xml' do @sessions = Session.order(:year, :number).all respond_to do |f| f.xml { builder :sitemap } end end get '/:year' do param :year, Integer case params[:year] when 2010..2016 redirect "/#wwdc-#{params[:year]}" else pass end end end
require 'sinatra' require 'youtube_it' %w(rubygems wordnik).each {|lib| require lib} Wordnik.configure do |config| config.api_key = '2511533437086d533fd5103847108c1b84ca3abec199e412d' end # Routes get '/' do word = Wordnik.words.get_random_word(:hasDictionaryDef => 'true') word["word"] client = YouTubeIt::Client.new videos = client.videos_by(query: word["word"]).videos while videos.length < 1 videos = client.videos_by( query: Wordnik.words.get_random_word(:hasDictionaryDef => 'true')["word"] ).videos end comment = client.comments(videos.sample.video_id.split(":").last).sample while comment.nil? comment = client.comments(videos.sample.video_id.split(":").last).sample end @comment = comment.content erb :index end refactoring like someone who really has to go to the bathroom require 'sinatra' require 'youtube_it' %w(rubygems wordnik).each {|lib| require lib} Wordnik.configure do |config| config.api_key = '2511533437086d533fd5103847108c1b84ca3abec199e412d' end def get_comment(videos) client.comments(videos.sample.video_id.split(":").last).sample end def random_word Wordnik.words.get_random_word(:hasDictionaryDef => 'true')["word"] end def search_for_videos(word) client.videos_by(query: word).videos end def client @client ||= YouTubeIt::Client.new end # Routes get '/' do @videos = search_for_videos(random_word) while @videos.nil? || @videos.length < 1 @comment_response = get_comment(@videos) while @comment_response.nil? || @comment_response.content.nil? @comment = @comment_response.content erb :index end
ENV["RACK_ENV"] ||= "development" require 'sinatra/base' require "sinatra/activerecord" require 'sinatra' require 'stripe' require 'dotenv' require 'json' require 'encrypted_cookie' require 'fileutils' require "carrierwave" require 'carrierwave/datamapper' require "carrierwave/orm/activerecord" require_relative 'models/image' require_relative 'data_mapper_setup' Dotenv.load Stripe.api_key = ENV['STRIPE_TEST_SECRET_KEY'] use Rack::Session::EncryptedCookie, :secret => ENV['SERVER_SECRET'] CarrierWave.configure do |config| config.root = File.dirname(__FILE__) + "/public" end get '/' do status 200 return "Splitter's Stripe Server is running." end post '/charge' do authenticate! # Get the credit card details submitted by the form source = params[:source] # Create the charge on Stripe's servers - this will charge the user's card begin charge = Stripe::Charge.create( :amount => params[:amount], :currency => params[:currency], :customer => @customer.id, :source => source, :description => params[:description] ) rescue Stripe::StripeError => e status 402 return "Error creating charge: #{e.message}" end status 200 return "Charge successfully created" end get '/customer' do authenticate! status 200 content_type :json @customer.to_json end post '/account/create' do begin account = Stripe::Account.create( :managed => true, :country => params[:country], :email => params[:email], :legal_entity => { :first_name => params[:first_name], :last_name => params[:last_name], :dob => { :day => params[:day], :month => params[:month], :year => params[:year] }, :address => { :line1 => params[:line1], :city => params[:city], :postal_code => params[:postal_code] }, :type => "individual" }, :tos_acceptance => { :date => Time.now.to_i, :ip => request.ip } ) rescue Stripe::StripeError => e status 402 return "Error creating managed customer account: #{e.message}" end status 200 return account.to_json end post '/account/external_account' do begin account = Stripe::Account.retrieve(params[:stripe_account]) account.external_accounts.object = 'bank_account' account.save account.external_accounts.country = 'US' account.save account.external_accounts.currency = 'usd' account.save account.external_accounts.routing_number = '110000000' account.save account.external_accounts.account_number = '000123456789' account.save rescue Stripe::StripeError => e status 402 return "Error adding external account to customer account: #{e.message}" end status 200 return account.to_json end post '/account/id' do begin path = File.dirname(__FILE__) + "/public" image = Image.new(file: params[:file]) image.save p image.file.url file = Stripe::FileUpload.create( { :purpose => params[:purpose], :file => image.file.url }, { :stripe_account => params[:stripe_account] } ) image.destroy rescue Stripe::StripeError => e status 402 return "Error saving verification id to account: #{e.message}" end status 200 return file.to_json end post '/account/id' do account = Stripe::Account.retrieve(params[:stripe_account]) account.legal_entity.verification.document = params[:file_id] account.save return account.to_json end post '/customer/sources' do authenticate! source = params[:source] # Adds the token to the customer's sources begin @customer.sources.create({:source => source}) rescue Stripe::StripeError => e status 402 return "Error adding token to customer: #{e.message}" end begin charge = Stripe::Charge.create( :amount => params[:amount], # this number should be in cents :currency => params[:currency], :customer => @customer.id, :source => source, :description => params[:description] ) rescue Stripe::StripeError => e status 402 return "Error creating charge: #{e.message}" end status 200 return "Charge successfully created" end post '/customer/default_source' do authenticate! source = params[:source] # Sets the customer's default source begin @customer.default_source = source @customer.save rescue Stripe::StripeError => e status 402 return "Error selecting default source: #{e.message}" end status 200 return "Successfully selected default source." end def authenticate! # This code simulates "loading the Stripe customer for your current session". # Your own logic will likely look very different. return @customer if @customer if session.has_key?(:customer_id) customer_id = session[:customer_id] begin @customer = Stripe::Customer.retrieve(customer_id) rescue Stripe::InvalidRequestError end else begin @customer = Stripe::Customer.create(:description => "iOS SDK example customer") rescue Stripe::InvalidRequestError end session[:customer_id] = @customer.id end @customer end # This endpoint is used by the Obj-C example to complete a charge. post '/charge_card' do # Get the credit card details submitted by the form token = params[:stripe_token] # Create the charge on Stripe's servers - this will charge the user's card begin charge = Stripe::Charge.create( :amount => params[:amount], # this number should be in cents :currency => params[:currency], :card => token, :description => params[:description] ) rescue Stripe::StripeError => e status 402 return "Error creating charge: #{e.message}" end status 200 return "Charge successfully created" end things ENV["RACK_ENV"] ||= "development" require 'sinatra/base' require "sinatra/activerecord" require 'sinatra' require 'stripe' require 'dotenv' require 'json' require 'encrypted_cookie' require 'fileutils' require "carrierwave" require 'carrierwave/datamapper' require "carrierwave/orm/activerecord" require_relative 'models/image' require_relative 'data_mapper_setup' Dotenv.load Stripe.api_key = ENV['STRIPE_TEST_SECRET_KEY'] use Rack::Session::EncryptedCookie, :secret => ENV['SERVER_SECRET'] CarrierWave.configure do |config| config.root = File.dirname(__FILE__) + "/public" end get '/' do status 200 return "Splitter's Stripe Server is running." end post '/charge' do authenticate! # Get the credit card details submitted by the form source = params[:source] # Create the charge on Stripe's servers - this will charge the user's card begin charge = Stripe::Charge.create( :amount => params[:amount], :currency => params[:currency], :customer => @customer.id, :source => source, :description => params[:description] ) rescue Stripe::StripeError => e status 402 return "Error creating charge: #{e.message}" end status 200 return "Charge successfully created" end get '/customer' do authenticate! status 200 content_type :json @customer.to_json end post '/account/create' do begin account = Stripe::Account.create( :managed => true, :country => params[:country], :email => params[:email], :legal_entity => { :first_name => params[:first_name], :last_name => params[:last_name], :dob => { :day => params[:day], :month => params[:month], :year => params[:year] }, :address => { :line1 => params[:line1], :city => params[:city], :postal_code => params[:postal_code] }, :type => "individual" }, :tos_acceptance => { :date => Time.now.to_i, :ip => request.ip } ) rescue Stripe::StripeError => e status 402 return "Error creating managed customer account: #{e.message}" end status 200 return account.to_json end post '/account/external_account' do begin account = Stripe::Account.retrieve(params[:stripe_account]) account.external_accounts.create(:object => "bank_account", :country => "US", :currency => "usd", :routing_number => "110000000", :account_number => "000123456789" ) rescue Stripe::StripeError => e status 402 return "Error adding external account to customer account: #{e.message}" end status 200 return account.to_json end post '/account/id' do begin path = File.dirname(__FILE__) + "/public" image = Image.new(file: params[:file]) image.save p image.file.url file = Stripe::FileUpload.create( { :purpose => params[:purpose], :file => image.file.url }, { :stripe_account => params[:stripe_account] } ) image.destroy rescue Stripe::StripeError => e status 402 return "Error saving verification id to account: #{e.message}" end status 200 return file.to_json end post '/account/id' do account = Stripe::Account.retrieve(params[:stripe_account]) account.legal_entity.verification.document = params[:file_id] account.save return account.to_json end post '/customer/sources' do authenticate! source = params[:source] # Adds the token to the customer's sources begin @customer.sources.create({:source => source}) rescue Stripe::StripeError => e status 402 return "Error adding token to customer: #{e.message}" end begin charge = Stripe::Charge.create( :amount => params[:amount], # this number should be in cents :currency => params[:currency], :customer => @customer.id, :source => source, :description => params[:description] ) rescue Stripe::StripeError => e status 402 return "Error creating charge: #{e.message}" end status 200 return "Charge successfully created" end post '/customer/default_source' do authenticate! source = params[:source] # Sets the customer's default source begin @customer.default_source = source @customer.save rescue Stripe::StripeError => e status 402 return "Error selecting default source: #{e.message}" end status 200 return "Successfully selected default source." end def authenticate! # This code simulates "loading the Stripe customer for your current session". # Your own logic will likely look very different. return @customer if @customer if session.has_key?(:customer_id) customer_id = session[:customer_id] begin @customer = Stripe::Customer.retrieve(customer_id) rescue Stripe::InvalidRequestError end else begin @customer = Stripe::Customer.create(:description => "iOS SDK example customer") rescue Stripe::InvalidRequestError end session[:customer_id] = @customer.id end @customer end # This endpoint is used by the Obj-C example to complete a charge. post '/charge_card' do # Get the credit card details submitted by the form token = params[:stripe_token] # Create the charge on Stripe's servers - this will charge the user's card begin charge = Stripe::Charge.create( :amount => params[:amount], # this number should be in cents :currency => params[:currency], :card => token, :description => params[:description] ) rescue Stripe::StripeError => e status 402 return "Error creating charge: #{e.message}" end status 200 return "Charge successfully created" end
#ruby 2048, for fun and to learn ruby better grid = [ [1, 0, 0, 1], [0, 2, 0, 0], [0, 0, 0, 3], [1, 0, 0, 0] ] def display(grid) for y in 0..3 do for x in 0..3 do print "#{grid[y][x]} " end puts end end #todo: make random number spawning do more than just 2 and 4, #make it take into account the total value of the array def spawn(grid) done = false until done do x = rand(4) y = rand(4) n = rand(1..2) * 2 if grid[y][x] == 0 grid[y][x] = n done = true end end end #broken ignore def moveleft(grid) grid.each do |x| x.each do |y| print grid[y][x] end end end def moveright(grid, dir) done = false diry = 0 dirx = 0 if dir == "up" diry = -1 elsif dir == "down" diry = 1 elsif dir == "left" dirx = -1 elsif dir == "right" dirx = 1 end for y in 0..3 do for x in 0..3 do #this doesn't work, research how to do this in ruby if ( 0 <= y <= 3 && 0 <= x <= 3) && grid[y+diry][x+dirx] = 0 puts "ok" end end end end dir = "right" display(grid) spawn(grid) puts "" display(grid) #moveright(grid, dir) puts "" display(grid) right movement working, does not work if there are gaps in the numbers eg 1010 becomes 0101. Added input via io/console reading STDIN #ruby 2048, for fun and to learn ruby better require 'io/console' grid = [ [1, 0, 0, 1], [0, 2, 0, 0], [0, 0, 0, 3], [1, 0, 0, 0] ] def display(grid) for y in 0..3 do for x in 0..3 do print "#{grid[y][x]} " end puts end end #todo: make random number spawning do more than just 2 and 4, #make it take into account the total value of the array def spawn(grid) done = false until done do x = rand(4) y = rand(4) n = rand(1..2) * 2 if grid[y][x] == 0 grid[y][x] = n done = true end end end def moveright(grid, dir) done = false diry = 0 dirx = 0 if dir == "up" diry = -1 elsif dir == "down" diry = 1 elsif dir == "left" dirx = -1 elsif dir == "right" dirx = 1 end for y in 0..3 do for x in 0..3 do if ( y.between?(0, 3) && x.between?(0, 3) ) && grid[y+diry][x+dirx] == 0 && grid[y][x] != 0 #puts "ok" grid[y+diry][x+dirx] = grid[y][x] grid[y][x] = 0 end end end end def read_char STDIN.echo = false STDIN.raw! input = STDIN.getc.chr if input == "\e" then input << STDIN.read_nonblock(3) rescue nil input << STDIN.read_nonblock(2) rescue nil end ensure STDIN.echo = true STDIN.cooked! return input end dir = "right" display(grid) spawn(grid) puts "" display(grid) moveright(grid, dir) puts "" display(grid) print read_char
# Get all lines of all files ARGF.each { | line | puts line } # Get all lines of all files, one by one using file handles puts ARGF.filename ARGF.file.each_line { |line| puts line } ARGF.close puts ARGF.filename ARGF.file.each_line { |line| puts line } ARGF.close Added sample code on using the argv property to access an array of command line arguments # Get array of all command line arguments puts ARGF.argv.inspect # Get all lines of all files ARGF.each { | line | puts line } # Get all lines of all files, one by one using file handles puts ARGF.filename ARGF.file.each_line { |line| puts line } ARGF.close puts ARGF.filename ARGF.file.each_line { |line| puts line } ARGF.close
Day 2 - wrapping # coding: utf-8 # http://AdventOfCode.com/ # Day 2 input = "29x13x26 11x11x14 27x2x5 6x10x13 15x19x10 26x29x15 8x23x6 17x8x26 20x28x3 23x12x24 11x17x3 19x23x28 25x2x25 1x15x3 25x14x4 23x10x23 29x19x7 17x10x13 26x30x4 16x7x16 7x5x27 8x23x6 2x20x2 18x4x24 30x2x26 6x14x23 10x23x9 29x29x22 1x21x14 22x10x13 10x12x10 20x13x11 12x2x14 2x16x29 27x18x26 6x12x20 18x17x8 14x25x1 30x15x22 17x18x7 28x23x24 15x12x25 14x7x20 29x23x8 24x5x22 6x22x8 1x15x26 14x5x1 24x28x28 17x23x23 4x15x7 23x8x11 6x15x1 23x18x13 17x1x26 23x13x17 2x18x8 22x22x1 10x22x6 28x29x20 22x21x25 14x8x23 12x30x14 8x7x5 3x30x15 4x3x29 25x18x3 16x7x16 4x3x8 9x16x30 20x28x3 28x24x6 4x18x2 23x18x5 22x4x30 15x30x9 7x12x12 3x22x29 12x1x9 9x2x25 17x11x10 25x24x7 7x27x26 26x4x12 29x2x26 19x24x12 23x23x3 26x28x16 18x4x16 25x30x18 29x19x19 16x3x27 29x25x29 18x19x5 14x21x30 19x13x26 19x10x15 9x4x7 18x6x6 24x25x29 9x12x27 15x3x22 30x17x21 18x19x28 9x11x12 8x28x22 11x3x4 28x17x20 24x18x15 11x12x13 6x19x24 28x4x5 28x22x23 13x29x2 9x16x15 29x28x1 10x18x30 19x11x12 26x28x25 23x17x13 25x1x21 17x1x27 17x27x28 28x13x15 14x13x25 11x29x7 22x29x5 13x6x14 23x18x13 25x7x17 18x9x20 21x11x2 28x11x13 13x25x1 19x29x25 16x29x4 10x21x10 7x25x17 5x9x3 1x15x6 8x27x29 23x6x30 22x22x29 6x20x30 26x25x29 10x19x19 20x30x9 5x30x24 17x10x27 30x14x30 8x17x4 7x18x6 3x5x4 24x17x15 14x20x17 22x27x15 18x14x15 23x9x11 21x16x29 7x18x21 9x3x29 10x13x4 2x30x4 23x20x4 8x22x21 29x28x4 13x16x25 21x9x11 7x26x26 13x23x30 19x7x10 9x23x21 21x9x17 9x21x15 20x29x22 23x13x15 19x25x2 12x11x30 20x21x6 21x6x17 24x26x9 29x21x29 29x26x16 6x16x1 2x12x6 6x7x20 7x2x22 6x22x4 13x11x27 25x27x14 11x8x6 26x11x14 30x3x29 27x21x20 15x16x26 6x22x10 11x9x25 23x13x6 13x9x3 30x22x13 29x23x14 25x19x6 7x29x11 19x18x5 29x25x13 25x24x27 1x9x12 22x9x17 14x12x28 19x21x17 13x25x17 14x25x12 4x14x30 7x15x28 3x6x25 6x2x16 15x19x11 17x30x20 20x23x7 26x21x6 26x29x24 2x4x30 4x22x18 13x3x28 27x6x21 5x3x27 12x7x11 28x11x9 12x9x2 1x22x20 15x13x28 14x19x16 28x20x3 20x4x9 26x7x26 18x19x25 7x1x13 20x23x29 27x26x8 11x15x15 10x21x23 29x2x11 21x28x20 3x18x23 26x17x17 14x26x17 20x7x17 18x12x8 4x8x8 8x15x23 24x29x5 1x25x8 1x28x17 16x18x13 29x24x22 13x16x10 14x7x16 15x11x29 12x15x19 17x6x28 4x3x9 15x16x8 29x27x11 2x24x20 4x21x3 29x24x27 18x22x22 7x8x18 20x7x8 19x9x2 20x17x2 2x29x10 19x25x1 28x9x3 29x27x20 7x21x7 10x4x22 26x8x5 26x14x1 5x27x9 2x18x3 3x27x17 30x17x23 30x11x20 4x6x7 6x29x27 30x16x20 24x30x28 19x20x26 18x1x25 26x12x12 19x15x29 16x21x24 23x13x26 25x16x10 8x9x18 24x14x1 24x15x21 19x9x14 8x23x11 22x2x16 29x9x26 3x16x25 15x20x30 3x11x12 15x2x3 13x7x4 2x7x27 9x26x11 30x24x19 28x17x21 10x8x2 11x15x26 10x12x20 24x24x27 25x26x16 13x4x20 25x13x11 12x22x3 20x7x1 12x18x6 26x8x20 14x2x7 23x12x1 26x24x24 27x26x23 26x17x5 17x24x2 26x5x6 23x5x1 5x18x30 24x21x19 5x28x11 21x20x14 25x4x22 26x24x11 7x5x8 13x1x30 5x1x6 14x5x2 8x11x7 13x20x1 17x30x14 29x22x10 12x26x3 27x17x3 26x27x4 5x26x17 22x11x19 8x26x3 24x19x22 7x1x4 6x27x30 4x28x14 16x14x18 4x5x20 19x25x4 15x15x1 10x14x14 16x18x24 21x27x15 5x5x10 1x7x13 16x2x8 13x15x11 3x25x10 20x29x8 12x3x2 10x13x12 25x27x1 11x30x19 7x19x13 27x6x18 16x21x19 21x29x5 16x23x12 29x19x15 5x5x10 27x15x1 13x16x22 29x19x5 8x12x9 3x18x5 13x25x3 5x9x21 10x20x16 9x9x11 23x21x1 22x2x15 27x8x13 23x7x3 26x30x15 29x15x16 16x27x13 2x18x9 10x27x8 20x9x25 10x2x17 16x13x13 21x26x1 27x26x24 9x30x16 19x17x28 25x15x1 10x26x6 10x11x11 5x26x25 30x4x15 9x8x23 14x25x7 8x28x8 28x18x24 4x4x25 16x25x11 17x27x8 15x16x9 24x13x21 17x3x27 27x5x26 8x27x12 29x2x8 24x23x30 1x30x21 6x18x20 13x14x12 25x30x23 24x6x24 12x7x21 11x6x8 8x30x30 26x3x12 28x6x5 18x7x1 7x6x20 14x16x18 11x22x15 4x20x10 19x24x19 8x24x11 4x9x10 6x6x22 10x9x29 1x5x28 19x25x29 20x30x3 15x13x13 9x9x24 20x14x29 26x24x13 2x25x8 10x26x2 12x19x12 18x6x20 4x5x14 26x27x10 16x26x20 3x21x15 2x26x18 14x11x17 26x26x25 10x1x11 17x19x19 27x28x26 9x2x10 19x30x15 23x30x14 15x3x20 2x14x22 21x18x8 22x4x29 19x6x29 9x26x29 16x10x9 22x12x22 13x28x14 25x14x28 28x3x30 10x17x1 10x27x22 10x23x19 14x25x9 11x24x8 30x25x10 22x13x28 2x7x6 11x20x8 9x22x14 19x16x9 11x24x4 11x17x2 6x4x10 26x10x10 12x14x5 27x10x3 15x3x6 11x7x19 22x10x12 21x26x10 13x20x3 27x8x8 1x24x23 24x9x22 23x17x23 3x28x19 2x20x28 23x17x24 26x1x4 4x1x12 5x6x16 13x22x13 25x21x21 20x21x12 9x24x25 17x16x12 12x28x9 18x16x27 29x12x2 30x12x15 24x11x10 4x9x22 4x24x5 19x11x5 6x25x6 1x20x17 22x8x21 11x26x4 16x19x3 8x12x8 13x2x18 10x5x11 8x12x17 21x2x5 26x17x26 23x18x17 28x11x14 1x4x27 29x5x28 5x9x10 5x7x25 20x15x27 15x11x17 12x14x1 29x14x4 18x14x18 14x25x24 26x14x18 13x8x11 30x1x23 3x4x12 12x24x9 8x6x16 14x15x30 12x30x8 22x11x18 16x30x28 17x18x4 13x14x23 2x28x8 3x28x30 29x30x8 4x6x26 6x30x17 11x30x30 19x4x3 12x15x20 22x28x4 26x30x2 6x12x7 1x10x5 25x29x7 17x9x18 16x21x29 21x14x7 15x16x11 26x6x15 8x24x7 2x20x4 2x9x3 19x8x13 18x7x22 27x14x17 2x13x8 18x15x26 15x27x27 18x11x15 1x29x20 21x12x11 20x2x15 28x23x9 1x1x17 7x23x9 30x9x27 9x16x18 15x24x28 30x11x18 29x26x10 9x5x25 2x1x19 14x3x14 6x3x6 30x15x20 20x17x27 28x10x9 14x24x28 17x11x6 12x3x6 8x8x15 23x14x21 11x21x7 5x13x30 4x29x25 30x28x24 18x4x9 3x15x6 13x9x19 30x14x7 7x9x9 17x11x26 24x26x13 16x21x16 27x17x25 2x21x11 9x11x27 3x3x7 13x8x14 20x20x26 13x29x22 30x11x1 7x10x19 27x5x9 23x17x15 21x6x13 24x15x16 18x4x14 18x16x6 22x11x18 14x2x5 15x3x7 10x20x29 16x1x10 30x23x1 10x15x11 17x14x5 22x8x13 7x11x28 26x17x3 2x23x2 28x13x19 18x12x28 22x23x16 14x12x1 20x8x19 17x19x13 29x2x12 2x26x27 29x16x4 13x8x18 16x15x30 23x16x2 28x8x27 21x8x23 13x20x26 19x6x17 17x30x15 7x4x30 2x13x30 18x7x19 4x13x27 8x6x5 18x20x25 2x3x30 23x27x13 22x30x4 23x25x25 23x16x19 25x3x1 5x6x15 11x29x12 25x24x7 16x7x20 20x3x2 12x27x15 16x10x12 1x3x14 22x1x26 2x24x18 11x29x16 15x2x9 10x1x24 21x8x11 30x11x23 6x30x21 13x27x29 14x6x5 18x29x19 12x4x28 29x3x14 10x30x28 5x7x15 14x1x10 9x25x14 7x24x18 28x17x21 18x13x25 26x15x1 21x1x19 12x16x21 4x6x13 7x15x26 17x19x5 12x28x2 1x20x19 27x7x5 17x26x8 12x15x19 5x23x10 8x2x8 16x13x12 14x27x1 26x29x3 24x16x14 14x13x13 7x22x23 2x9x30 4x27x8 26x27x15 23x1x6 25x29x18 5x18x1 20x8x20 5x10x25 30x25x15 7x22x25 28x26x17 29x4x1 21x11x27 20x9x8 25x22x12 2x11x11 23x2x16 23x27x20 2x13x28 27x2x24 11x1x17 12x4x27 16x20x22 30x12x10 5x15x4 5x2x27 12x4x25 1x16x4 27x4x4 21x16x3 27x26x3 24x6x6 24x12x12 20x20x25 8x29x2 21x4x5 2x4x8 4x13x19 3x20x10 12x15x16 6x5x4 12x16x20 22x19x17 8x17x22 25x16x15 7x1x19 10x1x7 23x23x5 28x6x12 2x25x12 10x27x12 24x27x19 14x14x20 4x1x5 16x27x29 20x20x24 28x24x30 6x15x15 9x15x30 23x26x3 17x24x21 22x25x25 18x29x10 20x25x1 24x11x16 20x7x21 20x7x9 7x26x2 5x18x1 16x26x28 4x10x18 27x30x21 26x9x9 8x16x14 6x27x8 28x9x20 13x13x4 9x18x16 18x15x18 22x19x14 14x10x17 25x29x11 1x18x19 8x11x26 18x6x14 30x24x13 27x1x27 15x9x3 2x29x17 2x26x21 22x9x9 20x20x20 22x28x2 26x5x16 11x3x14 21x16x16 18x26x7 18x30x6 7x11x12 15x10x2 27x2x16 27x30x24 28x14x24 7x4x8 6x28x15 13x19x1 22x26x30 7x30x24 2x17x21 19x26x2 19x24x15 14x23x2 21x27x15 30x15x14 21x29x5 23x30x2 4x1x2 15x5x13 21x2x30 20x7x16 1x21x25 2x25x1 12x29x5 28x13x16 26x3x12 29x20x23 28x12x20 4x30x8 16x15x16 6x16x29 2x28x13 24x25x2 26x15x22 17x20x11 18x12x7 19x1x18 8x27x13 22x16x8 19x26x17 13x11x10 22x12x3 13x12x14 29x17x9 6x14x10 14x20x10 8x26x9 25x13x22 3x30x25 14x28x1 30x29x12 3x17x15 3x24x14 28x24x22 16x6x1 20x25x14 17x17x13 6x19x27 10x15x20 8x23x20 7x29x21 18x9x25 10x5x22 2x27x27 16x18x30 15x5x12 26x29x29 28x11x10 9x29x28 24x15x23 26x9x10 5x1x25 22x27x16 7x29x3 1x3x5 8x7x29 19x21x11 28x13x30 17x16x20 5x10x25 9x14x15 15x14x23 16x4x17 21x8x2 9x9x8 22x22x4 10x2x27 12x19x10 15x29x4 22x14x7 29x18x5 1x7x27 24x1x15 23x23x26 12x17x23 26x10x24 8x22x2 8x1x10 22x19x12 2x23x13 11x27x25 26x15x27 27x7x21 18x9x6 22x21x22 7x12x26 23x21x13 14x3x8 5x9x28 29x29x15 27x25x23 12x2x24 8x2x20 29x19x4 12x24x29 2x27x28 14x20x9 28x6x25 18x29x8 19x11x30 15x11x23 18x7x7 14x20x14 26x18x22 27x25x13 12x10x30 30x2x7 28x10x1 18x10x30 22x11x5 22x16x3 25x15x9 5x10x24 4x28x8 19x24x18 3x4x25 14x4x30 11x26x3 12x12x12 26x7x24 3x2x14 1x27x7 2x2x13 3x26x26 12x4x11 12x17x20 4x19x30 5x18x10 17x6x18 19x30x20 11x2x17 30x13x19 22x23x7 17x28x2 5x17x30 7x11x4 21x26x18 15x28x4 5x6x27 12x6x16 9x17x12 27x20x5 14x5x20 27x14x6 2x14x21 4x28x30 24x5x1 19x29x29 11x23x1 8x16x21 3x17x19 10x13x5 20x21x16 23x3x6 27x26x11 3x2x22 14x3x5 10x9x8" # star 1 total_paper = 0 # star 2 total_ribbon = 0 input.each_line do |line| h,d,w = line.split('x').map(&:to_i).sort paper = 3*h*d + 2*d*w + 2*w*h total_paper += paper ribbon = 2*h + 2*d + h*d*w total_ribbon += ribbon end puts "Total paper %d ft²"%total_paper puts "Total ribbon %d ft"%total_ribbon
711265a6-2d48-11e5-bb5c-7831c1c36510 7118a0ba-2d48-11e5-9033-7831c1c36510 7118a0ba-2d48-11e5-9033-7831c1c36510
binary search tree' =begin Write a method to check that a binary tree ↴ is a valid binary search tree. =end class BinaryTreeNode attr_accessor :value attr_reader :left, :right def initialize(value) @value = value @left = nil @right = nil end def insert_left(value) @left = BinaryTreeNode.new(value) return @left end def insert_right(value) @right = BinaryTreeNode.new(value) return @right end end def is_binary_search_tree(root) nodes = [root] while !nodes.empty? node = nodes.pop if node.left return false if node.value <= node.left.value nodes.push(node.left) end if node.right return false if node.value >= node.right.value nodes.push(node.right) end end return true end root = BinaryTreeNode.new(5) root.insert_left(3) root.insert_right(8) root.right.insert_left(7) root.right.insert_right(9) root.right.right.insert_right(10) puts is_binary_search_tree(root)
require 'benchmark' require 'ffi' iter = 100000 module Posix extend FFI::Library attach_function :getuid, [], :uint end puts "uid=#{Process.pid} Posix.getuid=#{Posix.getuid}" puts "Benchmark FFI getuid performance, #{iter}x calls" 10.times { puts Benchmark.measure { iter.times { Posix.getuid } } } puts "Benchmark Process.uid performance, #{iter}x calls" 10.times { puts Benchmark.measure { iter.times { Process.uid } } } Add Invoker#call0 getuid benchmark require 'benchmark' require 'ffi' iter = 100000 module Posix extend FFI::Library attach_function :getuid, [], :uint end puts "uid=#{Process.pid} Posix.getuid=#{Posix.getuid}" puts "Benchmark FFI getuid performance, #{iter}x calls" 10.times { puts Benchmark.measure { iter.times { Posix.getuid } } } puts "Benchmark FFI Invoker#call0() getuid performance, #{iter}x calls" invoker = FFI.create_invoker(nil, 'getuid', [], :uint) 10.times { puts Benchmark.measure { iter.times { invoker.call0() } } } puts "Benchmark Process.uid performance, #{iter}x calls" 10.times { puts Benchmark.measure { iter.times { Process.uid } } }
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "bicycle" s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Stuart Chinery"] s.date = "2012-06-06" s.description = "A conveniance gem for cycling through a set of values, much like the 'cycle' functionality found in Rails, but is independant of which framework you use so will run in Sinatra, Padrino or straight up Ruby itself." s.email = "sleepingstu@gmail.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ ".document", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "bicycle.gemspec", "lib/bicycle.rb", "test/helper.rb", "test/test_bicycle.rb" ] s.homepage = "http://github.com/sleepingstu/bicycle" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.19" s.summary = "Why walk when you can cycle" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<minitest>, [">= 0"]) s.add_development_dependency(%q<yard>, ["~> 0.6.0"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<turn>, ["~> 0.9.5"]) else s.add_dependency(%q<minitest>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.6.0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<turn>, ["~> 0.9.5"]) end else s.add_dependency(%q<minitest>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.6.0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<turn>, ["~> 0.9.5"]) end end Regenerate gemspec for version 0.1.0 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "bicycle" s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Stuart Chinery"] s.date = "2012-06-06" s.description = "A convenience gem for cycling through a set of values, ported from the 'cycle' functionality found in Rails. It is independent of which framework you use so will run in Sinatra, Padrino or straight up Ruby itself." s.email = "sleepingstu@gmail.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ ".document", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "bicycle.gemspec", "lib/bicycle.rb", "test/helper.rb", "test/test_bicycle.rb" ] s.homepage = "http://github.com/sleepingstu/bicycle" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.19" s.summary = "Why walk when you can cycle" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<minitest>, [">= 0"]) s.add_development_dependency(%q<yard>, ["~> 0.6.0"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<turn>, ["~> 0.9.5"]) s.add_development_dependency(%q<debugger>, [">= 0"]) else s.add_dependency(%q<minitest>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.6.0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<turn>, ["~> 0.9.5"]) s.add_dependency(%q<debugger>, [">= 0"]) end else s.add_dependency(%q<minitest>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.6.0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<turn>, ["~> 0.9.5"]) s.add_dependency(%q<debugger>, [">= 0"]) end end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'biffbot/version' Gem::Specification.new do |gem| gem.name = 'biffbot' gem.version = Biffbot::VERSION gem.authors = ['Anurag Mohanty'] gem.email = ['tevren@gmail.com'] gem.description = 'Ruby gem to connect to diffbot\'s article api' gem.summary = 'Given a url, pulls article content using diffbot\'s article extractor' gem.homepage = 'https://github.com/tevren/biffbot' gem.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) gem.executables = gem.files.grep(/^bin\//) { |f| File.basename(f) } gem.test_files = gem.files.grep(/^(test|spec|features)\//) gem.require_paths = ['lib'] gem.add_dependency('httparty') gem.add_dependency('json', '~> 1.8') gem.add_dependency('hashie', '~> 3.3') gem.add_development_dependency('rspec') gem.add_development_dependency('rubocop') gem.add_development_dependency('dotenv') end adding rake to the gemspec # -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'biffbot/version' Gem::Specification.new do |gem| gem.name = 'biffbot' gem.version = Biffbot::VERSION gem.authors = ['Anurag Mohanty'] gem.email = ['tevren@gmail.com'] gem.description = 'Ruby gem to connect to diffbot\'s article api' gem.summary = 'Given a url, pulls article content using diffbot\'s article extractor' gem.homepage = 'https://github.com/tevren/biffbot' gem.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) gem.executables = gem.files.grep(/^bin\//) { |f| File.basename(f) } gem.test_files = gem.files.grep(/^(test|spec|features)\//) gem.require_paths = ['lib'] gem.add_dependency('httparty') gem.add_dependency('json', '~> 1.8') gem.add_dependency('hashie', '~> 3.3') gem.add_development_dependency('rspec') gem.add_development_dependency('rake') gem.add_development_dependency('rubocop') gem.add_development_dependency('dotenv') end
### VERSION "nCore" ## ../nCore/bin/CircleBP.rb require_relative 'BaseLearningExperiment' class Neuron include NonMonotonicIOFunction end #class OutputNeuron # include NonMonotonicIOFunction #end class Experiment def setParameters args = { :experimentNumber => experimentLogger.experimentNumber, :descriptionOfExperiment => descriptionOfExperiment, # training parameters re. Output Error :outputErrorLearningRate => 0.3, # 0.03, :minMSE => 0.001, :maxNumEpochs => 12e3, # Network Architecture and initial weights :numberOfInputNeurons => 2, :numberOfHiddenNeurons => 20, :numberOfOutputNeurons => 1, :weightRange => 1.0, :typeOfLink => Link, # Training Set parameters :numberOfExamples => (numberOfExamples = 24), :firstExamplesAngleToXAxis => 0.0, :firstExamplesAngleToXAxisForTesting => 15.0, # Recording and database parameters :neuronToDisplay => 2, :intervalForSavingNeuronData => 10000, :intervalForSavingDetailedNeuronData => 10000, :intervalForSavingTrainingData => 100, } end def createTrainingSet firstExamplesAngleToXAxis = args[:firstExamplesAngleToXAxis] numberOfExamples = args[:numberOfExamples] examples = createExamples(firstExamplesAngleToXAxis, numberOfExamples) return examples end def createTestingSet firstExamplesAngleToXAxisForTesting = args[:firstExamplesAngleToXAxisForTesting] numberOfExamples = args[:numberOfExamples] testingExamples = createExamples(firstExamplesAngleToXAxisForTesting, numberOfExamples) args[:testingExamples] = testingExamples end def createExamples(firstExamplesAngleToXAxis, numberOfExamples) numberOfClasses = 2 numExamplesPerClass = numberOfExamples / numberOfClasses angleBetweenExamplesInDegrees = 360.0 / numExamplesPerClass radiusArray = [1.0, 1.3] desiredOutput = [0.0, 1.0] examples = [] numExamplesPerClass.times do |exampleNumberWithinClass| angle = (angleBetweenExamplesInDegrees * exampleNumberWithinClass) + firstExamplesAngleToXAxis angleInRadians = angle * (360.0/(2.0 * Math::PI)) numberOfClasses.times do |indexToClass| radius = radiusArray[indexToClass] x = radius * Math.cos(angleInRadians) y = radius * Math.sin(angleInRadians) aPoint = [x, y] targets = [desiredOutput[indexToClass]] exampleNumber = if (indexToClass == 1) exampleNumberWithinClass + numExamplesPerClass else exampleNumberWithinClass end anExample = {:inputs => aPoint, :targets => targets, :exampleNumber => exampleNumber, :class => indexToClass} examples << anExample end end STDERR.puts "Error: Incorrect Number of Examples Generated and/or Specified" unless (examples.length == args[:numberOfExamples]) examples end def createNetworkAndTrainer network = Standard3LayerNetwork.new(args) theTrainer = StandardBPTrainingSupervisor.new(examples, network, args) return network, theTrainer end end ###################################### START of Main Learning ########################################## experiment = Experiment.new("NonMonHiddenLayerCircleBP the output layer io is sigmoid", randomNumberSeed=0) experiment.performSimulation() CircleBP generalization mse improves by 10:1 using non-monotonic io function for the hidden layer neurons, while keeping the output neuron's io function the simple sigmoid. ### VERSION "nCore" ## ../nCore/bin/CircleBP.rb require_relative 'BaseLearningExperiment' class Neuron include NonMonotonicIOFunction end #class OutputNeuron # include NonMonotonicIOFunction #end class Experiment def setParameters args = { :experimentNumber => experimentLogger.experimentNumber, :descriptionOfExperiment => descriptionOfExperiment, # training parameters re. Output Error :outputErrorLearningRate => 0.3, # 0.03, :minMSE => 0.001, :maxNumEpochs => 12e3, # Network Architecture and initial weights :numberOfInputNeurons => 2, :numberOfHiddenNeurons => 20, :numberOfOutputNeurons => 1, :weightRange => 1.0, :typeOfLink => Link, # Training Set parameters :numberOfExamples => (numberOfExamples = 24), :firstExamplesAngleToXAxis => 0.0, :firstExamplesAngleToXAxisForTesting => 15.0, # Recording and database parameters :neuronToDisplay => 2, :intervalForSavingNeuronData => 10000, :intervalForSavingDetailedNeuronData => 10000, :intervalForSavingTrainingData => 100, } end def createTrainingSet firstExamplesAngleToXAxis = args[:firstExamplesAngleToXAxis] numberOfExamples = args[:numberOfExamples] examples = createExamples(firstExamplesAngleToXAxis, numberOfExamples) return examples end def createTestingSet firstExamplesAngleToXAxisForTesting = args[:firstExamplesAngleToXAxisForTesting] numberOfExamples = args[:numberOfExamples] testingExamples = createExamples(firstExamplesAngleToXAxisForTesting, numberOfExamples) args[:testingExamples] = testingExamples end def createExamples(firstExamplesAngleToXAxis, numberOfExamples) numberOfClasses = 2 numExamplesPerClass = numberOfExamples / numberOfClasses angleBetweenExamplesInDegrees = 360.0 / numExamplesPerClass radiusArray = [1.0, 1.3] desiredOutput = [0.0, 1.0] examples = [] numExamplesPerClass.times do |exampleNumberWithinClass| angle = (angleBetweenExamplesInDegrees * exampleNumberWithinClass) + firstExamplesAngleToXAxis angleInRadians = angle * (360.0/(2.0 * Math::PI)) numberOfClasses.times do |indexToClass| radius = radiusArray[indexToClass] x = radius * Math.cos(angleInRadians) y = radius * Math.sin(angleInRadians) aPoint = [x, y] targets = [desiredOutput[indexToClass]] exampleNumber = if (indexToClass == 1) exampleNumberWithinClass + numExamplesPerClass else exampleNumberWithinClass end anExample = {:inputs => aPoint, :targets => targets, :exampleNumber => exampleNumber, :class => indexToClass} examples << anExample end end STDERR.puts "Error: Incorrect Number of Examples Generated and/or Specified" unless (examples.length == args[:numberOfExamples]) examples end def createNetworkAndTrainer network = Standard3LayerNetwork.new(args) theTrainer = StandardBPTrainingSupervisor.new(examples, network, args) return network, theTrainer end end ###################################### START of Main Learning ########################################## experiment = Experiment.new("NonMonHiddenLayerCircleBP the output layer io is sigmoid", randomNumberSeed=0) experiment.performSimulation()
#!/usr/bin/env ruby require 'optparse' $:.unshift(File.expand_path("../../lib", __FILE__)) options = {:katello_apidoc_url => "http://localhost:3000/katello/apidoc"} OptionParser.new do |opts| opts.banner = "Script for generating API bindings for Katello API from Apipie docs." opts.on("-u", "--url KATELLO_APIDOC_URL", "By default #{options[:katello_apidoc_url]}") do |val| options[:katello_apidoc_url] = val end end.parse! require 'katello_api/generator/base.rb' options[:katello_apidoc_url].sub!(/\Z\//,"") KatelloApi::Generator::Base.start(options[:katello_apidoc_url]) system("yard doc") generate.rb - catch invalidoption and display error #!/usr/bin/env ruby $:.unshift(File.expand_path("../../lib", __FILE__)) require 'optparse' require 'katello_api/generator/base' options = {:katello_apidoc_url => "http://localhost:3000/katello/apidoc"} optparse = OptionParser.new do |opts| opts.banner = <<-BANNER Generate Ruby API bindings for Katello's API from Apipie docs. USAGE: #{__FILE__} [FLAGS] BANNER opts.on("-u", "--url KATELLO_APIDOC_URL", "By default #{options[:katello_apidoc_url]}") do |val| options[:katello_apidoc_url] = val end end begin optparse.parse! options[:katello_apidoc_url].sub!(/\Z\//, "") KatelloApi::Generator::Base.start(options[:katello_apidoc_url]) system("yard doc") rescue OptionParser::InvalidOption => e puts "#{e.message}\n\n#{optparse}" exit 1 end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{radiant-copy_move-extension} s.version = "2.4.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Benny Degezelle", "Andrew vonderLuft"] s.date = %q{2011-06-27} s.description = %q{With this extension you can copy or move a page with or without its children.} s.email = %q{benny@gorilla-webdesign.be} s.extra_rdoc_files = [ "LICENSE", "README.textile", "TODO" ] s.files = [ "HELP.rdoc", "LICENSE", "README.textile", "Rakefile", "TODO", "VERSION", "app/helpers/copy_move_helper.rb", "app/views/admin/pages/_copy_move_extra_td.html.haml", "app/views/admin/pages/_copy_move_extra_th.html.haml", "app/views/admin/pages/_copy_move_form.html.haml", "app/views/admin/pages/copy_children.html.haml", "app/views/admin/pages/copy_page.html.haml", "app/views/admin/pages/copy_tree.html.haml", "app/views/admin/pages/move_page.html.haml", "config/locales/de.yml", "config/locales/en.yml", "config/locales/nl.yml", "config/routes.rb", "copy_move_extension.rb", "lib/copy_move.rb", "lib/copy_move/controller.rb", "lib/copy_move/model.rb", "lib/tasks/copy_move_extension_tasks.rake", "public/images/admin/copy-move.png", "public/images/admin/page_white.png", "public/images/admin/page_white_copy.png", "public/images/admin/page_white_go.png", "public/images/admin/page_white_stack.png", "radiant-copy_move-extension.gemspec", "spec/controllers/copy_move_controller_spec.rb", "spec/models/copy_move_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{https://github.com/jomz/radiant-copy-move} s.require_paths = ["lib"] s.rubygems_version = %q{1.6.2} s.summary = %q{Copy/Move extension for Radiant CMS} s.test_files = [ "spec/controllers/copy_move_controller_spec.rb", "spec/models/copy_move_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<radiant>, [">= 1.0.0.rc2"]) else s.add_dependency(%q<radiant>, [">= 1.0.0.rc2"]) end else s.add_dependency(%q<radiant>, [">= 1.0.0.rc2"]) end end update gemspec # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "radiant-copy_move-extension" s.version = "2.4.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Benny Degezelle", "Andrew vonderLuft"] s.date = "2013-02-18" s.description = "With this extension you can copy or move a page with or without its children." s.email = "benny@gorilla-webdesign.be" s.extra_rdoc_files = [ "LICENSE", "README.textile", "TODO" ] s.files = [ "HELP.rdoc", "LICENSE", "README.textile", "Rakefile", "TODO", "VERSION", "app/helpers/copy_move_helper.rb", "app/views/admin/pages/_copy_move_extra_td.html.haml", "app/views/admin/pages/_copy_move_extra_th.html.haml", "app/views/admin/pages/_copy_move_form.html.haml", "app/views/admin/pages/copy_children.html.haml", "app/views/admin/pages/copy_page.html.haml", "app/views/admin/pages/copy_tree.html.haml", "app/views/admin/pages/move_page.html.haml", "config/locales/de.yml", "config/locales/en.yml", "config/locales/nl.yml", "config/routes.rb", "copy_move_extension.rb", "lib/copy_move.rb", "lib/copy_move/controller.rb", "lib/copy_move/model.rb", "lib/tasks/copy_move_extension_tasks.rake", "public/images/admin/copy-move.png", "public/images/admin/page_white.png", "public/images/admin/page_white_copy.png", "public/images/admin/page_white_go.png", "public/images/admin/page_white_stack.png", "radiant-copy_move-extension.gemspec", "spec/controllers/copy_move_controller_spec.rb", "spec/models/copy_move_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = "https://github.com/jomz/radiant-copy-move" s.require_paths = ["lib"] s.rubygems_version = "1.8.25" s.summary = "Copy/Move extension for Radiant CMS" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<radiant>, [">= 1.0.0.rc2"]) else s.add_dependency(%q<radiant>, [">= 1.0.0.rc2"]) end else s.add_dependency(%q<radiant>, [">= 1.0.0.rc2"]) end end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "rails_admin_googleanalytics/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "rails_admin_googleanalytics" s.version = RailsAdminGoogleanalytics::VERSION s.authors = ["Richard Peng"] s.email = ["richard@richardpeng.com"] s.homepage = "http://richardpeng.com" s.summary = "Google Analytics tab for Rails Admin" s.description = "Show some basic statistics from within the Rails Admin interface." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.add_dependency "rails", "= 4.2.4" s.add_dependency "google-api-client", ">= 0.5" end move rails dep version down $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "rails_admin_googleanalytics/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "rails_admin_googleanalytics" s.version = RailsAdminGoogleanalytics::VERSION s.authors = ["Richard Peng"] s.email = ["richard@richardpeng.com"] s.homepage = "http://richardpeng.com" s.summary = "Google Analytics tab for Rails Admin" s.description = "Show some basic statistics from within the Rails Admin interface." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.add_dependency "rails", "~> 3.2.13" s.add_dependency "google-api-client", ">= 0.5" end
spaced 20160804 (new formula) Closes #4161. Signed-off-by: Torsten Seemann <feac082ffa4709ec52de15779c15d209ea844842@seemann.id.au> class Spaced < Formula desc "Spaced-Words for alignment-free sequence comparison" homepage "http://spaced.gobics.de/" # doi "10.1186/s13015-015-0032-x" # tag "bioinformatics" url "http://spaced.gobics.de/content/spaced.tar.gz" version "20160804" sha256 "016e9b565dc7189a69bd87e34b0df2f8a85831bd7f765b4f43b5612a2cff5fb1" needs :cxx11 needs :openmp def install # Fix: error: 'default_random_engine' in namespace 'std' does not name a type inreplace "src/patternset.h", "#include <vector>", "#include <vector>\n#include <random>\n" system "make" bin.install "spaced" doc.install "README", "COPYING" end test do assert_match "Jensen-Shannon", shell_output("#{bin}/spaced 2>&1", 0) end end
class Spades < Formula desc "SPAdes: de novo genome assembly" homepage "http://bioinf.spbau.ru/spades/" url "http://spades.bioinf.spbau.ru/release3.9.0/SPAdes-3.9.0.tar.gz" sha256 "77436ac5945aa8584d822b433464969a9f4937c0a55c866205655ce06a72ed29" # tag "bioinformatics" # doi "10.1089/cmb.2012.0021" bottle do cellar :any revision 1 sha256 "244ebfd9ed2461e003dc2ebb9030b11ef0c2e0e705b7da0fc533feb4c3b23d71" => :el_capitan sha256 "d807d6322131bde60c4da57bb90136f549f48532dbc1b05d7268d9cbf4dc617e" => :yosemite sha256 "c44b851d733c90d1109abeb8daa6cd68d66327eddf84c629494e373283fe0377" => :mavericks sha256 "f7562b7fb92d4771a3cd5d3499e6cf2338581315fafef58e1ae3ed94d1b5b2f8" => :x86_64_linux end depends_on "cmake" => :build depends_on "gcc" depends_on :python if OS.linux? needs :openmp fails_with :gcc => "4.7" do cause "Compiling SPAdes requires GCC >= 4.7 for OpenMP 3.1 support" end def install mkdir "src/build" do system "cmake", "..", *std_cmake_args system "make", "install" end end test do system "spades.py", "--test" end end spades: apply jemalloc fix for Sierra (#4624) This fix is already in the latest release of jemalloc, but hasn't made its way over to the vendored version of jemalloc in SPAdes yet. class Spades < Formula desc "SPAdes: de novo genome assembly" homepage "http://bioinf.spbau.ru/spades/" url "http://spades.bioinf.spbau.ru/release3.9.0/SPAdes-3.9.0.tar.gz" sha256 "77436ac5945aa8584d822b433464969a9f4937c0a55c866205655ce06a72ed29" # tag "bioinformatics" # doi "10.1089/cmb.2012.0021" bottle do cellar :any revision 1 sha256 "244ebfd9ed2461e003dc2ebb9030b11ef0c2e0e705b7da0fc533feb4c3b23d71" => :el_capitan sha256 "d807d6322131bde60c4da57bb90136f549f48532dbc1b05d7268d9cbf4dc617e" => :yosemite sha256 "c44b851d733c90d1109abeb8daa6cd68d66327eddf84c629494e373283fe0377" => :mavericks sha256 "f7562b7fb92d4771a3cd5d3499e6cf2338581315fafef58e1ae3ed94d1b5b2f8" => :x86_64_linux end depends_on "cmake" => :build depends_on "gcc" depends_on :python if OS.linux? needs :openmp fails_with :gcc => "4.7" do cause "Compiling SPAdes requires GCC >= 4.7 for OpenMP 3.1 support" end # Fix malloc: *** malloc_zone_unregister() failed for 0x7fffb1c3c000 # Upstream issue "jemalloc upgrade needed to fix macOS Sierra" # Reported 20 Nov 2016 https://github.com/ablab/spades/issues/9 # Underlying jemalloc issue: https://github.com/jemalloc/jemalloc/pull/427 if MacOS.version >= :sierra patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/f31c35f/spades/jemalloc-sierra-fix.diff" sha256 "7f362d7e60b60147a41b449f34e6210370031e974a588c51347f869559cf0775" end end def install mkdir "src/build" do system "cmake", "..", *std_cmake_args system "make", "install" end end test do system "#{bin}/spades.py", "--test" end end
#!/usr/bin/env ruby $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'sp_store' def measure_time start = Time.now yield puts ( Time.now - start ) end # storage & cache information block_size = 2**20 block_count = 2048 node_cache_size = 2**9 session_cache_size = 64 load_store = true delete_store = false # choose between mock or real p_chip mock_p_chip = true # benchmark options write_data_gen = false run_benchmark = false test_command, test_type = ARGV[0], ARGV[1] if test_command if test_command == "--init" load_store = false elsif test_command == "--delete" delete_store = true else raise ArgumentError, "using --test <test_name> to run benchmark" unless test_command=="--test" raise ArgumentError, "test \"#{test_type}\" does not exist" unless SpStore::Benchmark::SyntheticBenchmark.method_defined? test_type run_benchmark = true end end ################ initialization ############################ # initialize sp_store controller sp_store_controller = nil measure_time do sp_store_controller = SpStore::Benchmark::StoreSetup.sp_store_controller( block_size, block_count, node_cache_size, session_cache_size, load_store, mock_p_chip ) puts "Initialization time for sp store (secs):" end # initialize bare controller bare_controller = nil measure_time do bare_controller = SpStore::Benchmark::StoreSetup.bare_controller( block_size, block_count, load_store ) puts "Initialization time for mock store (secs):" end ############### Benchmark Test Setup ######################## benchmark = SpStore::Benchmark::SyntheticBenchmark.new block_size, block_count, SpStore::Benchmark::StoreSetup.disk_directory, sp_store_controller, bare_controller # pre-generate write data measure_time do benchmark.generate_write_data_file puts "Write data pre-generation (secs):" end if write_data_gen ################### Running Benchmark ####################### eval "benchmark.#{ARGV[1]}" if run_benchmark ################### Delete Existing Store ################### SpStore::Storage::DiskStore.delete_store if delete_store SpStore::Mocks::FileStore.delete_store if delete_store use OptionParser #!/usr/bin/env ruby $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'sp_store' require 'optparse' ############## storage & cache information ################# block_size = 2**20 block_count = 2048 node_cache_size = 2**9 session_cache_size = 64 ################ parse command options ##################### options = {} optparse = OptionParser.new do|opts| # Set a banner, displayed at the top of the help screen. opts.banner = "Usage: sp_store [options]" # Define the options, and what they do options[:init] = false opts.on( '-i', '--init', 'Create a new disk storage' ) do options[:init] = true end options[:delete] = false opts.on( '-d', '--delete', 'Delete the disk storage' ) do options[:delete] = true end options[:mock_p] = false opts.on( '--mock-p', 'Use mock P chip for testing' ) do options[:mock_p] = true end options[:write_data] = false opts.on( '--write-data', 'Pre-generate random bytes for block write' ) do options[:write_data] = true end options[:test] = nil opts.on( '-t', '--test TEST-NAME', 'Run benchmark TEST-NAME' ) do |test_type| options[:test] = test_type end opts.on( '--block-size NUM', Integer, 'Block size (byte) (in log2)' ) do |size| options[:block_size] = size end opts.on( '--block-count NUM', Integer, 'Block count (in log2)' ) do |count| options[:block_count] = count end opts.on( '--cache-size NUM', Integer, 'Node cache size (in log2)') do |c_size| options[:cache_size] = c_size end # This displays the help screen opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end end.parse! ################## options setting ######################## block_size = 2**options[:block_size] if options[:block_size] && options[:init] && options[:block_size]!= 0 block_count = 2**options[:block_count] if options[:block_count] && options[:init] && options[:block_count]!= 0 node_cache_size = 2**options[:cache_size] if options[:cache_size] && options[:cache_size]!= 0 load_store = !options[:init] delete_store = options[:delete] # choose between mock or real p_chip mock_p_chip = options[:mock_p] # benchmark options write_data_gen = options[:write_data] run_benchmark = options[:test] test_type = options[:test] if run_benchmark raise ArgumentError, "test \"#{test_type}\" does not exist" unless SpStore::Benchmark::SyntheticBenchmark.method_defined? test_type end ################ helper functions ############################ def measure_time start = Time.now yield puts ( Time.now - start ) end ################ initialization ############################ # initialize sp_store controller sp_store_controller = nil measure_time do sp_store_controller = SpStore::Benchmark::StoreSetup.sp_store_controller( block_size, block_count, node_cache_size, session_cache_size, load_store, mock_p_chip ) puts "Initialization time for sp store (secs):" end # initialize bare controller bare_controller = nil measure_time do bare_controller = SpStore::Benchmark::StoreSetup.bare_controller( block_size, block_count, load_store ) puts "Initialization time for mock store (secs):" end ############### Benchmark Test Setup ######################## benchmark = SpStore::Benchmark::SyntheticBenchmark.new block_size, block_count, SpStore::Benchmark::StoreSetup.disk_directory, sp_store_controller, bare_controller # pre-generate write data measure_time do benchmark.generate_write_data_file puts "Write data pre-generation (secs):" end if write_data_gen ################### Running Benchmark ####################### eval "benchmark.#{test_type}" if run_benchmark ################### Delete Existing Store ################### SpStore::Storage::DiskStore.delete_store if delete_store SpStore::Mocks::FileStore.delete_store if delete_store
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "expiring_token" s.version = "0.0.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Michael Moen"] s.date = "2011-11-10" s.description = "TODO: Generate and validate time expiring tokens" s.email = "moen@captainu.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "lib/expiring_token.rb", "spec/expiring_token_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/captainu/expiring_token" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.10" s.summary = "TODO: Generate and validate time expiring tokens" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<rcov>, [">= 0"]) end end gemspec # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "expiring_token" s.version = "0.0.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Michael Moen"] s.date = "2011-11-10" s.description = "Generate and validate time expiring tokens" s.email = "moen@captainu.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "expiring_token.gemspec", "lib/expiring_token.rb", "spec/expiring_token_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/captainu/expiring_token" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.10" s.summary = "Generate and validate time expiring tokens" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
require "mkmf" require "date" RMAGICK_VERS = "0.0.0" MIN_RUBY_VERS = "1.8.5" MIN_RUBY_VERS_NO = MIN_RUBY_VERS.tr(".","").to_i MIN_IM_VERS = "6.4.9" MIN_IM_VERS_NO = MIN_IM_VERS.tr(".","").to_i # Test for a specific value in an enum type def have_enum_value(enum, value, headers=nil, &b) checking_for "#{enum}.#{value}" do if try_compile(<<"SRC", &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ int main() { #{enum} t = #{value}; t = t; return 0; } SRC $defs.push(format("-DHAVE_ENUM_%s", value.upcase)) true else false end end end # Test for multiple values of the same enum type def have_enum_values(enum, values, headers=nil, &b) values.each do |value| have_enum_value(enum, value, headers, &b) end end def exit_failure(msg) Logging::message msg message msg+"\n" exit(1) end # Seems like lots of people have multiple versions of ImageMagick installed. def check_multiple_imagemagick_versions() versions = [] path = ENV['PATH'].split(File::PATH_SEPARATOR) path.each do |dir| file = File.join(dir, "Magick-config") if File.executable? file vers = `#{file} --version`.chomp.strip prefix = `#{file} --prefix`.chomp.strip versions << [vers, prefix, dir] end end versions.uniq! if versions.size > 1 msg = "\nWarning: Found more than one ImageMagick installation. This could cause problems at runtime.\n" versions.each do |vers, prefix, dir| msg << " #{dir}/Magick-config reports version #{vers} is installed in #{prefix}\n" end msg << "Using #{versions[0][0]} from #{versions[0][1]}.\n\n" Logging::message msg message msg end end # Ubuntu (maybe other systems) comes with a partial installation of # ImageMagick in the prefix /usr (some libraries, no includes, and no # binaries). This causes problems when /usr/lib is in the path (e.g., using # the default Ruby installation). def check_partial_imagemagick_versions() prefix = config_string("prefix") matches = [ prefix+"/lib/lib?agick*", prefix+"/include/ImageMagick", prefix+"/bin/Magick-config", ].map do |file_glob| Dir.glob(file_glob) end matches.delete_if { |arr| arr.empty? } if 0 < matches.length and matches.length < 3 msg = "\nWarning: Found a partial ImageMagick installation. Your operating system likely has some built-in ImageMagick libraries but not all of ImageMagick. This will most likely cause problems at both compile and runtime.\nFound partial installation at: "+prefix+"\n" Logging::message msg message msg end end if RUBY_PLATFORM =~ /mswin/ abort <<END_MSWIN +----------------------------------------------------------------------------+ | This rmagick gem is for use only on Linux, BSD, OS X, and similar systems | | that have a gnu or similar toolchain installed. The rmagick-win32 gem is a | | pre-compiled version of RMagick bundled with ImageMagick for use on | | Microsoft Windows systems. The rmagick-win32 gem is available on RubyForge.| | See http://rmagick.rubyforge.org/install-faq.html for more information. | +----------------------------------------------------------------------------+ END_MSWIN end unless checking_for("Ruby version >= #{MIN_RUBY_VERS}") do version = RUBY_VERSION.tr(".","").to_i version >= MIN_RUBY_VERS_NO end exit_failure "Can't install RMagick #{RMAGICK_VERS}. Ruby #{MIN_RUBY_VERS} or later required.\n" end # Magick-config is not available on Windows if RUBY_PLATFORM !~ /mswin|mingw/ # Check for compiler. Extract first word so ENV['CC'] can be a program name with arguments. config = defined?(RbConfig) ? ::RbConfig : ::Config cc = (ENV["CC"] or config::CONFIG["CC"] or "gcc").split(' ').first unless find_executable(cc) exit_failure "No C compiler found in ${ENV['PATH']}. See mkmf.log for details." end # Check for Magick-config unless find_executable("Magick-config") exit_failure "Can't install RMagick #{RMAGICK_VERS}. Can't find Magick-config in #{ENV['PATH']}\n" end check_multiple_imagemagick_versions() check_partial_imagemagick_versions() # Ensure minimum ImageMagick version unless checking_for("ImageMagick version >= #{MIN_IM_VERS}") do version = `Magick-config --version`.chomp.tr(".","").to_i version >= MIN_IM_VERS_NO end exit_failure "Can't install RMagick #{RMAGICK_VERS}. You must have ImageMagick #{MIN_IM_VERS} or later.\n" end $magick_version = `Magick-config --version`.chomp # Save flags $CFLAGS = ENV["CFLAGS"].to_s + " " + `Magick-config --cflags`.chomp $CPPFLAGS = ENV["CPPFLAGS"].to_s + " " + `Magick-config --cppflags`.chomp $LDFLAGS = ENV["LDFLAGS"].to_s + " " + `Magick-config --ldflags`.chomp $LOCAL_LIBS = ENV["LIBS"].to_s + " " + `Magick-config --libs`.chomp elsif RUBY_PLATFORM =~ /mingw/ # mingw `convert -version` =~ /Version: ImageMagick (\d+\.\d+\.\d+)-\d+ / abort "Unable to get ImageMagick version" unless $1 $magick_version = $1 if RUBY_PLATFORM =~ /x64/ $LOCAL_LIBS = '-lCORE_RL_magick_' else $LOCAL_LIBS = '-lCORE_RL_magick_ -lX11' end else # mswin `convert -version` =~ /Version: ImageMagick (\d+\.\d+\.\d+)-\d+ / abort "Unable to get ImageMagick version" unless $1 $magick_version = $1 $CFLAGS = "-W3" $CPPFLAGS = %Q{-I"C:\\Program Files\\Microsoft Platform SDK for Windows Server 2003 R2\\Include" -I"C:\\Program Files\\ImageMagick-#{$magick_version}-Q8\\include"} # The /link option is required by the Makefile but causes warnings in the mkmf.log file. $LDFLAGS = %Q{/link /LIBPATH:"C:\\Program Files\\Microsoft Platform SDK for Windows Server 2003 R2\\Lib" /LIBPATH:"C:\\Program Files\\ImageMagick-#{$magick_version}-Q8\\lib" /LIBPATH:"C:\\ruby\\lib"} $LOCAL_LIBS = 'CORE_RL_magick_.lib X11.lib' end #headers = %w{assert.h ctype.h errno.h float.h limits.h math.h stdarg.h stddef.h stdint.h stdio.h stdlib.h string.h time.h} headers = %w{assert.h ctype.h stdio.h stdlib.h math.h time.h} headers << "stdint.h" if have_header("stdint.h") # defines uint64_t headers << "sys/types.h" if have_header("sys/types.h") if have_header("wand/MagickWand.h") headers << "wand/MagickWand.h" else exit_failure "\nCan't install RMagick #{RMAGICK_VERS}. Can't find MagickWand.h." end if RUBY_PLATFORM !~ /mswin|mingw/ unless `Magick-config --libs`[/\bl\s*(MagickCore|Magick)\b/] exit_failure "Can't install RMagick #{RMAGICK_VERS}. " + "Can't find the ImageMagick library or one of the dependent libraries. " + "Check the mkmf.log file for more detailed information.\n" end end have_func("snprintf", headers) ["AcquireImage", # 6.4.1 "AffinityImage", # 6.4.3-6 "AffinityImages", # 6.4.3-6 "AutoGammaImageChannel", # 6.5.5-1 "AutoLevelImageChannel", # 6.5.5-1 "BlueShiftImage", # 6.5.4-3 "ColorMatrixImage", # 6.6.1-0 "ConstituteComponentTerminus", # 6.5.7-9 "DeskewImage", # 6.4.2-5 "DestroyConstitute", # 6.5.7-9(deprecated) "EncipherImage", # 6.3.8-6 "EqualizeImageChannel", # 6.3.6-9 "EvaluateImages", # 6.8.6-4 "FloodfillPaintImage", # 6.3.7 "FunctionImageChannel", # 6.4.8-8 "GetAuthenticIndexQueue", # 6.4.5-6 "GetAuthenticPixels", # 6.4.5-6 "GetImageAlphaChannel", # 6.3.9-2 "GetVirtualPixels", # 6.4.5-6 "LevelImageColors", # 6.4.2 "LevelColorsImageChannel", # 6.5.6-4 "LevelizeImageChannel", # 6.4.2 "LiquidRescaleImage", # 6.3.8-2 "MagickLibAddendum", # 6.5.9-1 "OpaquePaintImageChannel", # 6.3.7-10 "QueueAuthenticPixels", # 6.4.5-6 "RemapImage", # 6.4.4-0 "RemapImages", # 6.4.4-0 "RemoveImageArtifact", # 6.3.6 "RotationalBlurImage", # 6.8.8-9 "RotationalBlurImageChannel", # 6.8.8-9 "SelectiveBlurImageChannel", # 6.5.0-3 "SetImageAlphaChannel", # 6.3.6-9 "SetImageArtifact", # 6.3.6 "SetMagickMemoryMethods", # 6.4.1 "SparseColorImage", # 6.3.6-? "StatisticImage", # 6.6.8-6 "SyncAuthenticPixels", # 6.4.5-6 "TransformImageColorspace", # 6.5.1 "TransparentPaintImage", # 6.3.7-10 "TransparentPaintImageChroma" # 6.4.5-6 ].each do |func| have_func(func, headers) end checking_for("QueryMagickColorname() new signature") do if try_compile(<<"SRC") #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ int main() { MagickBooleanType okay; Image *image; MagickPixelPacket *color; char *name; ExceptionInfo *exception; okay = QueryMagickColorname(image, color, SVGCompliance, name, exception); return 0; } SRC $defs.push("-DHAVE_NEW_QUERYMAGICKCOLORNAME") true else false end end have_struct_member("Image", "type", headers) # ??? have_struct_member("DrawInfo", "kerning", headers) # 6.4.7-8 have_struct_member("DrawInfo", "interline_spacing", headers) # 6.5.5-8 have_struct_member("DrawInfo", "interword_spacing", headers) # 6.4.8-0 have_type("DitherMethod", headers) # 6.4.2 have_type("MagickFunction", headers) # 6.4.8-8 have_type("ImageLayerMethod", headers) # 6.3.6 replaces MagickLayerMethod have_type("long double", headers) #have_type("unsigned long long", headers) #have_type("uint64_t", headers) #have_type("__int64", headers) #have_type("uintmax_t", headers) #check_sizeof("unsigned long", headers) #check_sizeof("Image *", headers) have_enum_values("AlphaChannelType", ["CopyAlphaChannel", # 6.4.3-7 "BackgroundAlphaChannel"], headers) # 6.5.2-5 have_enum_values("CompositeOperator", ["BlurCompositeOp", # 6.5.3-7 "DistortCompositeOp", # 6.5.3-10 "LinearBurnCompositeOp", # 6.5.4-3 "LinearDodgeCompositeOp", # 6.5.4-3 "MathematicsCompositeOp", # 6.5.4-3 "PegtopLightCompositeOp", # 6.5.4-3 "PinLightCompositeOp", # 6.5.4-3 "VividLightCompositeOp"], headers) # 6.5.4-3 have_enum_values("CompressionType", ["DXT1Compression", # 6.3.9-3 "DXT3Compression", # 6.3.9-3 "DXT5Compression", # 6.3.9-3 "ZipSCompression", # 6.5.5-4 "PizCompression", # 6.5.5-4 "Pxr24Compression", # 6.5.5-4 "B44Compression", # 6.5.5-4 "B44ACompression"], headers) # 6.5.5-4 have_enum_values("DistortImageMethod", ["BarrelDistortion", # 6.4.2-5 "BarrelInverseDistortion", # 6.4.3-8 "BilinearForwardDistortion", # 6.5.1-2 "BilinearReverseDistortion", # 6.5.1-2 "DePolarDistortion", # 6.4.2-6 "PolarDistortion", # 6.4.2-6 "PolynomialDistortion", # 6.4.2-4 "ShepardsDistortion"], headers) # 6.4.2-4 have_enum_value("DitherMethod", "NoDitherMethod", headers) # 6.4.3 have_enum_values("FilterTypes", ["KaiserFilter", # 6.3.6 "WelshFilter", # 6.3.6-4 "ParzenFilter", # 6.3.6-4 "LagrangeFilter", # 6.3.7-2 "BohmanFilter", # 6.3.7-2 "BartlettFilter", # 6.3.7-2 "SentinelFilter"], headers) # 6.3.7-2 have_enum_values("MagickEvaluateOperator", ["PowEvaluateOperator", # 6.4.1-9 "LogEvaluateOperator", # 6.4.2 "ThresholdEvaluateOperator", # 6.4.3 "ThresholdBlackEvaluateOperator", # 6.4.3 "ThresholdWhiteEvaluateOperator", # 6.4.3 "GaussianNoiseEvaluateOperator", # 6.4.3 "ImpulseNoiseEvaluateOperator", # 6.4.3 "LaplacianNoiseEvaluateOperator", # 6.4.3 "MultiplicativeNoiseEvaluateOperator", # 6.4.3 "PoissonNoiseEvaluateOperator", # 6.4.3 "UniformNoiseEvaluateOperator", # 6.4.3 "CosineEvaluateOperator", # 6.4.8-5 "SineEvaluateOperator", # 6.4.8-5 "AddModulusEvaluateOperator"], # 6.4.8-5 headers) have_enum_values("MagickFunction", ["ArcsinFunction", # 6.5.2-8 "ArctanFunction", # 6.5.2-8 "PolynomialFunction", # 6.4.8-8 "SinusoidFunction"], headers) # 6.4.8-8 have_enum_values("ImageLayerMethod", ["FlattenLayer", # 6.3.6-2 "MergeLayer", # 6.3.6 "MosaicLayer", # 6.3.6-2 "TrimBoundsLayer" ], headers) # 6.4.3-8 have_enum_values("VirtualPixelMethod", ["HorizontalTileVirtualPixelMethod", # 6.4.2-6 "VerticalTileVirtualPixelMethod", # 6.4.2-6 "HorizontalTileEdgeVirtualPixelMethod", # 6.5.0-1 "VerticalTileEdgeVirtualPixelMethod", # 6.5.0-1 "CheckerTileVirtualPixelMethod"], # 6.5.0-1 headers) # Now test Ruby 1.9.0 features. headers = ["ruby.h"] if have_header("ruby/io.h") headers << "ruby/io.h" else headers << "rubyio.h" end have_func("rb_frame_this_func", headers) # Miscellaneous constants $defs.push("-DRUBY_VERSION_STRING=\"ruby #{RUBY_VERSION}\"") $defs.push("-DRMAGICK_VERSION_STRING=\"RMagick #{RMAGICK_VERS}\"") create_header() # Prior to 1.8.5 mkmf duplicated the symbols on the command line and in the # extconf.h header. Suppress that behavior by removing the symbol array. $defs = [] # Force re-compilation if the generated Makefile changed. $config_h = "Makefile rmagick.h" create_makefile("RMagick2") SUMMARY = <<"END_SUMMARY" #{"=" * 70} #{DateTime.now.strftime("%a %d%b%y %T")} This installation of RMagick #{RMAGICK_VERS} is configured for Ruby #{RUBY_VERSION} (#{RUBY_PLATFORM}) and ImageMagick #{$magick_version} #{"=" * 70} END_SUMMARY Logging::message SUMMARY message SUMMARY Allow MagickCore6 from Magick-config require "mkmf" require "date" RMAGICK_VERS = "0.0.0" MIN_RUBY_VERS = "1.8.5" MIN_RUBY_VERS_NO = MIN_RUBY_VERS.tr(".","").to_i MIN_IM_VERS = "6.4.9" MIN_IM_VERS_NO = MIN_IM_VERS.tr(".","").to_i # Test for a specific value in an enum type def have_enum_value(enum, value, headers=nil, &b) checking_for "#{enum}.#{value}" do if try_compile(<<"SRC", &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ int main() { #{enum} t = #{value}; t = t; return 0; } SRC $defs.push(format("-DHAVE_ENUM_%s", value.upcase)) true else false end end end # Test for multiple values of the same enum type def have_enum_values(enum, values, headers=nil, &b) values.each do |value| have_enum_value(enum, value, headers, &b) end end def exit_failure(msg) Logging::message msg message msg+"\n" exit(1) end # Seems like lots of people have multiple versions of ImageMagick installed. def check_multiple_imagemagick_versions() versions = [] path = ENV['PATH'].split(File::PATH_SEPARATOR) path.each do |dir| file = File.join(dir, "Magick-config") if File.executable? file vers = `#{file} --version`.chomp.strip prefix = `#{file} --prefix`.chomp.strip versions << [vers, prefix, dir] end end versions.uniq! if versions.size > 1 msg = "\nWarning: Found more than one ImageMagick installation. This could cause problems at runtime.\n" versions.each do |vers, prefix, dir| msg << " #{dir}/Magick-config reports version #{vers} is installed in #{prefix}\n" end msg << "Using #{versions[0][0]} from #{versions[0][1]}.\n\n" Logging::message msg message msg end end # Ubuntu (maybe other systems) comes with a partial installation of # ImageMagick in the prefix /usr (some libraries, no includes, and no # binaries). This causes problems when /usr/lib is in the path (e.g., using # the default Ruby installation). def check_partial_imagemagick_versions() prefix = config_string("prefix") matches = [ prefix+"/lib/lib?agick*", prefix+"/include/ImageMagick", prefix+"/bin/Magick-config", ].map do |file_glob| Dir.glob(file_glob) end matches.delete_if { |arr| arr.empty? } if 0 < matches.length and matches.length < 3 msg = "\nWarning: Found a partial ImageMagick installation. Your operating system likely has some built-in ImageMagick libraries but not all of ImageMagick. This will most likely cause problems at both compile and runtime.\nFound partial installation at: "+prefix+"\n" Logging::message msg message msg end end if RUBY_PLATFORM =~ /mswin/ abort <<END_MSWIN +----------------------------------------------------------------------------+ | This rmagick gem is for use only on Linux, BSD, OS X, and similar systems | | that have a gnu or similar toolchain installed. The rmagick-win32 gem is a | | pre-compiled version of RMagick bundled with ImageMagick for use on | | Microsoft Windows systems. The rmagick-win32 gem is available on RubyForge.| | See http://rmagick.rubyforge.org/install-faq.html for more information. | +----------------------------------------------------------------------------+ END_MSWIN end unless checking_for("Ruby version >= #{MIN_RUBY_VERS}") do version = RUBY_VERSION.tr(".","").to_i version >= MIN_RUBY_VERS_NO end exit_failure "Can't install RMagick #{RMAGICK_VERS}. Ruby #{MIN_RUBY_VERS} or later required.\n" end # Magick-config is not available on Windows if RUBY_PLATFORM !~ /mswin|mingw/ # Check for compiler. Extract first word so ENV['CC'] can be a program name with arguments. config = defined?(RbConfig) ? ::RbConfig : ::Config cc = (ENV["CC"] or config::CONFIG["CC"] or "gcc").split(' ').first unless find_executable(cc) exit_failure "No C compiler found in ${ENV['PATH']}. See mkmf.log for details." end # Check for Magick-config unless find_executable("Magick-config") exit_failure "Can't install RMagick #{RMAGICK_VERS}. Can't find Magick-config in #{ENV['PATH']}\n" end check_multiple_imagemagick_versions() check_partial_imagemagick_versions() # Ensure minimum ImageMagick version unless checking_for("ImageMagick version >= #{MIN_IM_VERS}") do version = `Magick-config --version`.chomp.tr(".","").to_i version >= MIN_IM_VERS_NO end exit_failure "Can't install RMagick #{RMAGICK_VERS}. You must have ImageMagick #{MIN_IM_VERS} or later.\n" end $magick_version = `Magick-config --version`.chomp # Save flags $CFLAGS = ENV["CFLAGS"].to_s + " " + `Magick-config --cflags`.chomp $CPPFLAGS = ENV["CPPFLAGS"].to_s + " " + `Magick-config --cppflags`.chomp $LDFLAGS = ENV["LDFLAGS"].to_s + " " + `Magick-config --ldflags`.chomp $LOCAL_LIBS = ENV["LIBS"].to_s + " " + `Magick-config --libs`.chomp elsif RUBY_PLATFORM =~ /mingw/ # mingw `convert -version` =~ /Version: ImageMagick (\d+\.\d+\.\d+)-\d+ / abort "Unable to get ImageMagick version" unless $1 $magick_version = $1 if RUBY_PLATFORM =~ /x64/ $LOCAL_LIBS = '-lCORE_RL_magick_' else $LOCAL_LIBS = '-lCORE_RL_magick_ -lX11' end else # mswin `convert -version` =~ /Version: ImageMagick (\d+\.\d+\.\d+)-\d+ / abort "Unable to get ImageMagick version" unless $1 $magick_version = $1 $CFLAGS = "-W3" $CPPFLAGS = %Q{-I"C:\\Program Files\\Microsoft Platform SDK for Windows Server 2003 R2\\Include" -I"C:\\Program Files\\ImageMagick-#{$magick_version}-Q8\\include"} # The /link option is required by the Makefile but causes warnings in the mkmf.log file. $LDFLAGS = %Q{/link /LIBPATH:"C:\\Program Files\\Microsoft Platform SDK for Windows Server 2003 R2\\Lib" /LIBPATH:"C:\\Program Files\\ImageMagick-#{$magick_version}-Q8\\lib" /LIBPATH:"C:\\ruby\\lib"} $LOCAL_LIBS = 'CORE_RL_magick_.lib X11.lib' end #headers = %w{assert.h ctype.h errno.h float.h limits.h math.h stdarg.h stddef.h stdint.h stdio.h stdlib.h string.h time.h} headers = %w{assert.h ctype.h stdio.h stdlib.h math.h time.h} headers << "stdint.h" if have_header("stdint.h") # defines uint64_t headers << "sys/types.h" if have_header("sys/types.h") if have_header("wand/MagickWand.h") headers << "wand/MagickWand.h" else exit_failure "\nCan't install RMagick #{RMAGICK_VERS}. Can't find MagickWand.h." end if RUBY_PLATFORM !~ /mswin|mingw/ unless `Magick-config --libs`[/\bl\s*(MagickCore|Magick)6?\b/] exit_failure "Can't install RMagick #{RMAGICK_VERS}. " + "Can't find the ImageMagick library or one of the dependent libraries. " + "Check the mkmf.log file for more detailed information.\n" end end have_func("snprintf", headers) ["AcquireImage", # 6.4.1 "AffinityImage", # 6.4.3-6 "AffinityImages", # 6.4.3-6 "AutoGammaImageChannel", # 6.5.5-1 "AutoLevelImageChannel", # 6.5.5-1 "BlueShiftImage", # 6.5.4-3 "ColorMatrixImage", # 6.6.1-0 "ConstituteComponentTerminus", # 6.5.7-9 "DeskewImage", # 6.4.2-5 "DestroyConstitute", # 6.5.7-9(deprecated) "EncipherImage", # 6.3.8-6 "EqualizeImageChannel", # 6.3.6-9 "EvaluateImages", # 6.8.6-4 "FloodfillPaintImage", # 6.3.7 "FunctionImageChannel", # 6.4.8-8 "GetAuthenticIndexQueue", # 6.4.5-6 "GetAuthenticPixels", # 6.4.5-6 "GetImageAlphaChannel", # 6.3.9-2 "GetVirtualPixels", # 6.4.5-6 "LevelImageColors", # 6.4.2 "LevelColorsImageChannel", # 6.5.6-4 "LevelizeImageChannel", # 6.4.2 "LiquidRescaleImage", # 6.3.8-2 "MagickLibAddendum", # 6.5.9-1 "OpaquePaintImageChannel", # 6.3.7-10 "QueueAuthenticPixels", # 6.4.5-6 "RemapImage", # 6.4.4-0 "RemapImages", # 6.4.4-0 "RemoveImageArtifact", # 6.3.6 "RotationalBlurImage", # 6.8.8-9 "RotationalBlurImageChannel", # 6.8.8-9 "SelectiveBlurImageChannel", # 6.5.0-3 "SetImageAlphaChannel", # 6.3.6-9 "SetImageArtifact", # 6.3.6 "SetMagickMemoryMethods", # 6.4.1 "SparseColorImage", # 6.3.6-? "StatisticImage", # 6.6.8-6 "SyncAuthenticPixels", # 6.4.5-6 "TransformImageColorspace", # 6.5.1 "TransparentPaintImage", # 6.3.7-10 "TransparentPaintImageChroma" # 6.4.5-6 ].each do |func| have_func(func, headers) end checking_for("QueryMagickColorname() new signature") do if try_compile(<<"SRC") #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ int main() { MagickBooleanType okay; Image *image; MagickPixelPacket *color; char *name; ExceptionInfo *exception; okay = QueryMagickColorname(image, color, SVGCompliance, name, exception); return 0; } SRC $defs.push("-DHAVE_NEW_QUERYMAGICKCOLORNAME") true else false end end have_struct_member("Image", "type", headers) # ??? have_struct_member("DrawInfo", "kerning", headers) # 6.4.7-8 have_struct_member("DrawInfo", "interline_spacing", headers) # 6.5.5-8 have_struct_member("DrawInfo", "interword_spacing", headers) # 6.4.8-0 have_type("DitherMethod", headers) # 6.4.2 have_type("MagickFunction", headers) # 6.4.8-8 have_type("ImageLayerMethod", headers) # 6.3.6 replaces MagickLayerMethod have_type("long double", headers) #have_type("unsigned long long", headers) #have_type("uint64_t", headers) #have_type("__int64", headers) #have_type("uintmax_t", headers) #check_sizeof("unsigned long", headers) #check_sizeof("Image *", headers) have_enum_values("AlphaChannelType", ["CopyAlphaChannel", # 6.4.3-7 "BackgroundAlphaChannel"], headers) # 6.5.2-5 have_enum_values("CompositeOperator", ["BlurCompositeOp", # 6.5.3-7 "DistortCompositeOp", # 6.5.3-10 "LinearBurnCompositeOp", # 6.5.4-3 "LinearDodgeCompositeOp", # 6.5.4-3 "MathematicsCompositeOp", # 6.5.4-3 "PegtopLightCompositeOp", # 6.5.4-3 "PinLightCompositeOp", # 6.5.4-3 "VividLightCompositeOp"], headers) # 6.5.4-3 have_enum_values("CompressionType", ["DXT1Compression", # 6.3.9-3 "DXT3Compression", # 6.3.9-3 "DXT5Compression", # 6.3.9-3 "ZipSCompression", # 6.5.5-4 "PizCompression", # 6.5.5-4 "Pxr24Compression", # 6.5.5-4 "B44Compression", # 6.5.5-4 "B44ACompression"], headers) # 6.5.5-4 have_enum_values("DistortImageMethod", ["BarrelDistortion", # 6.4.2-5 "BarrelInverseDistortion", # 6.4.3-8 "BilinearForwardDistortion", # 6.5.1-2 "BilinearReverseDistortion", # 6.5.1-2 "DePolarDistortion", # 6.4.2-6 "PolarDistortion", # 6.4.2-6 "PolynomialDistortion", # 6.4.2-4 "ShepardsDistortion"], headers) # 6.4.2-4 have_enum_value("DitherMethod", "NoDitherMethod", headers) # 6.4.3 have_enum_values("FilterTypes", ["KaiserFilter", # 6.3.6 "WelshFilter", # 6.3.6-4 "ParzenFilter", # 6.3.6-4 "LagrangeFilter", # 6.3.7-2 "BohmanFilter", # 6.3.7-2 "BartlettFilter", # 6.3.7-2 "SentinelFilter"], headers) # 6.3.7-2 have_enum_values("MagickEvaluateOperator", ["PowEvaluateOperator", # 6.4.1-9 "LogEvaluateOperator", # 6.4.2 "ThresholdEvaluateOperator", # 6.4.3 "ThresholdBlackEvaluateOperator", # 6.4.3 "ThresholdWhiteEvaluateOperator", # 6.4.3 "GaussianNoiseEvaluateOperator", # 6.4.3 "ImpulseNoiseEvaluateOperator", # 6.4.3 "LaplacianNoiseEvaluateOperator", # 6.4.3 "MultiplicativeNoiseEvaluateOperator", # 6.4.3 "PoissonNoiseEvaluateOperator", # 6.4.3 "UniformNoiseEvaluateOperator", # 6.4.3 "CosineEvaluateOperator", # 6.4.8-5 "SineEvaluateOperator", # 6.4.8-5 "AddModulusEvaluateOperator"], # 6.4.8-5 headers) have_enum_values("MagickFunction", ["ArcsinFunction", # 6.5.2-8 "ArctanFunction", # 6.5.2-8 "PolynomialFunction", # 6.4.8-8 "SinusoidFunction"], headers) # 6.4.8-8 have_enum_values("ImageLayerMethod", ["FlattenLayer", # 6.3.6-2 "MergeLayer", # 6.3.6 "MosaicLayer", # 6.3.6-2 "TrimBoundsLayer" ], headers) # 6.4.3-8 have_enum_values("VirtualPixelMethod", ["HorizontalTileVirtualPixelMethod", # 6.4.2-6 "VerticalTileVirtualPixelMethod", # 6.4.2-6 "HorizontalTileEdgeVirtualPixelMethod", # 6.5.0-1 "VerticalTileEdgeVirtualPixelMethod", # 6.5.0-1 "CheckerTileVirtualPixelMethod"], # 6.5.0-1 headers) # Now test Ruby 1.9.0 features. headers = ["ruby.h"] if have_header("ruby/io.h") headers << "ruby/io.h" else headers << "rubyio.h" end have_func("rb_frame_this_func", headers) # Miscellaneous constants $defs.push("-DRUBY_VERSION_STRING=\"ruby #{RUBY_VERSION}\"") $defs.push("-DRMAGICK_VERSION_STRING=\"RMagick #{RMAGICK_VERS}\"") create_header() # Prior to 1.8.5 mkmf duplicated the symbols on the command line and in the # extconf.h header. Suppress that behavior by removing the symbol array. $defs = [] # Force re-compilation if the generated Makefile changed. $config_h = "Makefile rmagick.h" create_makefile("RMagick2") SUMMARY = <<"END_SUMMARY" #{"=" * 70} #{DateTime.now.strftime("%a %d%b%y %T")} This installation of RMagick #{RMAGICK_VERS} is configured for Ruby #{RUBY_VERSION} (#{RUBY_PLATFORM}) and ImageMagick #{$magick_version} #{"=" * 70} END_SUMMARY Logging::message SUMMARY message SUMMARY
require 'mkmf' require 'fileutils' def using_system_libraries? arg_config('--use-system-libraries', !!ENV['JSONNET_USE_SYSTEM_LIBRARIES']) end dir_config('jsonnet') unless using_system_libraries? message "Building jsonnet using packaged libraries.\n" require 'rubygems' require 'mini_portile2' message "Using mini_portile version #{MiniPortile::VERSION}\n" recipe = MiniPortile.new('jsonnet', 'v0.16.0') recipe.files = ['https://github.com/google/jsonnet/archive/v0.16.0.tar.gz'] class << recipe def compile # We want to create a file a library we can link to. Jsonnet provides us # with the command `make libjsonnet.so` which creates a shared object # however that won't be bundled into the compiled output so instead # we compile the c into .o files and then create an archive that can # be linked to execute('compile', make_cmd) execute('archive', 'ar rcs libjsonnet.a core/desugarer.o core/formatter.o core/lexer.o core/libjsonnet.o core/parser.o core/pass.o core/static_analysis.o core/string_utils.o core/vm.o third_party/md5/md5.o') end def configured? true end def install lib_path = File.join(port_path, 'lib') include_path = File.join(port_path, 'include') FileUtils.mkdir_p([lib_path, include_path]) FileUtils.cp(File.join(work_path, 'libjsonnet.a'), lib_path) FileUtils.cp(File.join(work_path, 'include', 'libjsonnet.h'), include_path) FileUtils.cp(File.join(work_path, 'include', 'libjsonnet_fmt.h'), include_path) end end recipe.cook # I tried using recipe.activate here but that caused this file to build ok # but the makefile to fail. These commands add the necessary paths to do both $LIBPATH = ["#{recipe.path}/lib"] | $LIBPATH $CPPFLAGS << " -I#{recipe.path}/include" # This resolves an issue where you can get improper linkage when compiling # and get an error like "undefined symbol: _ZTVN10__cxxabiv121__vmi_class_type_infoE" # experienced on ubuntu. # See: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=193950 $LIBS << " -lstdc++" end abort 'libjsonnet.h not found' unless have_header('libjsonnet.h') abort 'libjsonnet not found' unless have_library('jsonnet') have_header('libjsonnet_fmt.h') create_makefile('jsonnet/jsonnet_wrap') Update the default jsonnet version require 'mkmf' require 'fileutils' def using_system_libraries? arg_config('--use-system-libraries', !!ENV['JSONNET_USE_SYSTEM_LIBRARIES']) end dir_config('jsonnet') unless using_system_libraries? message "Building jsonnet using packaged libraries.\n" require 'rubygems' require 'mini_portile2' message "Using mini_portile version #{MiniPortile::VERSION}\n" recipe = MiniPortile.new('jsonnet', 'v0.17.0') recipe.files = ['https://github.com/google/jsonnet/archive/v0.17.0.tar.gz'] class << recipe def compile # We want to create a file a library we can link to. Jsonnet provides us # with the command `make libjsonnet.so` which creates a shared object # however that won't be bundled into the compiled output so instead # we compile the c into .o files and then create an archive that can # be linked to execute('compile', make_cmd) execute('archive', 'ar rcs libjsonnet.a core/desugarer.o core/formatter.o core/lexer.o core/libjsonnet.o core/parser.o core/pass.o core/static_analysis.o core/string_utils.o core/vm.o third_party/md5/md5.o') end def configured? true end def install lib_path = File.join(port_path, 'lib') include_path = File.join(port_path, 'include') FileUtils.mkdir_p([lib_path, include_path]) FileUtils.cp(File.join(work_path, 'libjsonnet.a'), lib_path) FileUtils.cp(File.join(work_path, 'include', 'libjsonnet.h'), include_path) FileUtils.cp(File.join(work_path, 'include', 'libjsonnet_fmt.h'), include_path) end end recipe.cook # I tried using recipe.activate here but that caused this file to build ok # but the makefile to fail. These commands add the necessary paths to do both $LIBPATH = ["#{recipe.path}/lib"] | $LIBPATH $CPPFLAGS << " -I#{recipe.path}/include" # This resolves an issue where you can get improper linkage when compiling # and get an error like "undefined symbol: _ZTVN10__cxxabiv121__vmi_class_type_infoE" # experienced on ubuntu. # See: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=193950 $LIBS << " -lstdc++" end abort 'libjsonnet.h not found' unless have_header('libjsonnet.h') abort 'libjsonnet not found' unless have_library('jsonnet') have_header('libjsonnet_fmt.h') create_makefile('jsonnet/jsonnet_wrap')
require 'mkmf' require 'fileutils' Dir.chdir "../../leveldb" system "make" or abort Dir.chdir "../ext/leveldb" $CFLAGS << " -I../../leveldb/include" $LIBS << " -L../../leveldb -Wl,--whole-archive -lleveldb -Wl,--no-whole-archive" create_makefile "leveldb/leveldb" only make liblevedb.a from included leveldb distribution require 'mkmf' require 'fileutils' Dir.chdir "../../leveldb" system "make libleveldb.a" or abort Dir.chdir "../ext/leveldb" $CFLAGS << " -I../../leveldb/include" $LIBS << " -L../../leveldb -Wl,--whole-archive -lleveldb -Wl,--no-whole-archive" create_makefile "leveldb/leveldb"
require 'fileutils' require_relative '../providers' require_relative '../utils/graph' require_relative '../logging' module Citac module Agent class Analyzer def initialize(repository, env_manager) @repository = repository @env_manager = env_manager end def run(spec, operating_system, options = {}) raise "Operating system '#{operating_system}' not specific" unless operating_system.specific? log_info 'agent', "Running configuration specification '#{spec}' on operating system '#{operating_system}'..." provider = Citac::Providers.get spec.type script_name = "script#{provider.script_extension}" script_contents = @repository.script spec, operating_system Dir.mktmpdir do |dir| log_debug 'agent', "Using temporary directory '#{dir}'..." run_script_path = File.join(dir, 'run.sh') log_debug 'agent', "Writing run script '#{run_script_path}'..." File.open run_script_path, 'w', :encoding => 'UTF-8' do |f| f.puts '#!/bin/sh' f.puts 'cd /tmp/citac' provider.prepare_for_dependency_graph_generation @repository, spec, dir, f end run_script_contents = IO.read run_script_path, :encoding => 'UTF-8' log_debug 'agent', "Run script:\n--EOF--\n#{run_script_contents}\n--EOF--" script_path = File.join(dir, script_name) IO.write script_path, script_contents, :encoding => 'UTF-8' log_debug 'agent', "Analyzation script '#{script_path}':\n--EOF--\n#{script_contents}\n--EOF--" env = @env_manager.find :operating_system => operating_system, :spec_runner => spec.type log_info 'agent', "Running analyzation in environment '#{env}'..." result = @env_manager.run env, run_script_path log_debug 'agent', "Run script output:\n--EOF--\n#{result.output}\n--EOF--" dependencies_graphml = IO.read File.join(dir, 'dependencies.graphml'), :encoding => 'UTF-8' dependencies = Citac::Utils::Graphs::Graph.from_graphml dependencies_graphml log_info 'agent', "Saving generated dependency graph for '#{spec}' to repository..." @repository.save_dependency_graph spec, operating_system, dependencies end end end end end Implemented that by default already generated graphs are not regenerated. require 'fileutils' require_relative '../providers' require_relative '../utils/graph' require_relative '../logging' module Citac module Agent class Analyzer def initialize(repository, env_manager) @repository = repository @env_manager = env_manager end def run(spec, operating_system, options = {}) raise "Operating system '#{operating_system}' not specific" unless operating_system.specific? return if @repository.has_dependency_graph?(spec, operating_system) && !options[:force] log_info 'agent', "Running configuration specification '#{spec}' on operating system '#{operating_system}'..." provider = Citac::Providers.get spec.type script_name = "script#{provider.script_extension}" script_contents = @repository.script spec, operating_system Dir.mktmpdir do |dir| log_debug 'agent', "Using temporary directory '#{dir}'..." run_script_path = File.join(dir, 'run.sh') log_debug 'agent', "Writing run script '#{run_script_path}'..." File.open run_script_path, 'w', :encoding => 'UTF-8' do |f| f.puts '#!/bin/sh' f.puts 'cd /tmp/citac' provider.prepare_for_dependency_graph_generation @repository, spec, dir, f end run_script_contents = IO.read run_script_path, :encoding => 'UTF-8' log_debug 'agent', "Run script:\n--EOF--\n#{run_script_contents}\n--EOF--" script_path = File.join(dir, script_name) IO.write script_path, script_contents, :encoding => 'UTF-8' log_debug 'agent', "Analyzation script '#{script_path}':\n--EOF--\n#{script_contents}\n--EOF--" env = @env_manager.find :operating_system => operating_system, :spec_runner => spec.type log_info 'agent', "Running analyzation in environment '#{env}'..." result = @env_manager.run env, run_script_path log_debug 'agent', "Run script output:\n--EOF--\n#{result.output}\n--EOF--" dependencies_graphml = IO.read File.join(dir, 'dependencies.graphml'), :encoding => 'UTF-8' dependencies = Citac::Utils::Graphs::Graph.from_graphml dependencies_graphml log_info 'agent', "Saving generated dependency graph for '#{spec}' to repository..." @repository.save_dependency_graph spec, operating_system, dependencies end end end end end
require_relative "../app/%s" % [File.basename(__FILE__, "_spec.rb")] path = __FILE__.sub(/\.rb$/, ".json") $DATA = JSON.parse(File.read(path)) describe AdvertisingAgency do after(:each) do results = AdvertisingAgency.numberOfRejections(@requests) expect(results).to eq(@expected) end $DATA.each_with_index do |t, i| it "test #{i}" do @requests = t[0] @expected = t[1] end end end added AustrianLotto problem and generalized specs name = File.basename(__FILE__, "_spec.rb") require_relative "../app/%s" % [name] path = __FILE__.sub(/\.rb$/, ".json") $DATA = JSON.parse(File.read(path)) describe name do after(:each) do results = Object.const_get(name).numberOfRejections(@requests) expect(results).to eq(@expected) end $DATA.each_with_index do |t, i| it "test #{i}" do @requests = t[0] @expected = t[1] end end end
FactlinkUI::Application.routes.draw do # The priority is based upon order of creation: # first created -> highest priority. # User Authentication devise_for :users, :controllers => { confirmations: "users/confirmations", invitations: "users/invitations", registrations: "users/registrations", sessions: "users/sessions", passwords: "users/passwords" } # Web Front-end root :to => "home#index" # Javascript Client calls # TODO: replace /site/ gets with scoped '/sites/', and make it a resource (even if it only has show) get "/site/blacklisted" => "sites#blacklisted" get "/site/count" => "sites#facts_count_for_url" get "/site" => "sites#facts_for_url" # Prepare a new Fact # If you change this route, don't forget to change it in application.rb # as well (frame busting) match "/factlink/intermediate" => "facts#intermediate" # Static js micro templates get "/templates/:name" => "js_lib#show_template", constraints: { name: /[-a-zA-Z_]+/ } get "/jslib/:path" => "js_lib#redir", constraints: { path: /[-a-zA-Z0-9_.\/]*/ } # Generate the images for the indicator used in the js-lib get "/system/wheel/:percentages" => "wheel#show" # Show Facts#new as unauthenticated user to show the correct login link resources :facts, only: [:new, :update, :create] do member do post "/opinion/:type" => "facts#set_opinion", :as => "set_opinion" delete "/opinion" => "facts#remove_opinions", :as => "delete_opinion" end namespace :comments do # create post "/:opinion" => 'comments#create' # destroy delete "/:opinion/:id" => 'comments#destroy' # index get "/:opinion" => 'comments#index' end end resources :feedback get "/:fact_slug/f/:id" => "facts#extended_show", as: "frurl_fact" authenticated :user do resources :facts, :except => [:edit, :index, :update] do resources :evidence resources :supporting_evidence, :weakening_evidence do member do get "opinion" => "evidence#opinion" post "opinion/:type" => "evidence#set_opinion", :as => "set_opinion" delete "opinion/" => "evidence#remove_opinions", :as => "delete_opinion" end end member do post "/opinion/:type" => "facts#set_opinion", :as => "set_opinion" delete "/opinion" => "facts#remove_opinions", :as => "delete_opinion" match "/evidence_search" => "facts#evidence_search" get "/channels" => "facts#get_channel_listing" get "/believers" => "facts#believers" get "/disbelievers" => "facts#disbelievers" get "/doubters" => "facts#doubters" end end # Search and infinite scrolling match "/search(/page/:page)(/:sort/:direction)" => "search#search", :as => "factlink_overview" namespace :admin, path: 'a' do resources :users, :only => [:show, :new, :create, :edit, :update, :index] do collection do get :reserved end member do put :approve end end end # Seems to me we want to lose the scope "/:username" later and place all # stuff in this resource? devise_scope :user do resources :users, path: "", only: [ :edit, :update ] do get "/password/edit" => "users/registrations#edit_password" put "/password" => "users/registrations#update_password", as: "update_password" end end end get "/auth/:service/callback" => "identities#service_callback", as: "social_auth" delete "/auth/:service/deauthorize" => "identities#service_deauthorize" resources :conversations, only: [:index, :show, :create], path: 'c' do resources :messages, only: [:create, :show] end scope "/:username" do get "/" => "users#show", :as => "user_profile" put "/" => "users#update" get 'notification-settings' => "channels#backbone_page", as: "user_notification_settings" scope "/activities" do get "/" => "users#activities", :as => "activities" post "/mark_as_read" => "users#mark_activities_as_read", :as => "mark_activities_as_read" end resources :channels do collection do post "toggle/fact" => "channels#toggle_fact", :as => "toggle_fact" get "find" => "channels#search", :as => "find" end get "/facts/:fact_id" => "facts#extended_show", as: "fact" resources :subchannels, only: [:index, :destroy, :create, :update] do collection do post "add/:id/", :as => "add", :action => "create" post "remove/:id/", :as => "remove", :action => "destroy" end end resources :activities, only: [:index, :create, :update, :destroy], controller: 'channel_activities' do |variable| collection do get "last_fact" get "facts/:fact_id" => "facts#extended_show", as: "fact" end end member do post "toggle/fact/:fact_id/" => "channels#toggle_fact" post "add/:fact_id" => "channels#add_fact" post "remove/:fact_id" => "channels#remove_fact" scope "/facts" do get "/" => "channels#facts", :as => "get_facts_for" post "/" => "channels#create_fact", :as => "create_fact_for" scope "/:fact_id" do delete "/" => "channels#remove_fact", :as => "remove_fact_from" match "/evidence_search" => "facts#evidence_search" resource :supporting_evidence, :weakening_evidence do scope '/:evidence_id' do post "/opinion/:type", action: :set_opinion, :as => "set_opinion" delete "/opinion/", action: :remove_opinions, :as => "delete_opinion" end end end end end end end resources :topics, path: 't', only: [] do collection do get :top get :top_channels end member do get :related_user_channels end end get "/p/tos" => "tos#show", as: "tos" post "/p/tos" => "tos#update", as: "tos" scope "/p/tour" do get "youre-almost-done" => "tour#almost_done", as: "almost_done" get "create-your-first-factlink" => "tour#create_your_first_factlink", as: "create_your_first_factlink" get "choose-channels" => "tour#choose_channels", as: "choose_channels" end get "/p/privacy" => "privacy#privacy", as: "privacy" scope "/p" do get ":name" => "home#pages", :as => "pages", :constraints => {:name => /([-a-zA-Z_\/]+)/} end # Scope for user specific actions # I made this scope so we don't always have to know the current users username in de frontend # I'm abusing it for the search now as well, as this place looks like the best # since we cannot nest it in another user scope "/u" do put "/seen_messages" => "users#seen_message", as: 'see_message' get "/search" => "users#search", as: 'search_users' end end Fixed comments routes FactlinkUI::Application.routes.draw do # The priority is based upon order of creation: # first created -> highest priority. # User Authentication devise_for :users, :controllers => { confirmations: "users/confirmations", invitations: "users/invitations", registrations: "users/registrations", sessions: "users/sessions", passwords: "users/passwords" } # Web Front-end root :to => "home#index" # Javascript Client calls # TODO: replace /site/ gets with scoped '/sites/', and make it a resource (even if it only has show) get "/site/blacklisted" => "sites#blacklisted" get "/site/count" => "sites#facts_count_for_url" get "/site" => "sites#facts_for_url" # Prepare a new Fact # If you change this route, don't forget to change it in application.rb # as well (frame busting) match "/factlink/intermediate" => "facts#intermediate" # Static js micro templates get "/templates/:name" => "js_lib#show_template", constraints: { name: /[-a-zA-Z_]+/ } get "/jslib/:path" => "js_lib#redir", constraints: { path: /[-a-zA-Z0-9_.\/]*/ } # Generate the images for the indicator used in the js-lib get "/system/wheel/:percentages" => "wheel#show" # Show Facts#new as unauthenticated user to show the correct login link resources :facts, only: [:new, :update, :create] do member do post "/opinion/:type" => "facts#set_opinion", :as => "set_opinion" delete "/opinion" => "facts#remove_opinions", :as => "delete_opinion" scope '/comments' do # create post "/:opinion" => 'comments#create' # destroy delete "/:opinion/:id" => 'comments#destroy' # index get "/:opinion" => 'comments#index' end end end resources :feedback get "/:fact_slug/f/:id" => "facts#extended_show", as: "frurl_fact" authenticated :user do resources :facts, :except => [:edit, :index, :update] do resources :evidence resources :supporting_evidence, :weakening_evidence do member do get "opinion" => "evidence#opinion" post "opinion/:type" => "evidence#set_opinion", :as => "set_opinion" delete "opinion/" => "evidence#remove_opinions", :as => "delete_opinion" end end member do post "/opinion/:type" => "facts#set_opinion", :as => "set_opinion" delete "/opinion" => "facts#remove_opinions", :as => "delete_opinion" match "/evidence_search" => "facts#evidence_search" get "/channels" => "facts#get_channel_listing" get "/believers" => "facts#believers" get "/disbelievers" => "facts#disbelievers" get "/doubters" => "facts#doubters" end end # Search and infinite scrolling match "/search(/page/:page)(/:sort/:direction)" => "search#search", :as => "factlink_overview" namespace :admin, path: 'a' do resources :users, :only => [:show, :new, :create, :edit, :update, :index] do collection do get :reserved end member do put :approve end end end # Seems to me we want to lose the scope "/:username" later and place all # stuff in this resource? devise_scope :user do resources :users, path: "", only: [ :edit, :update ] do get "/password/edit" => "users/registrations#edit_password" put "/password" => "users/registrations#update_password", as: "update_password" end end end get "/auth/:service/callback" => "identities#service_callback", as: "social_auth" delete "/auth/:service/deauthorize" => "identities#service_deauthorize" resources :conversations, only: [:index, :show, :create], path: 'c' do resources :messages, only: [:create, :show] end scope "/:username" do get "/" => "users#show", :as => "user_profile" put "/" => "users#update" get 'notification-settings' => "channels#backbone_page", as: "user_notification_settings" scope "/activities" do get "/" => "users#activities", :as => "activities" post "/mark_as_read" => "users#mark_activities_as_read", :as => "mark_activities_as_read" end resources :channels do collection do post "toggle/fact" => "channels#toggle_fact", :as => "toggle_fact" get "find" => "channels#search", :as => "find" end get "/facts/:fact_id" => "facts#extended_show", as: "fact" resources :subchannels, only: [:index, :destroy, :create, :update] do collection do post "add/:id/", :as => "add", :action => "create" post "remove/:id/", :as => "remove", :action => "destroy" end end resources :activities, only: [:index, :create, :update, :destroy], controller: 'channel_activities' do |variable| collection do get "last_fact" get "facts/:fact_id" => "facts#extended_show", as: "fact" end end member do post "toggle/fact/:fact_id/" => "channels#toggle_fact" post "add/:fact_id" => "channels#add_fact" post "remove/:fact_id" => "channels#remove_fact" scope "/facts" do get "/" => "channels#facts", :as => "get_facts_for" post "/" => "channels#create_fact", :as => "create_fact_for" scope "/:fact_id" do delete "/" => "channels#remove_fact", :as => "remove_fact_from" match "/evidence_search" => "facts#evidence_search" resource :supporting_evidence, :weakening_evidence do scope '/:evidence_id' do post "/opinion/:type", action: :set_opinion, :as => "set_opinion" delete "/opinion/", action: :remove_opinions, :as => "delete_opinion" end end end end end end end resources :topics, path: 't', only: [] do collection do get :top get :top_channels end member do get :related_user_channels end end get "/p/tos" => "tos#show", as: "tos" post "/p/tos" => "tos#update", as: "tos" scope "/p/tour" do get "youre-almost-done" => "tour#almost_done", as: "almost_done" get "create-your-first-factlink" => "tour#create_your_first_factlink", as: "create_your_first_factlink" get "choose-channels" => "tour#choose_channels", as: "choose_channels" end get "/p/privacy" => "privacy#privacy", as: "privacy" scope "/p" do get ":name" => "home#pages", :as => "pages", :constraints => {:name => /([-a-zA-Z_\/]+)/} end # Scope for user specific actions # I made this scope so we don't always have to know the current users username in de frontend # I'm abusing it for the search now as well, as this place looks like the best # since we cannot nest it in another user scope "/u" do put "/seen_messages" => "users#seen_message", as: 'see_message' get "/search" => "users#search", as: 'search_users' end end
Gem::Specification.new do |s| s.name = "bossman" s.version = "0.1.0" s.date = "2008-08-27" s.summary = "Class for interaction with the Yahoo BOSS web service." s.email = "jpignata@waterfrontmedia.com" s.homepage = "http://github.com/jpignata/bossman-gem" s.authors = ["Jay Pignata"] s.files = ['bossman.gemspec', 'lib/bossman.rb', 'lib/bossman/basevalueobject.rb', 'lib/bossman/rest.rb', 'lib/bossman/result.rb', 'lib/bossman/resultset.rb', 'lib/bossman/search.rb', 'README', 'LICENSE'] s.add_dependency("activesupport", [">= 2.1.0"]) s.has_rdoc = false end incremented version Gem::Specification.new do |s| s.name = "bossman" s.version = "0.1.1" s.date = "2008-08-28" s.summary = "Class for interaction with the Yahoo BOSS web service." s.email = "jpignata@waterfrontmedia.com" s.homepage = "http://github.com/jpignata/bossman-gem" s.authors = ["Jay Pignata"] s.files = ['bossman.gemspec', 'lib/bossman.rb', 'lib/bossman/basevalueobject.rb', 'lib/bossman/rest.rb', 'lib/bossman/result.rb', 'lib/bossman/resultset.rb', 'lib/bossman/search.rb', 'README', 'LICENSE'] s.add_dependency("activesupport", [">= 2.1.0"]) s.has_rdoc = false end
require_relative '../../spec_helper' require_relative 'fixtures/classes' describe "IO#close" do before :each do @name = tmp('io_close.txt') @io = new_io @name end after :each do @io.close unless @io.closed? rm_r @name end it "closes the stream" do @io.close @io.should.closed? end it "returns nil" do @io.close.should == nil end it "raises an IOError reading from a closed IO" do @io.close -> { @io.read }.should raise_error(IOError) end it "raises an IOError writing to a closed IO" do @io.close -> { @io.write "data" }.should raise_error(IOError) end it 'does not close the stream if autoclose is false' do other_io = IO.new(@io.fileno) other_io.autoclose = false other_io.close -> { @io.write "data" }.should_not raise_error(IOError) end it "does nothing if already closed" do @io.close @io.close.should be_nil end it 'raises an IOError with a clear message' do matching_exception = nil -> do IOSpecs::THREAD_CLOSE_RETRIES.times do read_io, write_io = IO.pipe going_to_read = false thread = Thread.new do begin going_to_read = true read_io.read rescue IOError => ioe if ioe.message == IOSpecs::THREAD_CLOSE_ERROR_MESSAGE matching_exception = ioe end # try again end end # best attempt to ensure the thread is actually blocked on read Thread.pass until going_to_read && thread.stop? sleep(0.001) read_io.close thread.join write_io.close matching_exception&.tap {|ex| raise ex} end end.should raise_error(IOError, IOSpecs::THREAD_CLOSE_ERROR_MESSAGE) end end describe "IO#close on an IO.popen stream" do it "clears #pid" do io = IO.popen ruby_cmd('r = loop{puts "y"; 0} rescue 1; exit r'), 'r' io.pid.should_not == 0 io.close -> { io.pid }.should raise_error(IOError) end it "sets $?" do io = IO.popen ruby_cmd('exit 0'), 'r' io.close $?.exitstatus.should == 0 io = IO.popen ruby_cmd('exit 1'), 'r' io.close $?.exitstatus.should == 1 end it "waits for the child to exit" do io = IO.popen ruby_cmd('r = loop{puts "y"; 0} rescue 1; exit r'), 'r' io.close $?.exitstatus.should_not == 0 end end Add a test case for overridden IO#flush method in subclasses require_relative '../../spec_helper' require_relative 'fixtures/classes' describe "IO#close" do before :each do @name = tmp('io_close.txt') @io = new_io @name end after :each do @io.close unless @io.closed? rm_r @name end it "closes the stream" do @io.close @io.should.closed? end it "returns nil" do @io.close.should == nil end it "raises an IOError reading from a closed IO" do @io.close -> { @io.read }.should raise_error(IOError) end it "raises an IOError writing to a closed IO" do @io.close -> { @io.write "data" }.should raise_error(IOError) end it 'does not close the stream if autoclose is false' do other_io = IO.new(@io.fileno) other_io.autoclose = false other_io.close -> { @io.write "data" }.should_not raise_error(IOError) end it "does nothing if already closed" do @io.close @io.close.should be_nil end it "does not call the #flush method but flushes the stream internally" do @io.should_not_receive(:flush) @io.close @io.should.closed? end it 'raises an IOError with a clear message' do matching_exception = nil -> do IOSpecs::THREAD_CLOSE_RETRIES.times do read_io, write_io = IO.pipe going_to_read = false thread = Thread.new do begin going_to_read = true read_io.read rescue IOError => ioe if ioe.message == IOSpecs::THREAD_CLOSE_ERROR_MESSAGE matching_exception = ioe end # try again end end # best attempt to ensure the thread is actually blocked on read Thread.pass until going_to_read && thread.stop? sleep(0.001) read_io.close thread.join write_io.close matching_exception&.tap {|ex| raise ex} end end.should raise_error(IOError, IOSpecs::THREAD_CLOSE_ERROR_MESSAGE) end end describe "IO#close on an IO.popen stream" do it "clears #pid" do io = IO.popen ruby_cmd('r = loop{puts "y"; 0} rescue 1; exit r'), 'r' io.pid.should_not == 0 io.close -> { io.pid }.should raise_error(IOError) end it "sets $?" do io = IO.popen ruby_cmd('exit 0'), 'r' io.close $?.exitstatus.should == 0 io = IO.popen ruby_cmd('exit 1'), 'r' io.close $?.exitstatus.should == 1 end it "waits for the child to exit" do io = IO.popen ruby_cmd('r = loop{puts "y"; 0} rescue 1; exit r'), 'r' io.close $?.exitstatus.should_not == 0 end end
action :configure do base_instance = node['tomcat']['base_instance'] # Set defaults for resource attributes from node attributes. We can't do # this in the resource declaration because node isn't populated yet when # that runs [:catalina_options, :java_options, :use_security_manager, :authbind, :max_threads, :ssl_max_threads, :ssl_cert_file, :ssl_key_file, :ssl_chain_files, :keystore_file, :keystore_type, :truststore_file, :truststore_type, :certificate_dn, :loglevel, :tomcat_auth, :user, :group, :tmp_dir, :lib_dir, :endorsed_dir].each do |attr| if not new_resource.instance_variable_get("@#{attr}") new_resource.instance_variable_set("@#{attr}", node['tomcat'][attr]) end end service_actions = new_resource.instance_variable_get("@service_actions") if not service_actions service_actions = node['tomcat']['service_actions'] end if new_resource.name == 'base' instance = base_instance # If they weren't set explicitly, set these paths to the default [:base, :home, :config_dir, :log_dir, :work_dir, :context_dir, :webapp_dir].each do |attr| if not new_resource.instance_variable_get("@#{attr}") new_resource.instance_variable_set("@#{attr}", node["tomcat"][attr]) end end else # Use a unique name for this instance instance = "#{base_instance}-#{new_resource.name}" # If they weren't set explicitly, set these paths to the default with # the base instance name replaced with our own [:base, :home, :config_dir, :log_dir, :work_dir, :context_dir, :webapp_dir].each do |attr| if not new_resource.instance_variable_get("@#{attr}") and node["tomcat"][attr] new = node["tomcat"][attr].sub(base_instance, instance) new_resource.instance_variable_set("@#{attr}", new) end end # Create the directories, since the OS package wouldn't have [:base, :config_dir, :context_dir].each do |attr| directory new_resource.instance_variable_get("@#{attr}") do mode '0755' recursive true end end [:log_dir, :work_dir, :webapp_dir].each do |attr| directory new_resource.instance_variable_get("@#{attr}") do mode '0755' recursive true user new_resource.user group new_resource.group end end # Don't make a separate home, just link to base if new_resource.home != new_resource.base link "#{new_resource.home}" do to "#{new_resource.base}" end end # config_dir needs symlinks to the files we're not going to create ['catalina.policy', 'catalina.properties', 'context.xml', 'tomcat-users.xml', 'web.xml'].each do |file| link "#{new_resource.config_dir}/#{file}" do to "#{node['tomcat']['config_dir']}/#{file}" end end # The base also needs a bunch of to symlinks inside it ['bin', 'lib'].each do |dir| link "#{new_resource.base}/#{dir}" do to "#{node['tomcat']['base']}/#{dir}" end end {'conf' => 'config_dir', 'logs' => 'log_dir', 'temp' => 'tmp_dir', 'work' => 'work_dir', 'webapps' => 'webapp_dir'}.each do |name, attr| link "#{new_resource.base}/#{name}" do to new_resource.instance_variable_get("@#{attr}") end end # Make a copy of the init script for this instance if node['init_package'] == 'systemd' and not platform_family?('debian') template "/usr/lib/systemd/system/#{instance}.service" do source 'tomcat.service.erb' variables ({ :instance => instance, :user => new_resource.user, :group => new_resource.group }) owner 'root' group 'root' mode '0644' end else execute "/etc/init.d/#{instance}" do command <<-EOH cp /etc/init.d/#{base_instance} /etc/init.d/#{instance} perl -i -pe 's/#{base_instance}/#{instance}/g' /etc/init.d/#{instance} EOH end end end # Even for the base instance, the OS package may not make this directory directory new_resource.endorsed_dir do mode '0755' recursive true end unless new_resource.truststore_file.nil? java_options = new_resource.java_options.to_s java_options << " -Djavax.net.ssl.trustStore=#{new_resource.config_dir}/#{new_resource.truststore_file}" java_options << " -Djavax.net.ssl.trustStorePassword=#{new_resource.truststore_password}" new_resource.java_options = java_options end case node['platform_family'] when 'rhel', 'fedora' template "/etc/sysconfig/#{instance}" do source 'sysconfig_tomcat6.erb' variables ({ :user => new_resource.user, :home => new_resource.home, :base => new_resource.base, :java_options => new_resource.java_options, :use_security_manager => new_resource.use_security_manager, :tmp_dir => new_resource.tmp_dir, :catalina_options => new_resource.catalina_options, :endorsed_dir => new_resource.endorsed_dir }) owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end when 'smartos' # SmartOS doesn't support multiple instances template "#{new_resource.base}/bin/setenv.sh" do source 'setenv.sh.erb' owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end else template "/etc/default/#{instance}" do source 'default_tomcat6.erb' variables ({ :user => new_resource.user, :group => new_resource.group, :home => new_resource.home, :base => new_resource.base, :java_options => new_resource.java_options, :use_security_manager => new_resource.use_security_manager, :tmp_dir => new_resource.tmp_dir, :authbind => new_resource.authbind, :catalina_options => new_resource.catalina_options, :endorsed_dir => new_resource.endorsed_dir }) owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end end template "#{new_resource.config_dir}/server.xml" do source 'server.xml.erb' variables ({ :port => new_resource.port, :proxy_port => new_resource.proxy_port, :ssl_port => new_resource.ssl_port, :ssl_proxy_port => new_resource.ssl_proxy_port, :ajp_port => new_resource.ajp_port, :shutdown_port => new_resource.shutdown_port, :max_threads => new_resource.max_threads, :ssl_max_threads => new_resource.ssl_max_threads, :keystore_file => new_resource.keystore_file, :keystore_type => new_resource.keystore_type, :tomcat_auth => new_resource.tomcat_auth, :config_dir => new_resource.config_dir, }) owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end template "#{new_resource.config_dir}/logging.properties" do source 'logging.properties.erb' owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end if new_resource.ssl_cert_file.nil? execute 'Create Tomcat SSL certificate' do group new_resource.group command <<-EOH #{node['tomcat']['keytool']} \ -genkey \ -keystore "#{new_resource.config_dir}/#{new_resource.keystore_file}" \ -storepass "#{node['tomcat']['keystore_password']}" \ -keypass "#{node['tomcat']['keystore_password']}" \ -dname "#{node['tomcat']['certificate_dn']}" EOH umask 0007 creates "#{new_resource.config_dir}/#{new_resource.keystore_file}" action :run notifies :restart, "service[#{instance}]" end else script "create_keystore-#{instance}" do interpreter 'bash' action :nothing cwd new_resource.config_dir code <<-EOH cat #{new_resource.ssl_chain_files.join(' ')} > cacerts.pem openssl pkcs12 -export \ -inkey #{new_resource.ssl_key_file} \ -in #{new_resource.ssl_cert_file} \ -chain \ -CAfile cacerts.pem \ -password pass:#{node['tomcat']['keystore_password']} \ -out #{new_resource.keystore_file} EOH notifies :restart, "service[tomcat]" end cookbook_file "#{new_resource.config_dir}/#{new_resource.ssl_cert_file}" do mode '0644' notifies :run, "script[create_keystore-#{instance}]" end cookbook_file "#{new_resource.config_dir}/#{new_resource.ssl_key_file}" do mode '0644' notifies :run, "script[create_keystore-#{instance}]" end new_resource.ssl_chain_files.each do |cert| cookbook_file "#{new_resource.config_dir}/#{cert}" do mode '0644' notifies :run, "script[create_keystore-#{instance}]" end end end unless new_resource.truststore_file.nil? cookbook_file "#{new_resource.config_dir}/#{new_resource.truststore_file}" do mode '0644' end end service "#{instance}" do case node['platform_family'] when 'rhel', 'fedora' service_name "#{instance}" supports :restart => true, :status => true when 'debian' service_name "#{instance}" supports :restart => true, :reload => false, :status => true when 'smartos' # SmartOS doesn't support multiple instances service_name 'tomcat' supports :restart => false, :reload => false, :status => true else service_name "#{instance}" end action service_actions notifies :run, "execute[wait for #{instance}]", :immediately retries 4 retry_delay 30 end execute "wait for #{instance}" do command 'sleep 5' action :nothing end end Update instance.rb server.xml.erb template cookbook and source are now customisable action :configure do base_instance = node['tomcat']['base_instance'] # Set defaults for resource attributes from node attributes. We can't do # this in the resource declaration because node isn't populated yet when # that runs [:catalina_options, :java_options, :use_security_manager, :authbind, :max_threads, :ssl_max_threads, :ssl_cert_file, :ssl_key_file, :ssl_chain_files, :keystore_file, :keystore_type, :truststore_file, :truststore_type, :certificate_dn, :loglevel, :tomcat_auth, :user, :group, :tmp_dir, :lib_dir, :endorsed_dir].each do |attr| if not new_resource.instance_variable_get("@#{attr}") new_resource.instance_variable_set("@#{attr}", node['tomcat'][attr]) end end service_actions = new_resource.instance_variable_get("@service_actions") if not service_actions service_actions = node['tomcat']['service_actions'] end if new_resource.name == 'base' instance = base_instance # If they weren't set explicitly, set these paths to the default [:base, :home, :config_dir, :log_dir, :work_dir, :context_dir, :webapp_dir].each do |attr| if not new_resource.instance_variable_get("@#{attr}") new_resource.instance_variable_set("@#{attr}", node["tomcat"][attr]) end end else # Use a unique name for this instance instance = "#{base_instance}-#{new_resource.name}" # If they weren't set explicitly, set these paths to the default with # the base instance name replaced with our own [:base, :home, :config_dir, :log_dir, :work_dir, :context_dir, :webapp_dir].each do |attr| if not new_resource.instance_variable_get("@#{attr}") and node["tomcat"][attr] new = node["tomcat"][attr].sub(base_instance, instance) new_resource.instance_variable_set("@#{attr}", new) end end # Create the directories, since the OS package wouldn't have [:base, :config_dir, :context_dir].each do |attr| directory new_resource.instance_variable_get("@#{attr}") do mode '0755' recursive true end end [:log_dir, :work_dir, :webapp_dir].each do |attr| directory new_resource.instance_variable_get("@#{attr}") do mode '0755' recursive true user new_resource.user group new_resource.group end end # Don't make a separate home, just link to base if new_resource.home != new_resource.base link "#{new_resource.home}" do to "#{new_resource.base}" end end # config_dir needs symlinks to the files we're not going to create ['catalina.policy', 'catalina.properties', 'context.xml', 'tomcat-users.xml', 'web.xml'].each do |file| link "#{new_resource.config_dir}/#{file}" do to "#{node['tomcat']['config_dir']}/#{file}" end end # The base also needs a bunch of to symlinks inside it ['bin', 'lib'].each do |dir| link "#{new_resource.base}/#{dir}" do to "#{node['tomcat']['base']}/#{dir}" end end {'conf' => 'config_dir', 'logs' => 'log_dir', 'temp' => 'tmp_dir', 'work' => 'work_dir', 'webapps' => 'webapp_dir'}.each do |name, attr| link "#{new_resource.base}/#{name}" do to new_resource.instance_variable_get("@#{attr}") end end # Make a copy of the init script for this instance if node['init_package'] == 'systemd' and not platform_family?('debian') template "/usr/lib/systemd/system/#{instance}.service" do source 'tomcat.service.erb' variables ({ :instance => instance, :user => new_resource.user, :group => new_resource.group }) owner 'root' group 'root' mode '0644' end else execute "/etc/init.d/#{instance}" do command <<-EOH cp /etc/init.d/#{base_instance} /etc/init.d/#{instance} perl -i -pe 's/#{base_instance}/#{instance}/g' /etc/init.d/#{instance} EOH end end end # Even for the base instance, the OS package may not make this directory directory new_resource.endorsed_dir do mode '0755' recursive true end unless new_resource.truststore_file.nil? java_options = new_resource.java_options.to_s java_options << " -Djavax.net.ssl.trustStore=#{new_resource.config_dir}/#{new_resource.truststore_file}" java_options << " -Djavax.net.ssl.trustStorePassword=#{new_resource.truststore_password}" new_resource.java_options = java_options end case node['platform_family'] when 'rhel', 'fedora' template "/etc/sysconfig/#{instance}" do source 'sysconfig_tomcat6.erb' variables ({ :user => new_resource.user, :home => new_resource.home, :base => new_resource.base, :java_options => new_resource.java_options, :use_security_manager => new_resource.use_security_manager, :tmp_dir => new_resource.tmp_dir, :catalina_options => new_resource.catalina_options, :endorsed_dir => new_resource.endorsed_dir }) owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end when 'smartos' # SmartOS doesn't support multiple instances template "#{new_resource.base}/bin/setenv.sh" do source 'setenv.sh.erb' owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end else template "/etc/default/#{instance}" do source 'default_tomcat6.erb' variables ({ :user => new_resource.user, :group => new_resource.group, :home => new_resource.home, :base => new_resource.base, :java_options => new_resource.java_options, :use_security_manager => new_resource.use_security_manager, :tmp_dir => new_resource.tmp_dir, :authbind => new_resource.authbind, :catalina_options => new_resource.catalina_options, :endorsed_dir => new_resource.endorsed_dir }) owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end end server_xml_cookbook = node['tomcat']['server_template_cookbook'] server_xml_source = node['tomcat']['server_template_source'] template "#{new_resource.config_dir}/server.xml" do source server_xml_source cookbook server_xml_cookbook variables ({ :port => new_resource.port, :proxy_port => new_resource.proxy_port, :ssl_port => new_resource.ssl_port, :ssl_proxy_port => new_resource.ssl_proxy_port, :ajp_port => new_resource.ajp_port, :shutdown_port => new_resource.shutdown_port, :max_threads => new_resource.max_threads, :ssl_max_threads => new_resource.ssl_max_threads, :keystore_file => new_resource.keystore_file, :keystore_type => new_resource.keystore_type, :tomcat_auth => new_resource.tomcat_auth, :config_dir => new_resource.config_dir, }) owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end template "#{new_resource.config_dir}/logging.properties" do source 'logging.properties.erb' owner 'root' group 'root' mode '0644' notifies :restart, "service[#{instance}]" end if new_resource.ssl_cert_file.nil? execute 'Create Tomcat SSL certificate' do group new_resource.group command <<-EOH #{node['tomcat']['keytool']} \ -genkey \ -keystore "#{new_resource.config_dir}/#{new_resource.keystore_file}" \ -storepass "#{node['tomcat']['keystore_password']}" \ -keypass "#{node['tomcat']['keystore_password']}" \ -dname "#{node['tomcat']['certificate_dn']}" EOH umask 0007 creates "#{new_resource.config_dir}/#{new_resource.keystore_file}" action :run notifies :restart, "service[#{instance}]" end else script "create_keystore-#{instance}" do interpreter 'bash' action :nothing cwd new_resource.config_dir code <<-EOH cat #{new_resource.ssl_chain_files.join(' ')} > cacerts.pem openssl pkcs12 -export \ -inkey #{new_resource.ssl_key_file} \ -in #{new_resource.ssl_cert_file} \ -chain \ -CAfile cacerts.pem \ -password pass:#{node['tomcat']['keystore_password']} \ -out #{new_resource.keystore_file} EOH notifies :restart, "service[tomcat]" end cookbook_file "#{new_resource.config_dir}/#{new_resource.ssl_cert_file}" do mode '0644' notifies :run, "script[create_keystore-#{instance}]" end cookbook_file "#{new_resource.config_dir}/#{new_resource.ssl_key_file}" do mode '0644' notifies :run, "script[create_keystore-#{instance}]" end new_resource.ssl_chain_files.each do |cert| cookbook_file "#{new_resource.config_dir}/#{cert}" do mode '0644' notifies :run, "script[create_keystore-#{instance}]" end end end unless new_resource.truststore_file.nil? cookbook_file "#{new_resource.config_dir}/#{new_resource.truststore_file}" do mode '0644' end end service "#{instance}" do case node['platform_family'] when 'rhel', 'fedora' service_name "#{instance}" supports :restart => true, :status => true when 'debian' service_name "#{instance}" supports :restart => true, :reload => false, :status => true when 'smartos' # SmartOS doesn't support multiple instances service_name 'tomcat' supports :restart => false, :reload => false, :status => true else service_name "#{instance}" end action service_actions notifies :run, "execute[wait for #{instance}]", :immediately retries 4 retry_delay 30 end execute "wait for #{instance}" do command 'sleep 5' action :nothing end end
#!/usr/bin/ruby # Munin plugin for Mongo Collection Document Sizes require 'rubygems' require 'mongo' #get the database here db = Mongo::Connection.new("localhost",27017).db(ENV['dbname']); #check if the server is requesting a config or data if ARGV.size != 0 && ARGV[0].eql?("config") db.collection_names.each{|collection| coll = db.collection(collection) sanitized = collection.gsub('.','?') #Since Munin does not like periods here puts sanitized+".label "+ collection puts sanitized+".min 0" puts sanitized+".max 3000000" puts sanitized+".draw LINE1" puts sanitized+".type GAUGE" puts sanitized+".info Number of documents in " + collection } puts "graph_title MongoDB Collections in #{ENV['dbname']}" puts "graph_args --base 1000" puts "graph_vlabel documents" puts "graph_category MongoDB" else #output the data here db = Mongo::Connection.new("localhost",27017).db(ENV['dbname']); db.collection_names.each{ |collection| coll = db.collection(collection) puts collection.gsub('.','?')+'.value '+coll.count.to_s } end #Add this to your /etc/munin/plugin-conf.d/munin-node #[mongo*] #env.dbname test #Replace test with your database name! Removed an extra call to Connection::new #!/usr/bin/ruby # Munin plugin for Mongo Collection Document Sizes require 'rubygems' require 'mongo' #get the database here db = Mongo::Connection.new("localhost",27017).db(ENV['dbname']); #check if the server is requesting a config or data if ARGV.size != 0 && ARGV[0].eql?("config") db.collection_names.each{|collection| coll = db.collection(collection) sanitized = collection.gsub('.','?') #Since Munin does not like periods here puts sanitized+".label "+ collection puts sanitized+".min 0" puts sanitized+".max 3000000" puts sanitized+".draw LINE1" puts sanitized+".type GAUGE" puts sanitized+".info Number of documents in " + collection } puts "graph_title MongoDB Collections in #{ENV['dbname']}" puts "graph_args --base 1000" puts "graph_vlabel documents" puts "graph_category MongoDB" else #output the data here db.collection_names.each{ |collection| coll = db.collection(collection) puts collection.gsub('.','?')+'.value '+coll.count.to_s } end #Add this to your /etc/munin/plugin-conf.d/munin-node #[mongo*] #env.dbname test #Replace test with your database name!
jc: update 1.15.0 bottle.
jobs = [ "trigger", "commit", "acceptance", "capacity", "exploratory", "preproduction", "production", "jenkins-test"] params = jobs.collect { |job| { :name => job, :source => "#{job}-config.xml.erb", :target => "/var/tmp/#{job}-config.xml" } } params.each do |param| template param[:target] do source param[:source] variables( { :source_repo => node['pipeline']['source'] } ) end jenkins_job param[job] do action :create config param[source] end end lets see if this works. jobs = [ "trigger", "commit", "acceptance", "capacity", "exploratory", "preproduction", "production", "jenkins-test"] params = jobs.collect { |job| { :name => job, :source => "#{job}-config.xml.erb", :target => "/var/tmp/#{job}-config.xml" } } params.each do |param| template param[:target] do source param[:source] variables( { :source_repo => node['pipeline']['source'] } ) end jenkins_job param[job] do action :create config param[source] end end